服务在一段时间后停止运行

时间:2018-03-19 01:47:32

标签: android

我正在实施一款需要监控设备电池电量的应用。所以我实现了这样的服务:

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在后台

也许我的问题与自我相关:

  1. 如何在一段时间后避免服务停止运行?
  2. 如何避免启动时崩溃?我已经读过使用" startForegroundService"但是,它确实需要向用户提供通知。
  3. 如何在不经常显示通知的情况下在后台运行并正确监控电池?
  4. 谢谢!

1 个答案:

答案 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);