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,服务被销毁。
相关文章推荐
- 第一行代码 第10章 服务 -- 前台服务与IntentService
- 深入理解Service(三)——前台服务和IntentService
- Android之服务(四)前台服务
- 前台服务
- Android服务——前台服务
- 使用startForeground让android服务前台运行
- android服务- Notification创建通知 - startForeground 使用前台服务
- 使用startForeground让android服务前台运行
- android如何让后台服务service不被杀死(设置前台服务)
- Android Service---在前台运行服务
- 安卓开发40:使用startForeground让android服务前台运行
- 前台服务
- 让服务成为前台服务,即使在低内存也不会被杀掉
- IntentService----意图服务
- 使用startForeground让android服务前台运行
- asp.net前台.aspx与Web服务.asmx的数据交互
- startForeground()让服务保持前台级别
- Service的使用(二)启动服务与IntentService
- Android_Service(2)前台服务(service)和远程服务(service)
- 使用.net core ABP和Angular模板构建博客管理系统(完善前台服务)