I've used BroadcastReceiver to auto-start the app as soon as device boot is completed. But it is not working. While tested with cmd (adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -p com.capitaleyejobschedulers.com.jobschedulers), the log is shown only if the app is in the foreground. If it is minimized or swipe out from the app list (ie. app not running), it doesn't work.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
mReceiver = new BootCompletedIntentReceiver();
registerReceiver(mReceiver, filter);
}
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.e("bootDeviceValue", " zzz");
}
}
}
@Override
public void onDestroy() {
try{
if(mReceiver!=null)
unregisterReceiver(mReceiver);
}catch(Exception e){
}
super.onDestroy();
}
Update 1:
MainActivity
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("bootDeviceValue", " aaaaa");
}
}
YourActivityRunOnStartup class
public class YourActivityRunOnStartup extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.e("bootDeviceValue", " bbbbb");
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zzzz.com.autorunonboot">
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:enabled="true"
android:exported="true"
android:name=".YourActivityRunOnStartup"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>