简体   繁体   中英

Start Application on Startup in Android

I am trying to launch the main activity (which is the only activity) named as "MainActivity" when the Android OS starts. The app is installed on the internal storage but it says Unfortunately, The app(Name of app) has stopped. I am using the Boot Receive code as below

My MainActivity code in .java file

public class BootUpReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent i = new Intent(context, MainActivity.class);  
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);  
    }
}

AndroidManifest.xml

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

      <receiver android:enabled="true" android:name=".BootUpReceiver"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

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

Finally, did the right thing after searching some time, For some one who is stuck up here. What you have to do is register the onReceive function in a separate package, what i was getting the error in Logcat was Classnotfound as i placed the code in my MainActivity class and its package. As soon as i did changed the onReceive function to new package the application worked flawlessly.

try this:

public class BootUpReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equalsIgnoreCase("android.intent.action.BOOT_COMPLETED")) {
            Intent i = new Intent(context, MainActivity.class);  
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }  
    }
}

https://stackoverflow.com/a/11079306/6237295

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM