您的位置:首页 > 移动开发 > Android开发

Android读书笔记(八) 前台服务、IntentService

2017-11-09 15:28 471 查看

1.前台服务

  当系统内存不足时,有可能会回收掉服务。如果你想服务一直保持运行状态,不会因内存不足而被回收,可以使用前台服务。常见的前台服务,音乐播放器,一个通知中有几个按钮,音乐不停,此通知就不消失。

  前台服务最明显的地方是,有一个类似与通知显示在状态栏中。

//实现代码
public class MyService extends Service {
@Override
public void onCreate() {

Intent intent = new Intent(this, ABCActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("前台服务标题")
.setContentText("前台服务内容")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources()
, R.mipmap.ic_launcher))
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}


  上面展示代码其实就是在Service中创建了一个通知。只不过显示通知的方法有所不同,使用了startForeground()方法,参数一是通知的id,参数二是Notification对象。

//开启前台服务
Intent intent = new Intent(ABCActivity.this, MyService.class);
startService(intent);


2.IntentService

特点:异步、自动停止

  当在服务中需要处理一些耗时的任务,并且完成后自动停止。IntentService非常适合这样的场合,耗时的任务在onHandleIntent()中进行,因为onHandleIntent()方法中代码运行在子线程中。下面展示一下代码。

public class MyIntentService extends IntentService {

public MyIntentService() {
super("MyIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {

Log.i("123123","Thread id is" + Thread.currentThread().getId());
}

@Override
public void onDestroy() {
Log.i("123123", "onDestroy");

}
}


  启动方式与上面的一样,这里就不贴代码了。打印的结果:

11-02 16:48:35.370 3247-3247/cn.xd.study I/123123: Thread id is1
11-02 16:48:35.375 3247-3296/cn.xd.study I/123123: Thread id is142
11-02 16:48:35.384 3247-3247/cn.xd.study I/123123: onDestroy


  1是主线程,142是子线程,最后onDestroy,服务被销毁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息