由于服务的系统优先级比较低,当内存不足时,有可能回收掉正在后台运行的服务。如果希望服务一直运行,可以考虑使用前台服务。
public void onCreate() { //创建服务时调用
Notification.Builder builder = new Notification.Builder(MyService.this);
builder.setTicker("This is a trcker");//通知栏的预览文字
builder.setSmallIcon(R.mipmap.ic_launcher);//图标
builder.setContentTitle("This is title");//通知的标题
builder.setContentText("This is content");//通知的内容
builder.setWhen(System.currentTimeMillis());//设置通知时间为当前系统时间
Notification notification = builder.build();//获取Notification的实例
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
startForeground(1, notification);
Log.d("Myservice" , "--OnCreate executed");
super.onCreate();
}