Tag Archives: Android Start Automatically

Android: How to Start App Automatically

Need to register for static broadcast (dynamic broadcast)

Give permission:

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

Register static broadcast receiver:

<receiver android:name=".MainActivity$MyBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

All configuration information:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.startactivity">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver android:name=".MainActivity$MyBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity

public class MainActivity extends AppCompatActivity {   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public class MyBroadcastReceiver extends BroadcastReceiver{  //Must be static, otherwise the startup will report an error

        @Override
        public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
                    Intent mainActivity=new Intent(context,MainActivity.class); //skip to MainActivity
                    mainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(mainActivity);
                }
        }
    }
}