![](/img/trans.png)
[英]How to restrict the user from interacting with the program for a certain period of time?
[英]How to restrict the Android application to run only a certain time period?
我想創建一個運行一定時間間隔的應用程序。
[編輯] 按特定的時間間隔,我的意思是用戶是否從Play商店下載應用程序。 他可以在固定的時間內(例如X個小時)查看所有功能。 之后,我們可以設置任何種類的限制(任何UI / Navigation限制,以便用戶無法查看功能)。
[問題]
最簡單有效的方法是什么? 就像我認為這些解決方案不起作用:
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
要么
Time now = new Time();
now.setToNow();
設置限制的最佳方法是什么(如我在某些游戲應用程序中所看到的那樣,在應用程序端或服務器端,在服務器和應用程序之間進行同步,以使用戶無法簡單地更改時間並訪問功能)。
因此,如果您想在第一次運行中將應用程序運行一段時間,則需要跟蹤第一次運行。 因此,您可以設置一個首選項變量,以便它可以告訴您是否是第一次運行。
現在設置一個CountDownTimer
並將其設置為運行一個小時,並在計時器結束后,通過對它調用finish()
來關閉Activity。
SharedPreferences pref = getSharedPreferences("ApplicationTag", Activity.MODE_PRIVATE);
if (pref.contains("FIRST_LAUNCH")){
finish(); // As you want, it can't be used if the application launches second time.
} else {
// Set the first launch flag to true.
pref.edit.putBoolean("FIRST_LAUNCH", true).commit();
// Start the count down timer
new CountDownTimer(3600000, 1000) {
public void onTick(long millisRemaining) {
// Do nothing
}
public void onFinish() {
// Finish the Activity
finish();
}
}.start();
因此,您可能會想,如果我在“活動”之間進行切換該怎么辦。 因此,在這種情況下,您將創建一個BaseActivity
類,該類將被應用程序中的其他Activity擴展。 將CountDownTimer
代碼放在此處,並引用您所處的Context
,然后在計時器結束時調用context.finish()
。
因此,如果您不想限制首次啟動的用戶,則需要以某種方式節省時間。 Activity
完成后,您將在onDestroy
函數中獲得回調。 因此,請覆蓋onDestroy
函數,並以剩余時間(以毫秒為單位)再次設置一些首選項。 這樣您就可以在應用程序啟動時再次初始化計時器。
希望有幫助!
嘗試設置警報以在您想要的任何時間后觸發任何活動。 如下所示:
calendar = Calendar.getInstance();
Intent intent = new Intent(this, ActivityYouWantToStart.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 101, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
calendar.add(Calendar.Hour,1);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
用戶首次啟動您的代碼時調用此代碼,並在ActivityYouWantToStart.class
內部執行此段時間后要執行的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.