Unable to find Last Active Time The App Was Used

420 Views Asked by At

I have build an app which Launch another app called WazeApp such that if the last active time of Waze app is greater than 5 minutes then i will launch the app else i won't.

here is method:

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

but my WazeApp is not launching for the first time i have installed it. Can Anyone fix this problem

1

There are 1 best solutions below

0
On

From google examples:

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

And them you can use this:

http://developer.android.com/intl/es/reference/android/app/usage/UsageStats.html#getLastTimeUsed()

if( mUsageStats.getPackageName().equals("YOUR PACKAGE NAME")){
mUsageStats.getLastTimeUsed();}