Pregunta

I saw some other posts about how to start your application on phone start but it might be annoying for the user to see the application pop up each time. What I would rather do is start a service and check to see if I should start up and keep the app up or shut it down. My question is how can I accomplish something like this or the "correct" way to do it i.e. is it better to start a service or the app?

¿Fue útil?

Solución

In your manifest, add the RECEIVE_BOOT_COMPLETED permission.

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

Make a BroadcastReceiver. Add it to your manifest so that it receives the BOOT_COMPLETED action.

<receiver android:name="your.package.name.BootCompletedReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

In your app, you would save the user's preference in SharedPreferences. If you aren't using a typical preference screen, you can always do this:

// if inside an activity or service, context can be "this"
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putBoolean("start_at_boot", true).commit();

In your receiver, you can check this preference and decide what to do from there.

public class BootCompletedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean startAtBoot = prefs.getBoolean("start_at_boot", false) {
        if (startAtBoot) {
            // do something here
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top