我已经构建了一个应用程序来启动另一个名为WazeApp的应用程序,这样如果Waze应用程序的最后一个活动时间超过5分钟,那么我将启动应用程序,否则我不会。
这是方法:
/**
* return true if waze was running before 5 Minutes
* @param context
* @return
*/
private static boolean wasWazeRunningBefore5Minutes(Context context) {
long current = System.currentTimeMillis();
long fiveMinuteBeforeMillis = current - TimeUnit.SECONDS.toMillis(TIME_INTERVAL);//TIME_INTERVAL=5*60 sec
UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, fiveMinuteBeforeMillis, current);
for (UsageStats stat : stats) {
if (stat.getPackageName().equals(WAZE_PACKAGE_NAME)) {
long lastTimeUsed = stat.getLastTimeUsed();
Log.d(TAG, "last time used: " + DateFormat.format("dd/MM/yyyy, hh:mm:ss", new Date(lastTimeUsed)));
long gap = TimeUnit.MILLISECONDS.toSeconds(current - lastTimeUsed);
if (gap > TIME_INTERVAL) {
return true;
}
Log.d(TAG, "app open gap: " + gap + " sec");
break;
}
}
return false;
}
但我的WazeApp第一次安装时没有启动。 任何人都可以解决这个问题
答案 0 :(得分:0)
来自谷歌示例:
https://github.com/googlesamples/android-AppUsageStatistics
public List<UsageStats> getUsageStatistics(int intervalType) {
// Get the app statistics since one year ago from the current time.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
.queryUsageStats(intervalType, cal.getTimeInMillis(),
System.currentTimeMillis());
if (queryUsageStats.size() == 0) {
Log.i(TAG, "The user may not allow the access to apps usage. ");
Toast.makeText(getActivity(),
getString(R.string.explanation_access_to_appusage_is_not_enabled),
Toast.LENGTH_LONG).show();
mOpenUsageSettingButton.setVisibility(View.VISIBLE);
mOpenUsageSettingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}
});
}
return queryUsageStats;
}
他们可以使用它:
http://developer.android.com/intl/es/reference/android/app/usage/UsageStats.html#getLastTimeUsed()
if( mUsageStats.getPackageName().equals("YOUR PACKAGE NAME")){
mUsageStats.getLastTimeUsed();}