1.什么是前台服务
前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不容许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有这个服务被终止或从前台主动移除通知后才能被解除。
2.为什么使用
在一般情况下,Service几乎都是在后台运行,一直默默地做着辛苦的工作。但这种情况下,后台运行的Service系统优先级相对较低,当系统内存不足时,在后台运行的Service就有可能被回收。
那么,如果我们希望Service可以一直保持运行状态且不会在内存不足的情况下被回收时,可以选择将需要保持运行的Service设置为前台服务。
3.如何实现
<Button
android:onClick="Startfor"
android:text="开启前台服务"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
public void Startfor(View view) {
Intent intent = new Intent(this,MyService.class);
startService(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.item);
remoteViews.setTextViewText(R.id.tv1,"落霞与孤鹜齐飞");
remoteViews.setTextViewText(R.id.tv2,"秋水共长天一色");
remoteViews.setImageViewResource(R.id.iv1,R.drawable.ic_launcher_background);
Intent intent1 = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,101,intent1,PendingIntent.FLAG_CANCEL_CURRENT);
Notification.Builder builder=new Notification.Builder(MyService.this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setCustomContentView(remoteViews);
Notification notification = builder.build();
startForeground(1,notification);
return super.onStartCommand(intent, flags, startId);
}
关闭前天服务
<Button
android:onClick="Stopfor"
android:text="关闭前台服务"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
public void Stopfor(View view) {
Intent intent = new Intent(this,MyService.class);
stopService(intent);//停止服务
}