gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:34:32 25 4
gpt4 key购买 nike

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

如何让它完美运行?

平铺服务

...
@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.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

此处 Intent 可为空 according to the docs

提供给 Context.startService(Intent) 的 Intent,如给定。如果服务在其进程消失后重新启动,并且之前已返回除 START_STICKY_COMPATIBILITY 之外的任何内容,则该值可能为 null。

在检查 getAction() 之前添加空检查将修复崩溃,但您可能想了解服务重新启动的原因

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com