我正在实施一款需要监控设备电池电量的应用。所以我实现了这样的服务:
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 {...} app在后台
也许我的问题与自我相关:
谢谢!
答案 0 :(得分:0)
实际上这是因为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);