How to get arguments for starting a service after

2019-08-30 02:53发布

问题:

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 extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        searchString = (String) intent.getExtras().get(GET_SEARCHSTRING_AFTER_START);
        [...]   
        return START_STICKY;

    public  static final String GET_SEARCHSTRING_AFTER_START = "SEARCHVALUE";

    public class OnStartupStarter[...]

}

But when the service should be started via a BroadcastReceiver when the device has started I can't put the searchString because this is given by an activity. When the service starts after the device has been started the service should start with the searchString it had before the device was turned off.

The BroadcastReceiver is a subclass from the service's class:

public static class OnStartupStarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        /* TODO: Start the service with the searchString it 
         * had before the device has been turned off...
         */
    }
}


Normally the service is started like this:

private OnCheckedChangeListener ServiceSwitchCheckedStatusChanged 
= new OnCheckedChangeListener() {
     public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        Intent s = new Intent(getBaseContext(), ServiceClass.class);

        s.putExtra(ServiceClass.GET_SEARCHSTRING_AFTER_START, <ARGUMENT>);
        if(isChecked)
            startService(s);
        else
            stopService(s);
    }
};

回答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:

protected void onPause() {
    super.onPause();

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

BroadcastReceiver:

public static class OnStartupStarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

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