繁体   English   中英

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

[英]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 {...}应用程序在后台

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

  1. 如何避免该服务在一段时间后停止运行?
  2. 如何避免启动时崩溃? 我已经阅读过使用“ startForegroundService”的信息,但是它确实需要向用户显示通知。
  3. 我如何在后台运行并正确监控电池而又不不断显示通知?

谢谢!

实际上,这是因为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM