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