Analysis of the problem that the intent is null in the onStartCommand(Intent intent, int flags, int startId) method during Android Service startup

    Recently, the app has appeared two or three times due to the Intent.getIntExtra() on a null object exception thrown when the onStartCommand(intent, flags, startId) method of the Service obtains the parameters carried by the intent, and the intent is a null pointer. This error is caused by not having a deep understanding of the flags parameter of the onStartCommand() method.

 Error reason: The reason why the intent is null is that the intent parameter is passed through the startService(Intent intent) method. If the service may be restarted by the system after the process exits, the intent parameter does not go through the service's start method startService, so is null.

Solution:

  1. Judge non-null before using intent;
  2. At the return in the onStartCommand(Intent intent, int flags, int startId) method in Service, change return super.onstartCommand(intent, flags, startId) to return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId).

    The four selection parameters of flags are described in detail below, START_STICKY_COMPATIBILITY, START_STICKY, START_NOT_STICKY, START_REDELIVER_INTENT:

  1. START_STICKY: If the service process is killed, the service will be kept in the start state, but the passed intent object will not be retained, and then the system will try to recreate the service. Because it is in the start state, onStartCommand(Intent, int, int) will be called after creation. ) method, intent is null if no other startup commands have been passed to the service during this time.
  2. START_NOT_STICKY: Non-sticky, which means that if the service is killed by the system abnormally after executing the onStartCommand (Intent, int, int) method, the system will not automatically restart the service.
  3. START_REDELIVER_INTENT: Retransmit the intent. When using this return flags value, if the service is killed by the system abnormally after executing onStartCommand (Intent, int, int), the system will restart the service and pass in the intent.
  4. START_STICKY_COMPATIBILITY: Compatible version of START_STICKY, but does not guarantee that the service will be restarted.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688833&siteId=291194637