我的Android进阶之旅------>android中service的onStartCommand()方法中intent为null的问题

       今天在维护公司的一个APP的时候,突然爆了空指针异常,

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.getBooleanExtra(java.lang.String, boolean)' on a null object reference

       下面是报错的log。

D/AndroidRuntime( 4721): Shutting down VM
E/AndroidRuntime( 4721): FATAL EXCEPTION: main
E/AndroidRuntime( 4721): Process: com.tintele.sos, PID: 4721
E/AndroidRuntime( 4721): java.lang.RuntimeException: Unable to start service com.tintele.sos.SosService@36087165 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.getBooleanExtra(java.lang.String, boolean)' on a null object reference
E/AndroidRuntime( 4721):        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3152)
E/AndroidRuntime( 4721):        at android.app.ActivityThread.access$2100(ActivityThread.java:178)
E/AndroidRuntime( 4721):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1568)
E/AndroidRuntime( 4721):        at android.os.Handler.dispatchMessage(Handler.java:111)
E/AndroidRuntime( 4721):        at android.os.Looper.loop(Looper.java:194)
E/AndroidRuntime( 4721):        at android.app.ActivityThread.main(ActivityThread.java:5637)
E/AndroidRuntime( 4721):        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 4721):        at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 4721):        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
E/AndroidRuntime( 4721):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
E/AndroidRuntime( 4721): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.getBooleanExtra(java.lang.String, boolean)' on a null object reference
E/AndroidRuntime( 4721):        at com.tintele.sos.SosService.onStartCommand(SosService.java:309)
E/AndroidRuntime( 4721):        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3135)
E/AndroidRuntime( 4721):        ... 9 more

     打印log后发现原来是在onStartCommand(Intent intent, int flags, int startId)方法中intent为null。这个错误是对onStartCommand()方法的flags参数没有深入理解造成的,报错的代码:

boolean groundAlarmFlag=intent.getBooleanExtra("flag", false);

      而这个flag参数是通过别处传过来的,代码如下:

Intent intent = new Intent(getBaseContext(), SosService.class);
intent.putExtra("flag", true);
startService(intent);

 

【报错原因】

       因此报错 intent的参数是null的原因是这个intent参数是通过startService(Intent)方法所传递过来的,但是如果Service在你的进程退出后有可能被系统自动重启,这个时候intent就会是null.
【解决方法】
        【方法一】在使用intent前需要判断一下是否为空。即:

boolean groundAlarmFlag = false;
if (intent!=null) {
    groundAlarmFlag=intent.getBooleanExtra("flag", false);
}

        【方法二】

      将onStartCommand()方法的返回值从

return super.onStartCommand(intent, flags, startId);

      改成

return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);

因为onStartCommand方法的默认值START_STICKY_COMPATIBILITY或者START_STICKY不能保证intent不为null.

/**
     * Called by the system every time a client explicitly starts the service by calling
     * {@link android.content.Context#startService}, providing the arguments it supplied and a
     * unique integer token representing the start request.  Do not call this method directly.
     *
     * <p>For backwards compatibility, the default implementation calls
     * {@link #onStart} and returns either {@link #START_STICKY}
     * or {@link #START_STICKY_COMPATIBILITY}.
     *
     * <p>If you need your application to run on platform versions prior to API
     * level 5, you can use the following model to handle the older {@link #onStart}
     * callback in that case.  The <code>handleCommand</code> method is implemented by
     * you as appropriate:
     *
     * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java
     *   start_compatibility}
     *
     * <p class="caution">Note that the system calls this on your
     * service's main thread.  A service's main thread is the same
     * thread where UI operations take place for Activities running in the
     * same process.  You should always avoid stalling the main
     * thread's event loop.  When doing long-running operations,
     * network calls, or heavy disk I/O, you should kick off a new
     * thread, or use {@link android.os.AsyncTask}.</p>
     *
     * @param intent The Intent supplied to {@link android.content.Context#startService},
     * as given.  This may be null if the service is being restarted after
     * its process has gone away, and it had previously returned anything
     * except {@link #START_STICKY_COMPATIBILITY}.
     * @param flags Additional data about this start request.  Currently either
     * 0, {@link #START_FLAG_REDELIVERY}, or {@link #START_FLAG_RETRY}.
     * @param startId A unique integer representing this specific request to
     * start.  Use with {@link #stopSelfResult(int)}.
     *
     * @return The return value indicates what semantics the system should
     * use for the service's current started state.  It may be one of the
     * constants associated with the {@link #START_CONTINUATION_MASK} bits.
     *
     * @see #stopSelfResult(int)
     */
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
    }

==================================================================

下面具体讲解一下这几个flags的参数,首先参数有START_STICKY_COMPATIBILITY、

START_STICKY、START_NOT_STICKY、START_REDELIVER_INTENT四个。下面分别介绍一下,如下面表格所示:

START_STICKY        如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
START_NOT_STICKY      “非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT
      重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
START_STICKY_COMPATIBILITY
      START_STICKY的兼容版本,但不保证服务被kill后一定能重启。  

                                                                                                             

   源代码如下:

/**
     * Constant to return from {@link #onStartCommand}: compatibility
     * version of {@link #START_STICKY} that does not guarantee that
     * {@link #onStartCommand} will be called again after being killed.
     */
    public static final int START_STICKY_COMPATIBILITY = 0;

    /**
     * Constant to return from {@link #onStartCommand}: if this service's
     * process is killed while it is started (after returning from
     * {@link #onStartCommand}), then leave it in the started state but
     * don't retain this delivered intent.  Later the system will try to
     * re-create the service.  Because it is in the started state, it will
     * guarantee to call {@link #onStartCommand} after creating the new
     * service instance; if there are not any pending start commands to be
     * delivered to the service, it will be called with a null intent
     * object, so you must take care to check for this.
     *
     * <p>This mode makes sense for things that will be explicitly started
     * and stopped to run for arbitrary periods of time, such as a service
     * performing background music playback.
     */
    public static final int START_STICKY = 1;

    /**
     * Constant to return from {@link #onStartCommand}: if this service's
     * process is killed while it is started (after returning from
     * {@link #onStartCommand}), and there are no new start intents to
     * deliver to it, then take the service out of the started state and
     * don't recreate until a future explicit call to
     * {@link Context#startService Context.startService(Intent)}.  The
     * service will not receive a {@link #onStartCommand(Intent, int, int)}
     * call with a null Intent because it will not be re-started if there
     * are no pending Intents to deliver.
     *
     * <p>This mode makes sense for things that want to do some work as a
     * result of being started, but can be stopped when under memory pressure
     * and will explicit start themselves again later to do more work.  An
     * example of such a service would be one that polls for data from
     * a server: it could schedule an alarm to poll every N minutes by having
     * the alarm start its service.  When its {@link #onStartCommand} is
     * called from the alarm, it schedules a new alarm for N minutes later,
     * and spawns a thread to do its networking.  If its process is killed
     * while doing that check, the service will not be restarted until the
     * alarm goes off.
     */
    public static final int START_NOT_STICKY = 2;

    /**
     * Constant to return from {@link #onStartCommand}: if this service's
     * process is killed while it is started (after returning from
     * {@link #onStartCommand}), then it will be scheduled for a restart
     * and the last delivered Intent re-delivered to it again via
     * {@link #onStartCommand}.  This Intent will remain scheduled for
     * redelivery until the service calls {@link #stopSelf(int)} with the
     * start ID provided to {@link #onStartCommand}.  The
     * service will not receive a {@link #onStartCommand(Intent, int, int)}
     * call with a null Intent because it will will only be re-started if
     * it is not finished processing all Intents sent to it (and any such
     * pending events will be delivered at the point of restart).
     */
    public static final int START_REDELIVER_INTENT = 3;

 

 官方文档上的解释如下:

 

public static final int START_STICKY_COMPATIBILITY

 

Added in API level 5

Constant to return from onStartCommand(Intent, int, int): compatibility version of START_STICKY that does not guarantee thatonStartCommand(Intent, int, int) will be called again after being killed.

Constant Value: 0 (0x00000000)

 

public static final int START_STICKY

 

Added in API level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning fromonStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Constant Value: 1 (0x00000001)

 

public static final int START_NOT_STICKY

Added in API level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning fromonStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Constant Value: 2 (0x00000002)

 

public static final int START_REDELIVER_INTENT

 

Added in API level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning fromonStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again viaonStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided toonStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).

Constant Value: 3 (0x00000003)

 

public int onStartCommand (Intent intent, int flags, int startId)

 

Added in API level 5

Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY orSTART_STICKY_COMPATIBILITY.

If you need your application to run on platform versions prior to API level 5, you can use the following model to handle the older onStart(Intent, int) callback in that case. The handleCommand method is implemented by you as appropriate:

// This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    handleCommand(intent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

Note that the system calls this on your service's main thread. A service's main thread is the same thread where UI operations take place for Activities running in the same process. You should always avoid stalling the main thread's event loop. When doing long-running operations, network calls, or heavy disk I/O, you should kick off a new thread, or use AsyncTask.

Parameters
intent The Intent supplied to startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.
flags Additional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY.
startId A unique integer representing this specific request to start. Use with stopSelfResult(int).
Returns
  • The return value indicates what semantics the system should use for the service's current started state. It may be one of the constants associated with theSTART_CONTINUATION_MASK bits.
See Also

 

 

====================================================================================
  作者:欧阳鹏  欢迎转载,与人分享是进步的源泉!

  转载请保留原文地址:http://blog.csdn.net/ouyang_peng

====================================================================================

时间: 2024-11-01 11:42:26

我的Android进阶之旅------&gt;android中service的onStartCommand()方法中intent为null的问题的相关文章

我的Android进阶之旅------&amp;gt;Android利用温度传感器实现带动画效果的电子温度计

     要想实现带动画效果的电子温度计,需要以下几个知识点: 1.温度传感器相关知识. 2.ScaleAnimation动画相关知识,来进行水印刻度的缩放效果. 3.android:layout_weight属性的合理运用,关于android:layout_weight属性的讲解,可以参考:<我的Android进阶之旅------>关于android:layout_weight属性的一个面试题> 地址为:http://blog.csdn.net/ouyang_peng/article/

我的Android进阶之旅------&amp;gt;Android疯狂连连看游戏的实现之状态数据模型(三)

对于游戏玩家而言,游戏界面上看到的"元素"千变万化:但是对于游戏开发者而言,游戏界面上的元素在底层都是一些数据,不同数据所绘制的图片有所差异而已.因此建立游戏的状态数据模型是实现游戏逻辑的重要步骤. 1.定义数据模型 连连看的界面是一个NxM的"网格",每个网格上显示一张图片.而这个网格只需要一个二维数组来定义即可,而每个网格上所显示的图片,对于底层数据模型来说,不同的图片对于着不同的数值即可. 对于上图所示的数据模型,只要让数值为0的网格上不绘制图片,其他数值的网

我的Android进阶之旅------&amp;gt;Android疯狂连连看游戏的实现之开发游戏界面(二)

连连看的游戏界面十分简单,大致可以分为两个区域: 游戏主界面区 控制按钮和数据显示区 1.开发界面布局 本程序使用一个RelativeLayout作为整体的界面布局元素,界面布局上面是一个自定义组件,下面是一个水平排列的LinearLayout. 下面是本程序的布局文件:/res/layout/main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=

我的Android进阶之旅------&amp;gt;Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)

正如在<我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)>一文中看到的,在AbstractBoard的代码中,当程序需要创建N个Piece对象时,程序会直接调用ImageUtil的getPlayImages()方法去获取图片,该方法会随机从res/drawable目录中取得N张图片. 下面是res/drawable目录视图: 为了让getPlayImages()方法能随机从res/drawable目录中取得N张图片,具体实现分为以下几步: 通

我的Android进阶之旅------&amp;gt; Android为TextView组件中显示的文本添加背景色

通过上一篇文章 我的Android进阶之旅------> Android在TextView中显示图片方法 (地址:http://blog.csdn.net/ouyang_peng/article/details/46916963)      我们学会了在TextView中显示图片的方法,现在我们来学习如何为TextView组件中显示的文本添加背景色.要求完成的样子如图所示: 首先来学习使用BackgroundColorSpan对象设置文字背景色,代码如下: TextView textView=(

我的Android进阶之旅------&amp;gt;Android权限参考大全

访问登记属性 android.permission.ACCESS_CHECKIN_PROPERTIES ,读取或写入登记check-in数据库属性表的权限 获取错略位置 android.permission.ACCESS_COARSE_LOCATION,通过WiFi或移动基站的方式获取用户错略的经纬度信息,定位精度大概误差在30~1500米 获取精确位置 android.permission.ACCESS_FINE_LOCATION,通过GPS芯片接收卫星的定位信息,定位精度达10米以内 访问定

我的Android进阶之旅------&amp;gt;Android颜色值(#AARRGGBB)透明度百分比和十六进制对应关系以及计算方法

我的Android进阶之旅-->Android颜色值(RGB)所支持的四种常见形式 透明度百分比和十六进制对应关系表格 透明度 十六进制 100% FF 99% FC 98% FA 97% F7 96% F5 95% F2 94% F0 93% ED 92% EB 91% E8 90% E6 89% E3 88% E0 87% DE 86% DB 85% D9 84% D6 83% D4 82% D1 81% CF 80% CC 79% C9 78% C7 77% C4 76% C2 75% B

我的Android进阶之旅------&amp;gt;Android颜色值(RGB)所支持的四种常见形式

Android中颜色值是通过红(Red).绿(Green).蓝(Blue)三原色,以及一个透明度(Alpha)值来表示的,颜色值总是以井号(#)开头,接下来就是Alpha-Red-Green-Blue的形式.其中Alpha值可以省略,如果省略了Alpha的值,那么该颜色默认是完全不透明的. Android的颜色值支持常见的四种形式如下所示: #RGB:分别指定红.绿.蓝三原色的值(只支持0~f这16级颜色)来代表颜色. #ARGB:分别指定红.绿.蓝三原色的值(只支持0~f这16级颜色)及透明度

我的Android进阶之旅------&amp;gt;Android疯狂连连看游戏的实现之游戏效果预览(一)

今天看完了李刚老师的<疯狂Android讲义>一书中的第18章<疯狂连连看>,从而学会了如何编写一个简单的Android疯狂连连看游戏.      开发这个流行的小游戏,难度适中,而且能充分激发学习热情,适合Android初学者来说是一个不错的选择.对于该游戏的开发,需要重点掌握单机游戏的界面分析和数据建模能力:游戏玩家严重看到的是游戏界面,但是在开发者眼中看到的应该是数据模型.除此之外,单机游戏通常需要一个比较美观的界面,需要通过自定义View来实现游戏主界面.      开发连