How to get arguments for starting a service after device has been started?

Deadly 提交于 2019-12-11 17:40:02

问题


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
            }
        }
    }
}


来源:https://stackoverflow.com/questions/11801033/how-to-get-arguments-for-starting-a-service-after-device-has-been-started

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!