[英]"null object reference" when trying to stop a service
我想停止服務但收到此錯誤:
嘗試在 null object 參考上調用虛擬方法 'boolean android.content.Context.stopService(android.content.Intent)'
這是我停止服務的方法(在 class public class Dialog extends AppCompatActivity
中):
public void stopService(Context context) {
Intent serviceIntent = new Intent(context, PicovoiceService.class);
stopService(serviceIntent);
}
這就是我在另一個 class 中調用該方法的方式:
@SuppressLint("ValidFragment")
public class Popup extends DialogFragment {
private final int _layout;
private final Dialog mDialog = new Dialog();
public boolean dialogIsActive = false;
@SuppressLint("ValidFragment")
public Popup(int layout) {
_layout = layout;
}
@SuppressLint({"ClickableViewAccessibility", "ResourceType"})
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(_layout, container, false);
// Display fragment_dialog
if (_layout == R.layout.fragment_dialog) {
// Toggle the listener
view.findViewById(R.id.dialogCta).setOnClickListener(v -> {
if (!dialogIsActive) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (mDialog.hasRecordPermission(getContext())) {
mDialog.startService(getContext());
dialogIsActive = true;
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mDialog.stopService(getContext()); // <-- ERROR
}
dialogIsActive = false;
}
});
}
return view;
}
}
mDialog.startService(getContext());
工作正常,但mDialog.stopService(getContext());
有什么問題? ?
我也嘗試過Intent serviceIntent = new Intent(getBaseContext(), PicovoiceService.class);
和Intent serviceIntent = new Intent(getApplicationContext(), PicovoiceService.class);
但我得到同樣的錯誤。
這就是我可以使它工作的方法:
private Intent mServiceIntent = null;
public void startService(Context context) {
mServiceIntent = new Intent(context, PicovoiceService.class);
ContextCompat.startForegroundService(context, mServiceIntent);
}
public void stopTheService(Context context) {
if (mServiceIntent != null) {
context.stopService(mServiceIntent);
}
}
當我在stopService()
之前使用context
時,錯誤消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.