2015-03-19 133 views
0

我有一款遊戲,並且我希望每隔幾小時發送一次通知,以關閉該應用程序而不打開它。爲了使這些通知不是問題,但我不知道如何計算應用程序未被使用的時間?我應該保存在本地文件,如應用程序偏好類嗎?還是有不同的方式?關閉應用程序的時間

例如:我玩遊戲,然後關閉它。我沒有觸及遊戲一天,然後我收到通知「回來等等等等,玩等等等等」

+0

偏好會在這裏我的第一選擇,簡單而有效。 – 2015-03-19 11:13:25

+0

你是否從服務器獲取了關於應用程序是否連接的控制權? – eduyayo 2015-03-19 11:13:45

+0

請參閱此問題http://stackoverflow.com/questions/2166961/determining-the-current-foreground-application-from-a-background-task-or-service/5528441#5528441 – Signare 2015-03-19 11:16:53

回答

0

使用AlarmManager來設置當你退出你的應用程序,你會收到你的接收器類的報警下面的代碼

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 

       PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM_ID_XYZ, new Intent(
         FILTER_TIME_ABC), PendingIntent.FLAG_UPDATE_CURRENT); 

       alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1*60*60*1000, 1*60*60*1000, pendingIntent); 

並在您的應用程序開始取消使用下面的代碼的所有報警:

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 

       PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM_ID_XYZ, new Intent(
         FILTER_TIME_ABC), PendingIntent.FLAG_UPDATE_CURRENT); 
alarmManager.cancel(pendingIntent); 
+0

如果有人正在使用一直運行的服務,則無需使用Alarmmanager。處理程序更容易。 – Fasiha 2015-03-19 11:31:19

+0

@MahaKhan服務可能會死亡......最好使用AlarmManager。 – 2015-03-19 12:41:36

0

如果您使用的始終運行有沒有必要使用Alarmmanager的服務。處理程序更容易。 使用共享首選項和一些類似的計算。

// Calendar.getInstance().getTime() This is previous time 

       Date prevTime = Calendar.getInstance().getTime(); 
       Date currentTime = null; 
       SimpleDateFormat formatter = new SimpleDateFormat(
         "EEE MMM dd HH:mm:ss zzzz yyyy"); 
       currentTime = formatter.parse(get value from share preference); 

       if (((prevTime.getTime() - currentTime.getTime()) 
         /(60 * 1000) % 60) < 30) 
        { 
    //Call Your function 

     } 

希望這將幫助你

+0

太好了!但是,如何在有人關閉應用程序時獲得時間? – user4689356 2015-03-19 12:49:56

+0

停止監聽器?或在後面按? – Fasiha 2015-03-19 13:36:29