0

我正在尝试在设备启动后启动服务。问题是该服务需要一些通常以这种方式获得的参数:

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[...]

}

但是,当设备启动时应该通过 BroadcastReceiver 启动服务时,我无法放置 searchString,因为这是由活动给出的。当服务在设备启动后启动时,服务应该以它在设备关闭之前的 searchString 开始。

BroadcastReceiver 是服务类的子类:

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...
         */
    }
}


通常服务是这样启动的:

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);
    }
};
4

1 回答 1

3

将最后一个搜索字符串保存SharedPreference在活动方法中,当您收到广播onPause时检索最后一个搜索字符串并像往常一样启动您的服务。BootCompleted

活动:

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

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

广播接收器:

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
            }
        }
    }
}
于 2012-08-03T18:26:56.340 回答