说说 Android 服务的高级技巧

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)问题。

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

@Override
public 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哈哈~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值