实际上,这是因为Android内置的安全性。为了保护用户,他们不鼓励使用后台服务。要允许这样的操作,用户必须通过在前台启动服务来知道您的服务正在运行。
Intent intent = new Intent(this, typeof(SomeActivityInYourApp));
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.Drawable.my_icon);
builder.setTicker("App info string");
builder.setContentTitle("Hey there");
builder.setContentText("My battery service is running!")
builder.setContentIntent(pi);
builder.setOngoing(true);
Notification notification = builder.build();
startForeground(SERVICE_NOTIFICATION_ID, notification);