1.修改Service的onCreate方法代码
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("message")
.setContentTitle("title")
.setContentIntent(pendingIntent);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// manager.notify(1, notification);
startForeground(1,notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
使用notification ,区别是用startForeground方法,这样打开的notification常驻状态栏(除非进程或者该服务被杀死)。
打开一个不在状态栏显示的notification , 第一个参数id为0即可 : startForeground(0, new Notification());
要从前台删除服务,需调用stopForeground()方法,需要一个布尔型参数,但是这个方法不终止服务。
如果该进程或者该服务被杀死,状态栏的notification也会消失。
Android6.0 以上版本 好像不可行!!!