[英]Service stops running after some time
我正在实现一个需要监视设备电池电量的应用程序。 所以我实现了这样的服务:
public class BatteryService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Save the data
}
};
}
我在MainActivity中启动此服务:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, BatteryService.class));
}
}
并在android.intent.action.BOOT_COMPLETED
接收器中:
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,BatteryService.class));
}
}
我有两个问题:
由java.lang.IllegalStateException引起:不允许启动服务Intent {...}应用程序在后台
也许我的问题与自我有关:
谢谢!
实际上,这是因为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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.