Start an Activity on Phone Boot in Android

假装没事ソ 提交于 2019-12-30 07:16:05

问题


I want to start my application automatically when the phone boots. I declared a BroadcastReceiver in the manifest file.

<receiver android:name=".Autostart">  
<intent-filter>  
    <action android:name="android.intent.action.BOOT_COMPLETED" />  
</intent-filter>  

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

I made a java file for the receiver.

Autostart.java

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

    Intent pushIntent = new Intent(context, MushTouchActivity.class); 
    pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(pushIntent);
    }
}

}

But, the application does not launch when I switch my phone on. Can anyone tell me what I am missing here ?


回答1:


try your if statement like this:

    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){


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

        context.startActivity(i);
    }



回答2:


In case you are on Android 3.1 or newer:

Make sure that you started your application at least once manually (e.g. by opening it from the app drawer). Otherwise your app is marked as stopped by the system:

Applications are in a stopped state when they are first installed but are not yet launched

Stopped apps do not receive any broadcast intents, including BOOT_COMPLETED.

See Android 3.1. Platform - Launch controls on stopped applications for more information.




回答3:


The best answer would be to show a Notification and ask the user to launch the app from that notification and use a pending intent for that activity in the notification.



来源:https://stackoverflow.com/questions/10853879/start-an-activity-on-phone-boot-in-android

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