web-dev-qa-db-ja.com

Androidプログラムでアプリケーションに費やされた時間を取得する方法

今日使用したすべてのアプリケーションの使用時間を取得したい。

*#*#4636#*#*をダイヤルすると、これらの詳細が表示されます。しかし、私はこれらの詳細をAndroidでプログラム的に必要としています。これで私を助けてください。

これらのPlayストアアプリが使用統計を表示する方法を確認できます

休憩なし

アプリの使用

14
Himanshu Mori

使用状況アクセス設定のあるアプリ

アクティビティクラス:-

package com.example.Android.appusagestatistics;

import Android.app.Activity;
import Android.app.usage.UsageStats;
import Android.app.usage.UsageStatsManager;
import Android.content.Context;
import Android.content.pm.ApplicationInfo;
import Android.content.pm.PackageManager;
import Android.content.pm.PackageManager.NameNotFoundException;
import Android.os.Bundle;

import Java.text.DateFormat;
import Java.util.ArrayList;
import Java.util.Calendar;
import Java.util.Collections;
import Java.util.Comparator;
import Java.util.List;
import Java.util.Map;

import Android.text.format.DateUtils;
import Android.util.ArrayMap;
import Android.util.Log;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.widget.AdapterView;
import Android.widget.BaseAdapter;
import Android.widget.ListView;
import Android.widget.Spinner;
import Android.widget.TextView;
import Android.widget.AdapterView.OnItemSelectedListener;

/**
 * Activity to display package usage statistics.
 */
public class UsageStatsActivity extends Activity implements OnItemSelectedListener {
    private static final String TAG = "UsageStatsActivity";
    private static final boolean localLOGV = false;
    private UsageStatsManager mUsageStatsManager;
    private LayoutInflater mInflater;
    private UsageStatsAdapter mAdapter;
    private PackageManager mPm;

    public static class AppNameComparator implements Comparator<UsageStats> {
        private Map<String, String> mAppLabelList;

        AppNameComparator(Map<String, String> appList) {
            mAppLabelList = appList;
        }

        @Override
        public final int compare(UsageStats a, UsageStats b) {
            String alabel = mAppLabelList.get(a.getPackageName());
            String blabel = mAppLabelList.get(b.getPackageName());
            return alabel.compareTo(blabel);
        }
    }

    public static class LastTimeUsedComparator implements Comparator<UsageStats> {
        @Override
        public final int compare(UsageStats a, UsageStats b) {
            // return by descending order
            return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
        }
    }

    public static class UsageTimeComparator implements Comparator<UsageStats> {
        @Override
        public final int compare(UsageStats a, UsageStats b) {
            return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
        }
    }

    // View Holder used when displaying views
    static class AppViewHolder {
        TextView pkgName;
        TextView lastTimeUsed;
        TextView usageTime;
    }

    class UsageStatsAdapter extends BaseAdapter {
        // Constants defining order for display order
        private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
        private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
        private static final int _DISPLAY_ORDER_APP_NAME = 2;

        private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
        private LastTimeUsedComparator mLastTimeUsedComparator = new LastTimeUsedComparator();
        private UsageTimeComparator mUsageTimeComparator = new UsageTimeComparator();
        private AppNameComparator mAppLabelComparator;
        private final ArrayMap<String, String> mAppLabelMap = new ArrayMap<>();
        private final ArrayList<UsageStats> mPackageStats = new ArrayList<>();

        UsageStatsAdapter() {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, -5);

            final List<UsageStats> stats =
                    mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                            cal.getTimeInMillis(), System.currentTimeMillis());
            if (stats == null) {
                return;
            }

            ArrayMap<String, UsageStats> map = new ArrayMap<>();
            final int statCount = stats.size();
            for (int i = 0; i < statCount; i++) {
                final Android.app.usage.UsageStats pkgStats = stats.get(i);

                // load application labels for each application
                try {
                    ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
                    String label = appInfo.loadLabel(mPm).toString();
                    mAppLabelMap.put(pkgStats.getPackageName(), label);

                    UsageStats existingStats =
                            map.get(pkgStats.getPackageName());
                    if (existingStats == null) {
                        map.put(pkgStats.getPackageName(), pkgStats);
                    } else {
                        existingStats.add(pkgStats);
                    }

                } catch (NameNotFoundException e) {
                    // This package may be gone.
                }
            }
            mPackageStats.addAll(map.values());

            // Sort list
            mAppLabelComparator = new AppNameComparator(mAppLabelMap);
            sortList();
        }

        @Override
        public int getCount() {
            return mPackageStats.size();
        }

        @Override
        public Object getItem(int position) {
            return mPackageStats.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            AppViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.usage_stats_item, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new AppViewHolder();
                holder.pkgName = (TextView) convertView.findViewById(R.id.package_name);
                holder.lastTimeUsed = (TextView) convertView.findViewById(R.id.last_time_used);
                holder.usageTime = (TextView) convertView.findViewById(R.id.usage_time);
                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (AppViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder
            UsageStats pkgStats = mPackageStats.get(position);
            if (pkgStats != null) {
                String label = mAppLabelMap.get(pkgStats.getPackageName());
                holder.pkgName.setText(label);
                holder.lastTimeUsed.setText(DateUtils.formatSameDayTime(pkgStats.getLastTimeUsed(),
                        System.currentTimeMillis(), DateFormat.MEDIUM, DateFormat.MEDIUM));
                holder.usageTime.setText(
                        DateUtils.formatElapsedTime(pkgStats.getTotalTimeInForeground() / 1000));
            } else {
                Log.w(TAG, "No usage stats info for package:" + position);
            }
            return convertView;
        }

        void sortList(int sortOrder) {
            if (mDisplayOrder == sortOrder) {
                // do nothing
                return;
            }
            mDisplayOrder= sortOrder;
            sortList();
        }
        private void sortList() {
            if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
                if (localLOGV) Log.i(TAG, "Sorting by usage time");
                Collections.sort(mPackageStats, mUsageTimeComparator);
            } else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
                if (localLOGV) Log.i(TAG, "Sorting by last time used");
                Collections.sort(mPackageStats, mLastTimeUsedComparator);
            } else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
                if (localLOGV) Log.i(TAG, "Sorting by application name");
                Collections.sort(mPackageStats, mAppLabelComparator);
            }
            notifyDataSetChanged();
        }
    }

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.usage_stats);

        mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
        mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mPm = getPackageManager();

        Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
        typeSpinner.setOnItemSelectedListener(this);

        ListView listView = (ListView) findViewById(R.id.pkg_list);
        mAdapter = new UsageStatsAdapter();
        listView.setAdapter(mAdapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        mAdapter.sortList(position);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // do nothing
    }
}

レイアウト:-

1。 usage_stats.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:orientation="vertical"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <TextView
        Android:text="@string/display_order_text"
        Android:textAppearance="?android:attr/textAppearanceLarge"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content" />

    <Spinner
        Android:id="@+id/typeSpinner"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:entries="@array/usage_stats_display_order_types" />

    <LinearLayout
        Android:orientation="horizontal"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content" >
        <TextView
            Android:text="@string/app_name_label"
            Android:textAppearance="?android:attr/textAppearanceMedium"
            Android:layout_width="wrap_content"
            Android:paddingEnd="6dip"
            Android:layout_height="wrap_content" />
        <TextView
            Android:text="@string/last_time_used_label"
            Android:paddingEnd="6dip"
            Android:textAppearance="?android:attr/textAppearanceMedium"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content" />
        <TextView
            Android:text="@string/usage_time_label"
            Android:textAppearance="?android:attr/textAppearanceMedium"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content" />
    </LinearLayout>
    <ListView Android:id="@+id/pkg_list"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:drawSelectorOnTop="false" />
</LinearLayout> 

2。 usage_stats_item.xml

<?xml version="1.0" encoding="utf-8"?><!--
/*
** Copyright 2008, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.Apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:minHeight="?android:attr/listPreferredItemHeight"
    Android:orientation="horizontal">

    <TextView
        Android:id="@+id/package_name"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:maxLines="1"
        Android:paddingEnd="6dip"
        Android:paddingStart="12dip"
        Android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        Android:id="@+id/last_time_used"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:maxLines="1"
        Android:paddingEnd="6dip"
        Android:paddingStart="12dip"
        Android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        Android:id="@+id/usage_time"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:maxLines="1"
        Android:paddingEnd="6dip"
        Android:paddingStart="12dip"
        Android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

値:-

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>


    <string-array name="usage_stats_display_order_types">
        <item>Usage time</item>
        <item>Last time used</item>
        <item>App name</item>
    </string-array>
</resources>

string.xml

 <string name="open_app_usage_setting">Open Apps with usage access settings</string>
<string name="last_time_used">"Last time used: "</string>
<string name="time_span">"Time span: "</string>

<string name="display_order_text">Sort by:</string>
<string name="app_name_label">App</string>
<string name="last_time_used_label">Last time used</string>
<!-- label for usage time -->
<string name="usage_time_label">Usage time</string> 

ユーザー権限:-

<uses-permission Android:name="Android.permission.PACKAGE_USAGE_STATS"/>

resultant snap

7
chand becse

Android 5.0から:_Android.app.usage.usageStats_を使用して、アプリが使用された合計時間をgetTotalTimeInForeground()にアクセスして取得できます。詳細については、 こちらを参照してください

4
Sudhasri

[〜#〜] tldr [〜#〜] @chand_becseコードを使用し、リストが空の場合は、このreguestPermissionsメソッドを追加し、onCreateでこれを呼び出しますメソッド(UsageStatsManagerが初期化された直後)

Chand becseの回答は完全に有効ですが、アプリケーションには他のアプリの統計情報を使用する権限が必要であることを覚えておく必要があります。 permision.PACKAGE_USAGEは単にユーザーに要求することはできないので、ACTION_USAGE_ACCESS_SETTINGSビューにリダイレクトして、手動でこれらの権限をオンにする必要があります。また、アプリケーションがすでにパーミッションを取得しているかどうかを確認するときに(すでに取得している場合でも)-1を取得するたびに、statsリストを確認していることにも気付きました。空です。もしそうなら、私は私のアプリケーションがこの機能のための許可を必要としていると思います。

    private void requestPermissions() {
        List<UsageStats> stats = mUsageStatsManager
                .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
        boolean isEmpty = stats.isEmpty();
        if (isEmpty) {
            startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
        }
    }

1