说说 Android 服务的高级技巧

作者 : 开心源码 本文共2250个字,预计阅读时间需要6分钟 发布时间: 2022-05-11 共84人阅读

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
NotificationNotification 对象

效果:

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哈哈~

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 说说 Android 服务的高级技巧

发表回复