2012-08-03 57 views
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启动一个活动。当设备启动后服务启动时,服务应该从设备关闭前的搜索字符串开始。

的广播接收器是从服务的类的子类:

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


通常在服务启动这样的:在SharedPreference

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

回答

3

保存最后一个搜索字符串中的活动方法,当您收到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 
      } 
     } 
    } 
} 
+0

谢谢你,你帮了我很多。它工作正常。 – HerpDerpington 2012-08-03 19:32:16

相关问题