Tamic/article

Google added the interface Android.app. usage from API 21. Through this API, we can count the usage of each app, startup times, startup time, etc., and also determine whether it is the front and back.





programming-2115930__480.jpg

Google added the interface Android.app. usage from API 21. Through this API, we can count the usage, startup times and startup time of each app, and determine whether it is running in the front and background, which is convenient and can also be used as a buried point. Today, let’s learn more about it.

Get front and back

This was done before 5.0:

 public String getForegroundApp(Context context) {        
    List<RunningAppProcesInfo> lr=context.getRunningAppProcesses();   

   if  (lr == null)  {     
       return null;   
  }   
 for (RunningAppProcessInfo ra : lr) {        
     if (ra.importance == RunningAppProcessInfo.IMPORTANCE_VISIBLE   || ra.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {                return ra.processName;     
        }    
    }      
   return null; 
}

Copy the code

Suddenly it doesn’t work from 5.0. This is a bit of a Eggs pain. Many people check the current interface of their application to mark and record the visible and invisible life cycles separately to determine whether it is a foreground or not. GetRecentTasks () has also been deprecated. The getTask permission we registered in the manifest has been taken away. The Android API already has an alternative, which is AppUsageStatistics requires user authorization. After 5.0 use AppUsageStatistics to obtain

private String getForegroundApp() { long ts = System.currentTimeMillis(); List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,ts-2000, ts); if (queryUsageStats == null || queryUsageStats.isEmpty()) { return null; } UsageStats recentStats = null; for (UsageStats usageStats : queryUsageStats) { if(recentStats == null || recentStats.getLastTimeUsed() < usageStats.getLastTimeUsed()) { recentStats  = usageStats; } } return recentStats.getPackageName; }Copy the code

See if it’s easy? Maybe you haven’t heard of it! Follow me!

AppUasgeStatistics

1 Apply for permission in the list first

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.appusagestatistics" Android: versionCode = "1" android: versionName = "1.0" > < USES - the permission android:name="android.permission.PACKAGE_USAGE_STATS"/> <application android:allowBackup="true" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:theme="@style/Theme.AppCompat.Light"> <activity android:name=".AppUsageStatisticsActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>Copy the code

2 GET UsageStatsManager and then use context GET to UsageStatsManager.

UsageStatsManager mUsageStatsManager = (UsageStatsManager) getActivity()                .getSystemService("usagestats"); //Context.USAGE_STATS_SERVICE
Copy the code

I use this API to get the usage of each app. IntervalType is the statistical period and statistical interval. UsageStatsManager provides four internal principles: year, month, week and day.

 DAILY("Daily", UsageStatsManager.INTERVAL_DAILY),
        WEEKLY("Weekly", UsageStatsManager.INTERVAL_WEEKLY),
        MONTHLY("Monthly", UsageStatsManager.INTERVAL_MONTHLY),
        YEARLY("Yearly", UsageStatsManager.INTERVAL_YEARLY);
Copy the code

In order to expand, I define a CustomUsageStats. UsageStats is a statistical class provided by Google, in which you can obtain the usage of app.

public class CustomUsageStats {   
  public UsageStats usageStats;    
  public Drawable appIcon;
}
Copy the code

The following code captures the usage of each app.

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; }Copy the code

Of course, the above code just gets the usage of the app to write a list, using the adapter to show the package name of the app, the last use time, and the icon icon.

public class UsageListAdapter extends RecyclerView.Adapter<UsageListAdapter.ViewHolder> {    
  private List<CustomUsageStats> mCustomUsageStatsList = new ArrayList<>();    
  private DateFormat mDateFormat = new SimpleDateFormat();   
   /**
     * Provide a reference to the type of views that you are using (custom ViewHolder)
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {        
    private final TextView mPackageName;        
    private final TextView mLastTimeUsed;        
    private final ImageView mAppIcon;        
    public ViewHolder(View v) {            
       super(v);
            mPackageName = (TextView) v.findViewById(R.id.textview_package_name);
            mLastTimeUsed = (TextView) v.findViewById(R.id.textview_last_time_used);
            mAppIcon = (ImageView) v.findViewById(R.id.app_icon);
        }        
        public TextView getLastTimeUsed() {            
           return mLastTimeUsed;
        }        
        public TextView getPackageName() {            
           return mPackageName;
        }        
        public ImageView getAppIcon() {            
          return mAppIcon;
        }
    }    
    public UsageListAdapter() {
    }    
    
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.usage_row, viewGroup, false);        return new ViewHolder(v);
    }    
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        viewHolder.getPackageName().setText(
                mCustomUsageStatsList.get(position).usageStats.getPackageName());        long lastTimeUsed = mCustomUsageStatsList.get(position).usageStats.getLastTimeUsed();
        viewHolder.getLastTimeUsed().setText(mDateFormat.format(new Date(lastTimeUsed)));
        viewHolder.getAppIcon().setImageDrawable(mCustomUsageStatsList.get(position).appIcon);
    }    
    @Override
    public int getItemCount() {        
       return mCustomUsageStatsList.size();
    }    
    public void setCustomUsageStatsList(List<CustomUsageStats> customUsageStats) {
        mCustomUsageStatsList = customUsageStats;
    }
}
Copy the code

Afterword.

This API does not mean that you can use it if you want to use it. Therefore, we can add this API when we do mobile burying point, which is convenient for us to collect app usage more accurately. Stay tuned for more tips.

Tamic/article www.jianshu.com/p/bdf47afe1…

Tamic Jane books: www.jianshu.com/u/3bbb1ddf4…

Timely reading articles can pay attention to my number:





Developer technology front