版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一、Service 是长期运行在后台的应用程序组件。默认情况下是和主线程绑定的,所以当我们在onStartCommand方法进行一些耗时操作时容易发生异常,所以android提供了IntentService给我们,它默认会开启一个新的线程执行我们的任务,当任务执行完毕后会主动关闭service.
实现方式:
1.继承IntentService
2.重写它的onHandleIntent方法
3.添加一个构造函数返回service名
/**
* @Author: david.lvfujiang
* @Date: 2019/10/21
* @Describe:
*/
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
}
二、当后台运行很多service时,如果系统出现内存不足则会杀死部分服务,但我有些服务我们不想被杀掉的时候我们可以设置
1. 提高Service的优先级:
2.把service写成系统服务,将不会被回收:
3.将服务改成前台服务foreground service:
前台service实现方式:调用startForeground给service添加一个通知栏
/**
* @Author: david.lvfujiang
* @Date: 2019/10/21
* @Describe:
*/
public class MyService extends Service {
String serviceName = "MyService";
Notification notification;
public String getServiceName() {
return serviceName;
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCreate() {
super.onCreate();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("哈哈哈", "hahh");
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
//判断是否是8.0Android.O
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan1 = new NotificationChannel("static", "Primary Channel", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(chan1);
builder = new NotificationCompat.Builder(this, "static");
} else {
builder = new NotificationCompat.Builder(this);
}
builder.setDefaults(NotificationCompat.DEFAULT_SOUND);//设置通知铃声
notification = builder.setTicker("您有新的消息")
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("下载")
.setProgress(100, 0, false)
.setAutoCancel(true)
.build();
startForeground(110, notification);
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
class MyBinder extends Binder {
public Service getService() {
return MyService.this;
}
}
}