Activity can't start from broadcast receiver

五迷三道 提交于 2020-01-24 00:37:07

问题


Start Activity from Broadcast receiver is not working on android 9 but its working below android 9 it's working fine, I searched a lot regarding this but could not find the suitable solution. Does anyone face the same problem, here is my code .

public void onReceive(final Context context, Intent intent) {

    try {
        this.tm = (TelephonyManager) context.getSystemService("phone");
        this.tm.listen(new PhoneStateListener() {
            public void onCallStateChanged(int state, final String num) {
                if (state == 1 && Receiver.this.preferences.getInt("start", 0) == 1) {
                    try {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                Receiver.this.i = new Intent(context, MainActivity.class);

                                context.startActivity(Receiver.this.i);
                            }
                        }, 300);
                    } catch (Exception e) {

                    }
                } 

回答1:


I see that you're listening to onCallStateChanged. But I think you need to ask permission for that on Android 9: https://stackoverflow.com/a/52025013/2212770




回答2:


you need to add flag to the intent

i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

before you call context.startActivity(i);




回答3:


Below I send on example for starting activity from the broadcast receiver, But this one is for starting the MainActivity after device reboot.

public class StartReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action= intent.getAction();
        if( action.equals("android.intent.action.BOOT_COMPLETED") ){

            Intent i= new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            context.startActivity(i);
        }
    }

}



回答4:


Android Q (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background.

https://developer.android.com/guide/components/activities/background-starts

However, you can achieve this by giving alert window permission.

How to start a activity from a broadcast receiver when the screen is locked in Android Q

It is working like a charm



来源:https://stackoverflow.com/questions/58231094/activity-cant-start-from-broadcast-receiver

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