Android kill process from broadcast receiver

2019-06-02 23:35发布

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

3条回答
We Are One
2楼-- · 2019-06-02 23:55

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.

查看更多
该账号已被封号
3楼-- · 2019-06-02 23:56

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.

查看更多
仙女界的扛把子
4楼-- · 2019-06-03 00:15

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

查看更多
登录 后发表回答