Android kill process from broadcast receiver

六月ゝ 毕业季﹏ 提交于 2019-12-08 08:15:48

问题


Hi i'm looking to kill an activity in my application when the usb is disconnected i have a broadcast receiver and all set up and working fine

public class USBOff extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent intent1 = new Intent(context, SdcardOff.class);
    startActivity(intent1);
    finish();
    }
 }

This code however tells me that the finish method and startActivity methods need to be created? why is this not working thank you for any help with my problem


回答1:


startActivity is a Context method, not a BroadcastReceiver method. finish is an Activity method. Try this:

context.startActivity(intent1);

You can't call finish from a BroadcastReceiver.




回答2:


I have found an interexting method : Manfest :

android:launchMode="singleInstance"
<action android:name="com.gr.app.KILLSELF" />

receiver code :

Intent intentInterface = new Intent("com.gr.app.KILLSELF");
mContext.startActivity(intentInterface);

activity onCreate part :

if (intent.getAction().compareTo("com.gr.app.KILLSELF") == 0) {
        finish();
    };

It will not work in such configuration if you may have many instancesof activity (string android:launchMode="singleInstance" is a problem for you),

I hope it will help




回答3:


Simple Logic :

If you dont want to kill the activity then do not use finish() And if you want to kill the activity then you should have to call finish();

So remove the finish(); from code and try it out. Enjoy.



来源:https://stackoverflow.com/questions/6352707/android-kill-process-from-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!