当我将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();
        }
...


活动

...
    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.access$1600(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()时,服务类中的Intent为null

意向在此处为空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()之前添加空检查将解决崩溃问题,但是您可能想调查一下为什么重新启动服务

关于java - 在SharedPreference.Editor上调用putString时,我的应用程序强制关闭,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60084858/

10-13 09:10