首页 > 系统 > Android > 正文

浅谈Android Service服务的高级技巧

2019-10-21 21:48:09
字体:
来源:转载
供稿:网友

1 前台服务

因为服务的优先级较低,所以当系统内存不足时,可能会回收正在后台运行的服务。如果若要避免服务被回收,可以使用前台服务。

前台服务会一直有一个图标在系统的状态栏中显示,下拉状态栏可以看到更加详细的信息,类似于消息通知效果。

public class FirstService extends Service {  private static final String TAG = "FirstService";  @Override  public void onCreate() {    super.onCreate();    Log.d(TAG, "onCreate");    //设置为前台服务    Intent intent = new Intent(this, MainActivity.class);    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);    Notification notification = new NotificationCompat.Builder(this)        .setContentTitle("梅西生涯最大尴尬 战法国能否破荒?")        .setContentText("世界杯1/8决赛,法国对阵阿根廷,法国队主帅德尚将迎来80战里程碑,成为队史执教场次最多的主教练,高卢雄鸡能否保持过去40年世界杯遇南美球队不败的金身,格里兹曼能否找回最佳状态,梅西能否打破此前世界杯淘汰赛666分钟的进球荒,都是此役的关键看点。")        .setWhen(System.currentTimeMillis())        .setSmallIcon(R.mipmap.ic_launcher)        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))        .setContentIntent(pendingIntent)        .build();    startForeground(1,notification);  }}

在此构建出通知对象(Notification)之后,调用 startForeground() 让当前服务变为一个前台服务。

startForeground 接收两个参数:

 

参数 说明
id 通知 ID
Notification Notification 对象

 

效果:

Android,Service,高级技巧

2 IntentService

如果在服务中处理耗时操作,那么容易出现 ANR(Application Not Responding)问题。

为了避免我们可以在主服务的具体方法中开启子线程,然后在子线程中来执行耗时操作,形如:

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {  Log.d(TAG, "onStartCommand");  //在子线程中来执行耗时操作  new Thread(new Runnable() {    @Override    public void run() {      //耗时操作    }  }).start();  return super.onStartCommand(intent, flags, startId);}

这样的服务一旦启动后,就会一直处于运行状态,直到调用 stopService() 或者 stopSelf() 才会停止服务。我们可以在耗时操作执行完毕后,调用 stopSelf() ,让服务自行停止:

new Thread(new Runnable() {  @Override  public void run() {    //耗时操作     stopSelf();  }}).start();

Android 提供了 IntentService 类,可以直接创建一个异步、执行完毕会自行结束的服务。

我们新建一个类,让它继承自 IntentService :

public class SecondService extends IntentService {  private static final String TAG = "SecondService";  public SecondService() {    super("SecondService");  }  @Override  protected void onHandleIntent(Intent intent) {    Log.d(TAG, "子线程 id(Intent 服务): " + Thread.currentThread().getId());    //在此执行耗时逻辑  }  @Override  public void onDestroy() {    super.onDestroy();    Log.d(TAG, "onDestroy");  }}

注意:这个类必须提供一个无参构造函数,并且必须在这个构造函数内部调用父类的有参构造函数。

接着,在活动类中启动 Intent 服务:

Log.d(TAG, "主线程 id: " + Thread.currentThread().getId());Intent intentService = new Intent(context, SecondService.class);startService(intentService);

输出结果:

D/MainActivity: 主线程 id: 1
D/SecondService: 子线程 id(Intent 服务): 145
D/SecondService: onDestroy

从结果中可以看出,IntentService 服务类开启了一个新的线程来执行耗时逻辑,并且在执行完毕后自动停止。是不是很方便呀O(∩_∩)O哈哈~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表