我的应用程序在 SharedPreference.Editor 上调用 putString 时强制关闭

My app force close when call putString on SharedPreference.Editor

当我调用putString 到SharedPreference 时出现问题。 我的程序首先 运行 通过 TileService,其中 运行 是一个 ForegroundService,然后从 ForegroundService 打开一个 Activity,在这个 Activity 中,我调用 putString 到 SharedPreference。

如何让它完美运行?

TileService

...
    @Override
    public void onClick()
    {
        super.onClick();
        Intent intent = new Intent(mContext,AdzanService.class);
        if(mTileEnabled)
            intent.setAction("STOP_SERVICE");
        else
            intent.setAction("START_SERVICE");
        startForegroundService(intent);
        mTileEnabled = !mTileEnabled;
    }
...

服务

...
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if (intent.getAction().equals("STOP_SERVICE"))
        {
            stopForeground(true);
            stopSelf();
        }
...

Activity

...
    private void save(){
        mEditor.putString("setting_location",((EditText)findViewById(R.id.setting_location)).getText().toString());
        mEditor.putString("setting_times",((RadioButton)findViewById(((RadioGroup)findViewById(R.id.setting_times)).getCheckedRadioButtonId())).getTag().toString());
        mEditor.apply();
    }
...

错误

java.lang.RuntimeException: Unable to start service in.blackant.adzan.AdzanService@873299c with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3722)
    at android.app.ActivityThread.access00(ActivityThread.java:198)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1686)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6693)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
    at in.blackant.adzan.AdzanService.onStartCommand(AdzanService.java:97)
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3703)
    ... 8 more

如错误消息所述,当您调用 intent.getAction()

时,服务 class 中的 Intent 为空

Intent 在这里可以为空 according to the docs

The Intent supplied to Context.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.

在检查之前添加空检查 getAction() 将修复崩溃,但您可能需要查看服务重启的原因