我正在尝试在设备启动后启动服务。问题是服务需要一些通常以这种方式获得的参数:
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);
}
};
答案 0 :(得分: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
}
}
}
}