Service

服务的基本用法

www.androiddevtools.cn

定义一个服务

  • 新建一个MyService类继承Service

      public class MyService extends Service {
      	@Override
      	public IBinder onBind(Intent intent) {
      		return mBinder;
      	}
      }
    
  • 重写Service中的onCreate、onStartCommand、onDestroy方法并写入打印log方法。

  •   @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
      	Log.i(TAG, "onStartCommand: onStartCommand executed");
      	return super.onStartCommand(intent, flags, startId);
      }
    
      @Override
      public void onCreate() {
      	super.onCreate();
      	Log.i(TAG, "onCreate: onCreate executed");
      }
    
      @Override
      public void onDestroy() {
      	Log.i(TAG, "onDestroy: onDestroy executed");
      	super.onDestroy();
      }
    
  • 在Manifest文件的application结点中注册服务

      <service android:name=".MyService"/>
    

这样服务就完全定义好了,接下来开始运用。

启动和停止服务

  • 在activity_main.xml中加入两个Button

  • 在MainActivity中设置两个按钮的监听

      public class MainActivity extends AppCompatActivity implements OnClickListener {
          private Button mStartService,mStopService;
    
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              mStartService = (Button) findViewById(R.id.startService);
              mStopService = (Button) findViewById(R.id.stopService);
              mStartService.setOnClickListener(this);
              mStopService.setOnClickListener(this);
          }
      
          @Override
          public void onClick(View view) {
              switch (view.getId()){
                  case R.id.startService:
                      Log.i(TAG, "onClick: StartService");
                      Intent startIntent = new Intent(MainActivity.this,
      						MyService.class);
                      startService(startIntent); //启动服务
                      break;
                  case R.id.stopService:
                      Log.i(TAG, "onClick: StopService");
                      Intent stopIntent = new Intent(MainActivity.
      						this,MyService.class);
                      stopService(stopIntent); //停止服务
                      break;
                  default:
                      break;
              }
          }
      }
    
  • 当点击startService时会打印onCreate和onStartCommand方法中的log,而点击stopService时会打印onDestroy的log

  • onCreate方法在服务第一次创建时候的时候调用

  • onStartCommand方法在每次启动服务的时候调用
    > 多次点击startService时只会调用一次onCreate,但会多次调用onStartCommand方法

活动和服务进行通信

  • 在MyService中创建一个内部类DownloadBinder继承Binder,重写onBind方法

    DownloadBinder中的方法是两个模拟方法,没有实际用途,通过打印log证明实现过该方法

      private DownloadBinder mBinder = new DownloadBinder();
      
      public class DownloadBinder extends Binder {
          public void startDownload() {
              Log.i(TAG, "startDownload: startDownload executed");
          }
    
          public int getProgress() {
              Log.i(TAG, "getProgress: getProgress executed");
              return 0;
          }
    
      }
      @Override
      public IBinder onBind(Intent intent) {
          return mBinder;
      }
    
  • 在activity_main.xml中再追加两个Button

  • 在MainActivity中创建一个ServiceConnection,重写其中的两个方法

      private MyService.DownloadBinder mBinder;
      private ServiceConnection mConnection = new ServiceConnection() {
          @Override
          public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
              mBinder = (MyService.DownloadBinder) iBinder;
              mBinder.startDownload();
              mBinder.getProgress();
          }
    
          @Override
          public void onServiceDisconnected(ComponentName componentName) {
    
          }
      };
    
  • 绑定新Button,并添加onClickListener方法

      mBindService = (Button) findViewById(R.id.bindService);
      mUnbindService = (Button) findViewById(R.id.unbindService);
      mBindService.setOnClickListener(this);
      mUnbindService.setOnClickListener(this);
    
  • 在onClick中追加两个case

      case R.id.bindService:
          Intent bindIntent = new Intent(this,MyService.class);
          bindService(bindIntent, mConnection, BIND_AUTO_CREATE);//绑定服务
          break;
      case R.id.unbindService:
          unbindService(mConnection);//解绑服务
          break;
    

bindService方法接收三个参数,
第一个参数是刚创建的Intent对象,
第二个是ServiceConnect的实例,
第三个参数是一个标志位,
传入的BIND_AUTO_CREATE表示在活动和服务进行绑定后自动创建服务。
如果不进行创建服务而直接绑定会导致程序崩溃。

服务的生命周期

  • 如果调用了startService方法,相应的服务就会启动并且回调onStartCommand方法,
    如果服务没有被创建,onCreate方法会优先于onStartCommand方法执行。
  • 服务启动后会一直执行,直到stopService方法被调用。
  • 每次调用startService方法,都会执行一次onStartCommand方法,
    但是onCreate方法只会执行一次。所以只需要调用一次stopService方法,
    服务就会停止。
  • 可以调用bindService方法绑定服务,这样会回调服务中的onBind方法。
    如果服务之前没被创建过,会优先调用onCreate方法。
  • 用unBindService方法可以解除绑定。
  • 如果同时调用了startService方法和bindService方法,根据Android 系统的机制,
    一个服务只要被启动或者被绑定了之后,就会一直处于运行状态,
    必须要让以上两种条件同时不满足,服务才能被销毁。所以要同时调用stopService()
    和unbindService()方法,onDestroy()方法才会执行。

使用前台服务

  • 修改MyService的onCreate方法

      NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
      builder.setSmallIcon(android.R.drawable.sym_def_app_icon);
      builder.setContentTitle("Notification Title");
      builder.setContentText("Notification comes");
      Notification notification = builder.build();
      startForeground(1, notification);
    
  • 调用了startForeground()方法会让MyService变成一个前台服务并且显示到系统状态栏,
    使用方式与notify()方法相似。

使用IntentService

  • 创建一个MyIntentService继承IntentService,要求重构onHandleIntent方法和构造方法

      public class MyIntentService extends IntentService{
          private static final String TAG = "MyIntentService";
      
          public MyIntentService() {
              super("MyIntentService");
          }
      
          @Override
          protected void onHandleIntent(Intent intent) {
              // 打印当前线程的ID
              Log.i(TAG, "onHandleIntent: Thread id is " + Thread.currentThread().getId());
          }
      }
    
  • 在Manifest文件中注册MyIntentService

      <service android:name=".MyIntentService"/>
    
  • 在activity_main.xml中追加一个Button

  • 在MainActivity中绑定Button并添加onClickListener。

  • 在case中追加

      case R.id.start_intent_service:
              Log.i(TAG, "onClick: Thread id is "+Thread.currentThread().getId());
              Intent intentService = new Intent(this,MyIntentService.class);
              startService(intentService);
              break;
    

相关代码

以上程序的相关代码

原文地址:https://www.cnblogs.com/clevergirl/p/5689508.html