How do I start my app on startup?

前端 未结 8 1777
失恋的感觉
失恋的感觉 2020-11-22 01:06

I tried using the sample code in this link but it seems outdated and it did not work. So what changes do I have to make and to what files to have my app start automatically

8条回答
  •  长情又很酷
    2020-11-22 01:53

    This is how to make an activity start running after android device reboot:

    Insert this code in your AndroidManifest.xml file, within the element (not within the element):

    
    
    
    
        
            
            
            
        
    
    
    

    Then create a new class yourActivityRunOnStartup (matching the android:name specified for the element in the manifest):

    package yourpackage;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    
    public class yourActivityRunOnStartup extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Intent i = new Intent(context, MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
        }
    
    }
    

    Note: The call i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); is important because the activity is launched from a context outside the activity. Without this, the activity will not start.

    Also, the values android:enabled, android:exported and android:permission in the tag do not seem mandatory. The app receives the event without these values. See the example here.

提交回复
热议问题