Android-Service

1、服务(Service)是 Android 中实现程序后台运行的解决方案,它适合用于去执行那些不需要和用户交互而且还要求长期运行的任务;

2、服务并不是运行在一个独立的进程当中的,当其所在程序的进程被杀掉时,服务也将停止;

3、服务的基本用法:

  1)创建一个子类继承自 Service 类,并重写 onBind() 抽象方法;

  2)重写 Service 类的一些方法,常用的有:

    --onCreate(): 服务被创建时调用;

    --onStartCommand():在每次服务启动的时候调用;

    --onDestroy():在服务销毁的时候调用;

  3)AndroidManifest.xml 文件中对 Service 进行注册;<service android:name=".MyService" />

  4)创建并注册完毕之后,可以在 Activity 中通过 Intent 来启动或停止服务;

    --启动服务:

Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务

    --停止服务:

Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务

  5)还可以通过在 Service 中任何位置调用 stopSelf() 来停止服务;

4、Activity 与 Service 的通信:

  1)创建一个 Binder 对象来管理 Service 中的数据或方法,并让 onBind() 方法返回值为创建的 Binder 对象;

  2)在 Activity 里面通过 bindService() 方法与 Service 进行绑定,该方法有三个参数:

    --第一个参数为 Intent 对象,表示要启动的服务的 intent;

    --第二个参数为 ServiceConnection 对象,该对象中包含该两个方法:onServiceConnected() 和 onServiceDisconnected(),他们分别在 Activity 与 Service 连接和断开连接时调用,其中带有 Service 中 onBind() 方法返回的 Binder 对象,这里我们就可以获取它并操作 Service 的中的数据或方法;

    --第三个参数是一个标志位,传入BIND_AUTO_CREATE 表示在 Activity 和 Service 进行绑定后自动创建服务;

  3)绑定之后就可以在 Activity 中获取到 Service 中的 Binder 对象,从而与 Service 进行通信;

  4)在 Activity 中调用 unbindService() 方法即可解除绑定,该方法只需传入 ServiceConnection 对象即可;

5、Service 的生命周期:

  

6、前台服务:在 Service 中调用startForeground() 方法后就会让当前服务变为一个前台服务,它有两个参数:

  1)第一个参数类似于 NotificationManager 中 notify() 方法的第一个参数,是一个 Id;

  2)第二个参数为一个 Notification 对象,它将会显示在系统状态栏中;

7、服务的通常用法:

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 处理具体的逻辑
                stopSelf();//这里加上这一句的目的是使得当前服务能够在线程执行完毕时自动停止,否则服务将会一直运行
           }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
}

8、上面这种写法通常容易忘记开启线程或者在线程中关闭服务,因此 Android 专门提供了一个 IntentService 类,它的基本用法如下:

  1)新建一个MyIntentService 类继承自IntentService;

public class MyIntentService extends IntentService {
    public MyIntentService() {
        super("MyIntentService"); // 调用父类的有参构造函数
    }
    @Override
    protected void onHandleIntent(Intent intent) {
    // 打印当前线程的id
      Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService", "onDestroy executed");
    }
}

  2)重写 onHandleIntent() 方法,在这个方法中可以去处理一些具体的逻辑,而且不用担心ANR(Application Not Responding)的问题,因为这个方法已经是在子线程中运行的了;

  3)根据IntentService的特性,这个服务在运行结束后应该是会自动停止的;

 

posted on 2016-03-16 16:20  _taoGe  阅读(179)  评论(0编辑  收藏  举报