簡體   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