在指定时间停止服务

时间:2014-08-06 15:32:27

标签: android service sharedpreferences alarmmanager

我正在尝试根据已保存的sharedPreferences停止时间停止此服务。如下所示,mTime是从AlarmManager运行pendingIntent的开始时间(以毫秒为单位)。此代码有效,并始终在提供的开始时间启动我的服务并侦听来电。问题是我不知道在哪里使用停止时间(以毫秒为单位)来触发服务来停止/取消挂起的意图。

例如,假设我在晚上11点(mTime)开始服务,但希望它在早上7点(mTime2)停止。如果AlarmManager.set方法有一个停止时间参数,那将是理想的。

服务

//set alarm to trigger service
public static void setServiceAlarm(Context context, boolean isOn){
    //get shared Prefs time
    Long mTime = SaveSchedulePrefs.getSchedule(context);

    Intent i = new Intent(context, RingerService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    if(isOn){
        alarmManager.set(AlarmManager.RTC_WAKEUP, mTime, pi);   //change current time to shared prefs
    } else {
        alarmManager.cancel(pi);
        pi.cancel();
    }
}

启动服务(这总是基于alarmManager.set方法中的mTime):

//register listener
@Override
public int onStartCommand(Intent intent, int flags, int startId){
    mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    return START_STICKY;
}

 @Override
   public void onCreate(){
     mContext = (Context)this;
       mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

       mPhoneStateListener = new PhoneStateListener(){
           // state change 
           @Override
           public void onCallStateChanged(int state, String incomingNumber){
             //set ringer stuff
               myRingerManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
               int ringerMode = myRingerManager.getRingerMode();
               if (state == 1){ 
                   try{
                       Log.d(TAG, " number from incoming call: " + incomingNumber);
                       ...etc...

1 个答案:

答案 0 :(得分:1)

您只需向pendingIntent添加操作即可。例如" my.action.start"或者" my.action.stop"

然后在服务onStartCommand中检查intent.getAction()

//Note check for null on the getAction() I'm just typing in code example.

boolean isStart = (intent.getAction().equals("my.action.start")) ? true : false;

   if (isStart) {
        startForeground(R.id.action_record, getNotification());
        return Service.START_STICKY;
    } else {
        stopForeground(true);
        return Service.START_NOT_STICKY;
    }