使用前台服务
对于系统而言,服务的优先级还是比较低的,服务几乎都是在后台运行的。所以,如果内存警告的话,系统会去回收服务的这部分内存,终止服务的执行。有时候我们希望服务能够一直保持一个运行的状态,这个时候就可以考虑使用前台服务。
怎样才能创建一个前台服务呢?其实很简单。
我们需要在MyService的onCreate() 方法中:
//服务在创建的时候调用的方法
@Override
public void onCreate() {
Log.d("MyService","onCreate()-------");
super.onCreate();
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
Notification notification =new NotificationCompat.Builder(this,"channelId")
.setContentTitle("哈哈")
.setContentText("内容")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher_round))
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
}
在这里我们构建了Notification之后,调用startForeground()方法让MyService成为了一个前台服务。方法中第一个参数是Notification的id,第二个参数是我们构建的Notification对象。这个时候运行程序,启动MyService,MyserVice就作为一个前台服务运行了,我们可以在通知栏或者状态栏查看。
IntentService
通过前面我们对服务的了解,服务大多都是在主线程执行的,但是往往一些复杂的业务逻辑又不能直接在主线程中执行。这个是后续就需要开启子线程来实现操作。
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService","onStartCommand()-------");
new Thread(new Runnable() {
@Override
public void run() {
//执行复杂的逻辑
}
});
return super.onStartCommand(intent, flags, startId);
}
知道这种服务一旦启动就会处于运行状态,必须调用stopSelf()或者stopService()才能让其停下来。如果要让一个服务在执行完毕之后自动停下来 可以执行如下操作。
public void run() {
stopSelf();
}
为了可以简单的创建一个异步的 能够自动停止的服务 Android专门有一个类IntentService。IntentService类就很好的解决了上述两种问题。
那么怎么使用IntentService呢?
1、创建一个类MyIntentService继承自IntentService
2、在MyIntentService内实现如下方法
public class MyIntentService extends IntentService {
public MyIntentService(){
super("MyIntentService");//调用父类的有参构造方法
}
//onHandleIntent抽想方法 可以处理一些具体的逻辑 这个方法默认的是在子线程中执行
//这个方法在运行完成之后是自动停止的
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//打印当前线程的id
Log.d("MyIntentService","Thread id is"+ Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService","onDestroy() run");
}
}
上述方法中并没有特别的逻辑代码,方便测试,我们只是打印了一下当前服务运行的线程id。倘若线程销毁的话必定会调用onDestroy() 方法,打印日志。
接下来我们在MainActivity中实现点击一个按钮来启用IntentService
intent_servece.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivity","Threa is "+ Thread.currentThread().getId());
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
startService(intent);
}
});
另外需要注意一点IntentService的注册是普通的Service一样。需要在AndroidMinafest.xml中注册。

运行程序之后我们可以看到上面所示的打印结果。由此验证了我们前面所说的:IntentService能创建一个异步的 能够自动停止的服务。
网友评论