Skip to content Skip to sidebar Skip to footer

How To Get Arguments For Starting A Service After Device Has Been Started?

I'm trying to start a service after the device has been started. The problem is that the service needs some arguments which it normally gets this way: public class ServiceClass ext

Solution 1:

Save last search string in SharedPreference in activity onPause method, retrieve last search string when you receive BootCompleted broadcast and start your service as usually.

Activity:

protectedvoidonPause() {
    super.onPause();

    SharedPreferencespref= getSharedPreferences("my_pref", MODE_PRIVATE);
    SharedPreferences.Editoreditor= pref.edit();
    editor.putString("last_search", mLastSearch);
    editor.commit();
}

BroadcastReceiver:

publicstaticclassOnStartupStarterextendsBroadcastReceiver {
    @OverridepublicvoidonReceive(Context context, Intent intent) {
        Stringaction= intent.getAction();

        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            SharedPreferencespref= context.getSharedPreferences("my_pref", MODE_PRIVATE);
            StringlastSearch= pref.getString("last_search", null);
            if (lastSearch != null) {
                // TODO: Start service
            }
        }
    }
}

Post a Comment for "How To Get Arguments For Starting A Service After Device Has Been Started?"