由于错误而在broadcastreceiver中使用Sharedpreferences

时间:2011-12-02 21:58:35

标签: android sms broadcastreceiver sharedpreferences

BroadcastReceiver的代码是一个单独的单元SMSReceiver.java。接收方在Manifest中使用SMS接收意图过滤器声明。所以它“永远在线”。当应用程序正在运行时或仅在最后8个应用程序的列表中,它在收到传入SMS时工作正常。但是后来,当应用程序从内存中删除时,只有接收器待机,因错误而传入短信。我在接收者的代码Sharedpreferences中使用的事实。当我从收到的短信中获得一些信息时,我应该将其保存在主要活动稍后加载的首选项中。

LogCat显示错误的字符串。

public class SmsReceiver extends BroadcastReceiver 
{

    public static SharedPreferences mStatePrefs;

@Override
public void onReceive(Context context, Intent intent) 
{
   //... some code
   SharedPreferences.Editor ed = mStatePrefs.edit(); //HERE I GET AN EXCEPTION
   //... some code
}
}

LogCat日志..

12-02 22:36:03.887: ERROR/AndroidRuntime(18345): FATAL EXCEPTION: main
12-02 22:36:03.887: ERROR/AndroidRuntime(18345): java.lang.RuntimeException: Unable to start receiver com.example.android.MyApplication.SmsReceiver: java.lang.NullPointerException
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2034)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.app.ActivityThread.access$2400(ActivityThread.java:132)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1098)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.os.Looper.loop(Looper.java:143)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.app.ActivityThread.main(ActivityThread.java:4268)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at java.lang.reflect.Method.invokeNative(Native Method)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at java.lang.reflect.Method.invoke(Method.java:507)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at dalvik.system.NativeStart.main(Native Method)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345): Caused by: java.lang.NullPointerException
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at com.example.android.MyApplication.SmsReceiver.onReceive(SmsReceiver.java:198)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2019)
12-02 22:36:03.887: ERROR/AndroidRuntime(18345):     ... 10 more

当app处于活动状态或内存中时,它可以正常工作。但是当接收器被单独放置时,就会发生错误。那么我需要做些什么来解决这个问题呢?这是我的应用程序的块错误,这个接收器是主要的解决方案,程序感。它必须始终有效,并在偏好中保存信息。

1 个答案:

答案 0 :(得分:1)

您永远不会获得mStatePrefs的SharedPreference实例。只看你显示的代码,mStatePrefs仍然是null。

尝试:

mStatePrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor ed = mStatePrefs.edit();