服务:在后台运行,没有界面的组件。

服务生命周期如下:

两种启动方式:

1、startService(): onCreate()-->onStartCommand()-->onDestroy().
2、bindService():  onCreate()-->onBind()-->onUnbind()-->onDestroy().

一、定义一个服务,得做到以下:

1.继承Service,重写onBind()、onCreate()、onStartCommand()和 onDestroy();

2.在AndroidManifest里面注册才能生效.

二、启动服务:

Intent startIntent=new Intent(this,MyService.class);

startService(startIntent);

三、停止服务:

Intent stopIntent=new Intent(this,MyService.class);
stopService(stopIntent);

四、绑定服务:

1.onBind()方法返回Binder对象;

2.创建了ServiceConnection 的匿名类,重写onServiceConnected()方法和 onServiceDisconnected()方法;

3.用bindService()方法将 Activity 和 Service 进行绑定。

bindService()方法接收三个参数,第一个参数就是 Intent 对象,第二个参数是ServiceConnection 的实例,第三个
参数则是一个标志位,可以传入 BIND_AUTO_CREATE 表示在活动和服务进行绑定后自动创建服务。

示例如下:

Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);

五、解绑服务:

unbindService(connection);

六、使用IntentService

优点:

1.异步,可以在子线程处理耗时操作

2.执行完毕自动停止

代码示例如下:

MainActivity.java

package com.example.servicedemo;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity implements OnClickListener {
    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;
    private MyService.DownloadBinder downloadBinder;
    private Button startIntentService;
    private boolean mIsBound =false;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            downloadBinder=(MyService.DownloadBinder)service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }         @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService=(Button)findViewById(R.id.start);
        stopService=(Button)findViewById(R.id.stop);
        bindService = (Button) findViewById(R.id.bind_service);
        unbindService = (Button) findViewById(R.id.unbind_service);
        startIntentService = (Button) findViewById(R.id.start_intent_service);
        startIntentService.setOnClickListener(this);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }     @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()) {
          case R.id.start:
              Intent startIntent=new Intent(this,MyService.class);
              startService(startIntent);
              
             break;
          case R.id.stop:  
              Intent stopIntent=new Intent(this,MyService.class);
              stopService(stopIntent);
             break;
          case R.id.bind_service:   
              Intent bindIntent = new Intent(this, MyService.class);
              bindService(bindIntent,connection,BIND_AUTO_CREATE);//绑定服务
              mIsBound = true;
              break;
          case R.id.unbind_service:  
              if(mIsBound) {
                 unbindService(connection);  //解绑服务
                 Log.d("MainActivity","UnbindService");
                 mIsBound=false;
              }
            
              break;
          case R.id.start_intent_service:
                Log.d("MainActivity","Thread id is "+Thread.currentThread().getId());
                Intent intentService=new Intent(this,MyIntentService.class);
                startService(intentService);
                break;
          default:
              break;
        }
    }     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
   
}

MyService.java:

package com.example.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service{
private DownloadBinder mBinder = new DownloadBinder();
//继承Binder的内部类,一个方法开始下载,另一个方法获取进度
class DownloadBinder extends Binder {
public void startDownload() {
Log.d("MyService", "startDownload executed");
}
public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}
} @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
} public void onCreate(){
super.onCreate();
Log.d("MyService","onCreate executed");
} public int onStartCommand(Intent intent,int flags,int startId){
Log.d("MyService","onStartCommand executed");
return super.onStartCommand(intent,flags,startId); } public void onDestroy(){
Log.d("MyService","onDestroy executed");
super.onDestroy();
} }

MyIntentService.java:

package com.example.servicedemo;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log; public class MyIntentService extends IntentService{ public MyIntentService() {
super("MyIntentService");
// TODO Auto-generated constructor stub
} @Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.d("MyIntentService", "Thread id is " + Thread.currentThread().
getId());
} public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/start"
android:text="start service" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/stop"
android:text="stop service"
android:layout_below="@id/start"
/> <Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind Service"
android:layout_below="@id/stop" />
<Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Unbind Service"
android:layout_below="@id/bind_service" /> <Button
android:id="@+id/start_intent_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start IntentService"
android:layout_below="@id/unbind_service" /> </RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicedemo"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.servicedemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
></service>
<service android:name=".MyIntentService"></service>
</application> </manifest>

运行效果如下所示:

start Service:

多次start Service:

Bind Service:

start IntentService:

android笔记:Service的更多相关文章

  1. Android笔记二十七.Service组件入门(一).什么是Service?

    转载请表明出处:http://blog.csdn.net/u012637501(嵌入式_小J的天空) 一.Service 1.Service简单介绍     Service为Android四大组件之中 ...

  2. Android 学习笔记 Service服务与远程通信...(AIDL)

    PS:这一章节看的我有几分迷茫,不是很容易理解...不过还好总算是明白了一大半了...基本的迷惑是解决了... 学习内容: 1.跨应用启动服务... 2.跨应用绑定服务... 3.跨应用实现通信... ...

  3. Android 学习笔记 Service

    PS:前几篇的内容光是上代码了,也没有细细的讲解..感觉这样写很不好..因此还是多一些讲解吧... 学习内容: 1.了解Service... 2.Service的启动与停止.. 3.绑定与取消绑定Se ...

  4. Android笔记三十四.Service综合实例二

    综合实例2:client訪问远程Service服务 实现:通过一个button来获取远程Service的状态,并显示在两个文本框中. 思路:如果A应用须要与B应用进行通信,调用B应用中的getName ...

  5. Android笔记(五十九)Android总结:四大组件——Service篇

    什么是服务? 服务(service)是Android中实现程序后台运行的解决方案,适用于去执行那些不需要和用户交互并且还需要长期运行的任务.服务的运行不依赖于任何用户界面. 服务运行在主线程中,所以在 ...

  6. Android笔记(十七) Android中的Service

    定义和用途 Service是Android的四大组件之一,一直在后台运行,没有用户界面.Service组件通常用于为其他组件提供后台服务或者监控其他组件的运行状态,例如播放音乐.记录地理位置,监听用户 ...

  7. android服务Service(上)- IntentService

    Android学习笔记(五一):服务Service(上)- IntentService 对于需要长期运行,例如播放音乐.长期和服务器的连接,即使已不是屏幕当前的activity仍需要运行的情况,采用服 ...

  8. Android:Service

    Android Service: http://www.apkbus.com/android-15649-1-1.html android service 的各种用法(IPC.AIDL): http: ...

  9. android 远程Service以及AIDL的跨进程通信

    在Android中,Service是运行在主线程中的,如果在Service中处理一些耗时的操作,就会导致程序出现ANR. 但如果将本地的Service转换成一个远程的Service,就不会出现这样的问 ...

随机推荐

  1. JavaScript中的继承模式总结(九)

    一.总结: //js中的几种继承 //原型链的问题,包含引用类型的原型属性会被实例共享,子类型无法给超类型传递参数 function SuperType() { this.colors = [&quo ...

  2. bzoj 3978: [WF2012]Fibonacci Words

    Description 斐波那契01字符串的定义如下 F(n) = { 0  if n = 0 1  if n = 1 F(n-1)+F(n-2) if n >= 2 } 这里+的定义是字符串的 ...

  3. 2018-2019 20165226 网络对抗 Exp1+ 逆向进阶

    2018-2019 20165226 网络对抗 Exp1+ 逆向进阶 目录 一.实验内容介绍 二.64位shellcode的编写及注入 三.ret2lib及rop的实践 四.问题与思考 一.实验内容介 ...

  4. MySQL Binlog三种格式介绍及分析

    Mysql binlog日志有三种格式,分别为Statement,MiXED,以及ROW! 1.Statement:每一条会修改数据的sql都会记录在binlog中. 优点:不需要记录每一行的变化,减 ...

  5. [UE4]创建多把枪,使用Class,参数的对象类型

    先来说说函数输入参数的区别: 1.Object Reference 2.Class Reference 会出现可以让你选择一个类 3.Soft Object Reference 4.Soft Clas ...

  6. make menuconfig时出现 #include CURSES_LOC错误

    In :: scripts/kconfig/lxdialog/:: fatal error: curses.h: 没有那个文件或目录 #include CURSES_LOC ^ compilation ...

  7. 【Python编程:从入门到实践】chapter6 字典

    chapter6 字典 6.1 一个简单的字典 6.2 使用字典 6.2.1 访问字典中的值 6.2.2 添加键值对 6.2.3 先创建一个空字典 6.2.4 修改字典中的值 6.2.5 删除键值对 ...

  8. Solr --- Group查询与Facet区别

    简介 facet的查询结果主要是分组信息:有什么分组,每个分组包括多少记录:但是分组中有哪些数据是不可知道的,只有进一步搜索. group则类似于关系数据库的group by,可以用于一个或者几个字段 ...

  9. Executor框架(七)Future 接口、FutureTask类

    Future接口介绍   Future 表示异步计算的结果.它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果.   Future 一般由 ExecutorService 的submi ...

  10. paycharm导入webdriver包报错:module 'selenium.webdriver' has no attribute 'Firefox'

    首先:试试看在cmd中试试输入from selenium import webdriver,看是否报错,看一看是不是pycharm的原因.经过确认,在dos窗口中输入导入包的命令并没有报错.最后我重现 ...