在这里我们只考虑5.0以上的系统,首先我们需要5.0的sdK,并且要申请权限,代码如下:
private String getTaskPackname() { String currentApp = "CurrentNULL"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { UsageStatsManager usm = (UsageStatsManager) this.getSystemService("usagestats"); long time = System.currentTimeMillis(); List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time); if (appList != null && appList.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : appList) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (mySortedMap != null && !mySortedMap.isEmpty()) { currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName(); } } } else { ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses(); currentApp = tasks.get(0).processName; } Log.e("TAG", "Current App in foreground is: " + currentApp); return currentApp; }如果没有申请权限,返回null,所以要加上
Intent intent = new Intent( Settings.ACTION_USAGE_ACCESS_SETTINGS); startActivity(intent);进到设置页面,加上这个权限。这样就能拿到包名。下面附上监控某些应用,若在前台,跳出禁止使用demo。代码如下:
package com.example.lockdemo; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.ActivityManager; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private Button button ; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { //getTaskPackname(); if("com.sina.weibo".equals(getTaskPackname())) { startActivity(new Intent(MainActivity.this,LockActivity.class)); } handler.sendEmptyMessageDelayed(1, 500); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); handler.sendEmptyMessageDelayed(1, 500); //isNoSwitch(); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent( Settings.ACTION_USAGE_ACCESS_SETTINGS); startActivity(intent); } }); } @TargetApi(Build.VERSION_CODES.CUPCAKE) @SuppressLint("NewApi") private String getTaskPackname() { String currentApp = "CurrentNULL"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { UsageStatsManager usm = (UsageStatsManager) this.getSystemService("usagestats"); long time = System.currentTimeMillis(); List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time); if (appList != null && appList.size() > 0) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : appList) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (mySortedMap != null && !mySortedMap.isEmpty()) { currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName(); } } } else { ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses(); currentApp = tasks.get(0).processName; } Log.e("TAG", "Current App in foreground is: " + currentApp); return currentApp; } private boolean isNoOption() { PackageManager packageManager = getApplicationContext() .getPackageManager(); Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } private boolean isNoSwitch() { long ts = System.currentTimeMillis(); UsageStatsManager usageStatsManager = (UsageStatsManager) getApplicationContext() .getSystemService("usagestats"); List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats( UsageStatsManager.INTERVAL_BEST, 0, ts); if (queryUsageStats == null || queryUsageStats.isEmpty()) { return false; } return true; } void showToast(String str) { Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show(); } }
package com.example.lockdemo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.KeyEvent; public class LockActivity extends ActionBarActivity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); finish(); } return super.onKeyDown(keyCode, event); } }
这里,xml不在附上。系统权限要加上:
<uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission xmlns:tools="http://schemas.android.com/tools" android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />ok,搞定了。