Android Service的使用介绍

2019-05-19  本文已影响0人  dashingqi

简介

服务的开启方式
两种方式
两种方式的区别(和生命周期一起分析)
混合开启服务

接着观察生命周期方法,先执行unbindService()方法时执行了解绑服务的操作,当调用stopService()才将服务给销毁了。

bindService() --> startService()

start2.jpg
* 接着我们配合这种开启方式,去关闭服务
stopService()-->unbindService()
stop2-1.jpg

unbindService()-->stopService()

stop2-2.jpg

服务与Activity之间的通信方式

  public interface MyInterface {
      void get();
      void getMethod();
    }
class MyBinder extends Binder {

      public ServiceLifeMethod getService(){
          return ServiceLifeMethod.this;
      }
  }
  private MyInterface myInterface;
  public void addCallBack(MyInterface myInterface){
      this.myInterface = myInterface;
  }
  @Override
  public void onDestroy() {
      Log.d(TAG, "onDestroy: ");
      super.onDestroy();
      myInterface.get();
  }

 public class MainActivity extends AppCompatActivity  implements MyInterface
 
 @Override
   public void get() {
       //Service的onDestroy()发放得到执行
       Log.d(TAG, "get: onDestroy方法得到执行");
   }

   @Override
   public void getMethod() {

   }
 private ServiceConnection mServiceConnection = new ServiceConnection() {
       @Override
       public void onServiceConnected(ComponentName name, IBinder service) {
           ServiceLifeMethod.MyBinder myBinder = (ServiceLifeMethod.MyBinder) service;
           Log.d(TAG, "onServiceConnected: ");
           ServiceLifeMethod myBinderService = myBinder.getService();
           myBinderService.addCallBack(MainActivity.this);

       }

       @Override
       public void onServiceDisconnected(ComponentName name) {
           Log.d(TAG, "onServiceDisconnected: ");

       }
   };
 bindService.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               bindIntent = new Intent(MainActivity.this, ServiceLifeMethod.class);
               // Context.BIND_AUTO_CREATE 表示 活动和服务进行绑定后自动创建服务 使得onCreate方法得到执行,onStartCommand方法不会执行
               bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

           }
       });

服务的使用场景

  1. 音乐的播放
  2. 下载

问题记录

如何保证Service不被杀死
上一篇 下一篇

猜你喜欢

热点阅读