how to avoid null in intent that I have got in Ser

2019-08-08 11:23发布

问题:

I have a service that works in background. He returns START_STICKY because it listens to some events, this events occurs very fast (data from sensors). I some cases my service is killed: I have got a null intent and according to documentation it can happens when my service has killed because his process go away.

http://developer.android.com/reference/android/app/Service.html#onStart%28android.content.Intent,%20int%29

I want to know how avoid it. Any help will be appreciated.

Update

    private void startForeground() {
    String title = "Warning";//getString(R.string.note_title);
    String text = "App still working";//getString(R.string.note_msg);

    Intent intent = new Intent(this, DriverActivity.class);

    PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);


    Bitmap bitmap = BitmapFactory.decodeResource(
            getResources(),
            R.drawable.ic_launcher);
    Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(bitmap)
            .setContentTitle(title)
            .setContentText(text)
            .setContentIntent(pending);

    Notification notification = builder.getNotification();
    notification.flags |= Notification.FLAG_NO_CLEAR;
    startForeground(NOTIFICATION_ID, notification);
}

回答1:

Firs you need to identify why your service terminates. The two most probable motives are:

  • Service trows an exception and was terminated by Android
  • Service was terminated by Android because was running for long time (usually between 30 minutes and 1 hour) without being stated as foreground service

Exception This type of problem you can easly identify looking at logcat. Correction will depend on the cause reported.

Foreground this you can solve by setting your service to foreground using:

        startForeground(message, notification);

in your service.

Regards.