定义一个服务
重写onCreate()、onStartCommand()、onDestroy()这三个方法,onCreate()方法会在服务创建时调用,onStartCommand()方法会在每次服务启动时调用,onDestroy()方法会在服务销毁时调用。当我们希望服务一启动就执行某种操作只需要将逻辑写在onStartCommand()方法中。每一个服务都需要在AndroidManifest.xml文件中注册,注册形式如下
<service android:name=".MyService" >
</service>
启动和停止服务
构建Intent对象调用startService()和stopService()来执行和停止MyService,也可以任意位置调用stopSelf()方法让服务停止
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务
活动和服务的进行通信
创建一个ServiceConnection的匿名类,重写onServiceConnected()方法和onServiceDisconnected()方法,分别于活动和服务成功绑定以及解绑时调用,可以根据具体场景调用DownloadBinder中任何public方法。构建Intent对象,调用bindService()方法将activity与service进行绑定。bindService()方法接收三个参数,第一个参数就是刚刚创建的Intent对象,第二个参数是前面创建的ServiceConnection实例,第三个参数则是一个标识位,这里传入BIND_AUTO_CREATE表示在活动和服务进行绑定后自动创建服务。这会使得MyService中onCreate()方法得到执行,但onStartCommand()方法不会执行。解绑只需要调用unbindService()方法。
服务生命周期
-
启动类型的服务: onCreate()- >onStartCommand()->Service running–调用context.stopService() ->onDestroy()
-
绑定类型的服务: onCreate()->onBind()->Service running–调用>onUnbind() -> onDestroy()
使用前台服务
public class MyService extends Service {
……
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,
"Notification comes", System. currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "This is title", "This is content", pendingIntent);
startForeground(1, notification);
Log.d("MyService", "onCreate executed");
}
……
}
构建Notification对象调用startForeground()方法,第一个参数是通知的id,第二个参数时构建出的Notification对象。调用startForeground()方法会让MyService变成一个前台服务
使用IntentService
服务中的代码默认运行在主线程中,如果直接在服务里处理一些耗时的逻辑,很容易出现ANR。所有应在每个具体方法开启子线程处理耗时逻辑。服务一旦启动就会一直处于运行状态,必须调用stopService()或者stopSelf()方法让服务停下来。
android提供一个可以简单创建异步的、会自动停止的服务的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");
}
}
首先提供一无参的构造函数,并且必须在其内部调用父类的有参构造函数。在子类中实现onHandlerIntent()这个抽象方法,在这个方法中可以处理一些具体的逻辑而不用担心ANR