代码之家  ›  专栏  ›  技术社区  ›  Addev

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

  •  0
  • Addev  · 技术社区  · 8 年前

    我正在实施一个需要监控设备电池电量的应用程序。所以我实现了如下服务:

    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
            }
        };
    }
    

    我在我的主要活动中启动此服务:

    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:不允许启动服务意图{…}应用程序位于后台

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

    1. 如何避免服务在一段时间后停止运行?
    2. 如何避免开机时发生故障?我读过使用“startForegroundService”的文章,但它确实需要向用户提供通知。
    3. 如何在后台运行并正确监控电池,而不不断显示通知?

    谢谢

    1 回复  |  直到 8 年前
        1
  •  0
  •   Android_K.Doe    8 年前

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