package com.itheima.mobileguard.activities;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.app.ActivityManager;import android.content.Intent;import android.content.SharedPreferences;import android.graphics.Color;import android.os.Bundle;import android.text.format.Formatter;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.CheckBox;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.TextView;import com.itheima.mobileguard.R;import com.itheima.mobileguard.domain.TaskInfo;import com.itheima.mobileguard.engine.TaskInfoParser;import com.itheima.mobileguard.utils.SharedPreferencesUtils;import com.itheima.mobileguard.utils.SystemInfoUtils;import com.itheima.mobileguard.utils.UIUtils;import com.lidroid.xutils.ViewUtils;import com.lidroid.xutils.view.annotation.ViewInject;public class TaskManagerActivity extends Activity { @ViewInject(R.id.tv_task_process_count) private TextView tv_task_process_count; @ViewInject(R.id.tv_task_memory) private TextView tv_task_memory; @ViewInject(R.id.list_view) private ListView list_view; private long totalMem; private ListtaskInfos; private List userTaskInfos; private List systemAppInfos; private TaskManagerAdapter adapter; private int processCount; private long availMem;// private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);// sp = getSharedPreferences("config", 0); initUI(); initData(); } @Override protected void onResume() { super.onResume(); if(adapter != null){ adapter.notifyDataSetChanged(); } } private class TaskManagerAdapter extends BaseAdapter { @Override public int getCount() { /** * 判断当前用户是否需要展示系统进程 * 如果需要就全部展示 * 如果不需要就展示用户进程 */ boolean result = SharedPreferencesUtils.getBoolean(TaskManagerActivity.this, "is_show_system", false); if(result){ return userTaskInfos.size() + 1 + systemAppInfos.size() + 1; }else{ return userTaskInfos.size() + 1; } } @Override public Object getItem(int position) { if (position == 0) { //不是条目的位置,是显示"用户进程","系统进程"的位置 return null; } else if (position == userTaskInfos.size() + 1) { return null; } TaskInfo taskInfo; if (position < (userTaskInfos.size() + 1)) { // 用户程序 taskInfo = userTaskInfos.get(position - 1);// 多了一个textview的标签 , // 位置需要-1 } else { // 系统程序 int location = position - 1 - userTaskInfos.size() - 1; taskInfo = systemAppInfos.get(location); } return taskInfo; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { // 第0个位置显示的应该是 用户程序的个数的标签。 TextView tv = new TextView(getApplicationContext()); tv.setBackgroundColor(Color.GRAY); tv.setTextColor(Color.WHITE); tv.setText("用户程序:" + userTaskInfos.size() + "个"); return tv; } else if (position == (userTaskInfos.size() + 1)) { TextView tv = new TextView(getApplicationContext()); tv.setBackgroundColor(Color.GRAY); tv.setTextColor(Color.WHITE); tv.setText("系统程序:" + systemAppInfos.size() + "个"); return tv; } ViewHolder holder; View view; if (convertView != null && convertView instanceof LinearLayout) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = View.inflate(TaskManagerActivity.this, R.layout.item_task_manager, null); holder = new ViewHolder(); holder.iv_app_icon = (ImageView) view .findViewById(R.id.iv_app_icon); holder.tv_app_name = (TextView) view .findViewById(R.id.tv_app_name); holder.tv_app_memory_size = (TextView) view .findViewById(R.id.tv_app_memory_size); holder.tv_app_status = (CheckBox) view .findViewById(R.id.tv_app_status); view.setTag(holder); } TaskInfo taskInfo; if (position < (userTaskInfos.size() + 1)) { // 用户程序 taskInfo = userTaskInfos.get(position - 1);// 多了一个textview的标签 , // 位置需要-1 } else { // 系统程序 int location = position - 1 - userTaskInfos.size() - 1; taskInfo = systemAppInfos.get(location); } // 这个是设置图片控件的大小 // holder.iv_app_icon.setBackgroundDrawable(d) // 设置图片本身的大小 holder.iv_app_icon.setImageDrawable(taskInfo.getIcon()); holder.tv_app_name.setText(taskInfo.getAppName()); holder.tv_app_memory_size.setText("内存占用:" + Formatter.formatFileSize(TaskManagerActivity.this, taskInfo.getMemorySize())); if (taskInfo.isChecked()) { holder.tv_app_status.setChecked(true); } else { holder.tv_app_status.setChecked(false); } //判断当前展示的item是否是自己的程序。如果是。就把程序给隐藏 if(taskInfo.getPackageName().equals(getPackageName())){ //隐藏 holder.tv_app_status.setVisibility(View.INVISIBLE); }else{ //显示 holder.tv_app_status.setVisibility(View.VISIBLE); } return view; } } static class ViewHolder { ImageView iv_app_icon; TextView tv_app_name; TextView tv_app_memory_size; CheckBox tv_app_status; } private void initData() { new Thread() { public void run() { taskInfos = TaskInfoParser .getTaskInfos(TaskManagerActivity.this); userTaskInfos = new ArrayList (); systemAppInfos = new ArrayList (); for (TaskInfo taskInfo : taskInfos) { if (taskInfo.isUserApp()) { userTaskInfos.add(taskInfo); } else { systemAppInfos.add(taskInfo); } } runOnUiThread(new Runnable() { @Override public void run() { adapter = new TaskManagerAdapter(); list_view.setAdapter(adapter); } }); }; }.start(); } /** * 区别: * ActivityManager 活动管理器(任务管理器) * packageManager 包管理器 */ private void initUI() { setContentView(R.layout.activity_task_manager); ViewUtils.inject(this); processCount = SystemInfoUtils.getProcessCount(this); tv_task_process_count.setText("进程:" + processCount + "个"); availMem = SystemInfoUtils.getAvailMem(this); totalMem = SystemInfoUtils.getTotalMem(this); tv_task_memory.setText("剩余/总内存:" + Formatter.formatFileSize(TaskManagerActivity.this, availMem) + "/" + Formatter.formatFileSize(TaskManagerActivity.this, totalMem)); list_view.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { // 得到当前点击listview的对象,getItemAtPosition()返回的是取决于getItem()方法 Object object = list_view.getItemAtPosition(position); if (object != null && object instanceof TaskInfo) { TaskInfo taskInfo = (TaskInfo) object; ViewHolder holder = (ViewHolder) view.getTag(); if(taskInfo.getPackageName().equals(getPackageName())){ return; } // 判断当前的item是否被勾选上 /** * 如果被勾选上了。那么就改成没有勾选。 如果没有勾选。就改成已经勾选 */ if (taskInfo.isChecked()) { taskInfo.setChecked(false); holder.tv_app_status.setChecked(false); } else { taskInfo.setChecked(true); holder.tv_app_status.setChecked(true); } } } }); } /** * 全选 */ public void selectAll(View view) { for (TaskInfo taskInfo : userTaskInfos) { // 判断当前的用户程序是不是自己的程序。如果是自己的程序。那么就把文本框隐藏 if (taskInfo.getPackageName().equals(getPackageName())) { continue; } taskInfo.setChecked(true); } for (TaskInfo taskInfo : systemAppInfos) { taskInfo.setChecked(true); } // 一定要注意。一旦数据发生改变一定要刷新 adapter.notifyDataSetChanged(); } /** * 反选 */ public void selectOppsite(View view) { for (TaskInfo taskInfo : userTaskInfos) { // 判断当前的用户程序是不是自己的程序。如果是自己的程序。那么就把文本框隐藏 if (taskInfo.getPackageName().equals(getPackageName())) { continue; } taskInfo.setChecked(!taskInfo.isChecked()); } for (TaskInfo taskInfo : systemAppInfos) { taskInfo.setChecked(!taskInfo.isChecked()); } adapter.notifyDataSetChanged(); } /** * 清理进程 */ public void killProcess(View view) { // 想杀死进程。首先必须得到进程管理器 ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); // 清理进程的集合 List killLists = new ArrayList (); // 清理的总共的进程个数 int totalCount = 0; // 清理的进程的大小 int killMem = 0; for (TaskInfo taskInfo : userTaskInfos) { if (taskInfo.isChecked()) { killLists.add(taskInfo); // userTaskInfos.remove(taskInfo); totalCount++; killMem += taskInfo.getMemorySize(); } } for (TaskInfo taskInfo : systemAppInfos) { if (taskInfo.isChecked()) { killLists.add(taskInfo); // systemAppInfos.remove(taskInfo); totalCount++; killMem += taskInfo.getMemorySize(); // 杀死进程 参数表示包名 activityManager.killBackgroundProcesses(taskInfo .getPackageName()); } } /** * 注意: 当集合在迭代的时候。不能修改集合的大小 */ for (TaskInfo taskInfo : killLists) { // 判断是否是用户app if (taskInfo.isUserApp()) { userTaskInfos.remove(taskInfo); // 杀死进程 参数表示包名 activityManager.killBackgroundProcesses(taskInfo .getPackageName()); } else { systemAppInfos.remove(taskInfo); // 杀死进程 参数表示包名 activityManager.killBackgroundProcesses(taskInfo .getPackageName()); } } UIUtils.showToast( TaskManagerActivity.this, "共清理" + totalCount + "个进程,释放" + Formatter.formatFileSize(TaskManagerActivity.this, killMem) + "内存"); //processCount 表示总共有多少个进程 //totalCount 当前清理了多少个进程 processCount -= totalCount; tv_task_process_count.setText("进程:"+ processCount +"个"); // tv_task_memory.setText("剩余/总内存:" + Formatter.formatFileSize(TaskManagerActivity.this, availMem + killMem) + "/" + Formatter.formatFileSize(TaskManagerActivity.this, totalMem)); // 刷新界面 adapter.notifyDataSetChanged(); } /** * 打开设置界面 */ public void openSetting(View view){ Intent intent = new Intent(this,TaskManagerSettingActivity.class); startActivity(intent); }}
package com.itheima.mobileguard.utils;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStreamReader;import java.util.List;import android.R.integer;import android.app.ActivityManager;import android.app.ActivityManager.MemoryInfo;import android.app.ActivityManager.RunningAppProcessInfo;import android.app.ActivityManager.RunningServiceInfo;import android.content.Context;public class SystemInfoUtils { /** * 判断一个服务是否处于运行状态 * 上下文 */ public static boolean isServiceRunning(Context context, String className) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); Listinfos = am.getRunningServices(200); for (RunningServiceInfo info : infos) { String serviceClassName = info.service.getClassName(); if (className.equals(serviceClassName)) { return true; } } return false; } /** * 返回进程的总个数 */ public static int getProcessCount(Context context) { // 得到进程管理者 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); // 获取到当前手机上面所有运行的进程 List runningAppProcesses = activityManager .getRunningAppProcesses(); // 获取手机上面一共有多少个进程 return runningAppProcesses.size(); } public static long getAvailMem(Context context) { // 得到进程管理者 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); // 获取到内存的基本信息 activityManager.getMemoryInfo(memoryInfo); // 获取到剩余内存 return memoryInfo.availMem; } public static long getTotalMem(Context context) { // 获取到总内存 /* * 这个地方不能直接跑到低版本的手机上面 MemTotal: 344740 kB "/proc/meminfo" */ try { // /proc/meminfo 配置文件的路径 FileInputStream fis = new FileInputStream(new File("/proc/meminfo")); BufferedReader reader = new BufferedReader(new InputStreamReader( fis)); String readLine = reader.readLine(); StringBuffer sb = new StringBuffer(); for (char c : readLine.toCharArray()) { if (c >= '0' && c <= '9') { sb.append(c); } } return Long.parseLong(sb.toString()) * 1024; } catch (Exception e) { e.printStackTrace(); } return 0; }}
package com.itheima.mobileguard.engine;import java.util.ArrayList;import java.util.List;import android.R.integer;import android.app.ActivityManager;import android.app.ActivityManager.RunningAppProcessInfo;import android.content.Context;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.graphics.drawable.Drawable;import android.os.Debug.MemoryInfo;import android.text.format.Formatter;import com.itheima.mobileguard.R;import com.itheima.mobileguard.domain.TaskInfo;/*public class TaskInfo { private Drawable icon; private String packageName; private String appName; private long memorySize; *//** * 是否是用户进程 *//* private boolean userApp; *//** * 判断当前的item的条目是否被勾选上 *//* private boolean checked;}*/public class TaskInfoParser { public static ListgetTaskInfos(Context context) { PackageManager packageManager = context.getPackageManager(); List TaskInfos = new ArrayList (); // 获取到进程管理器 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); // 获取到手机上面所有运行的进程 List appProcesses = activityManager .getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : appProcesses) { TaskInfo taskInfo = new TaskInfo(); // 获取到进程的名字 String processName = runningAppProcessInfo.processName; taskInfo.setPackageName(processName); try { // 获取到内存基本信息 /** * 这个里面一共只有一个数据 */ MemoryInfo[] memoryInfo = activityManager .getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid}); // Dirty弄脏 // 获取到总共弄脏多少内存(当前应用程序占用多少内存) int totalPrivateDirty = memoryInfo[0].getTotalPrivateDirty() * 1024;// System.out.println("==========="+totalPrivateDirty); taskInfo.setMemorySize(totalPrivateDirty); PackageInfo packageInfo = packageManager.getPackageInfo( processName, 0); // /获取到图片 Drawable icon = packageInfo.applicationInfo .loadIcon(packageManager); taskInfo.setIcon(icon); // 获取到应用的名字 String appName = packageInfo.applicationInfo.loadLabel( packageManager).toString(); taskInfo.setAppName(appName); System.out.println("-------------------"); System.out.println("processName="+processName); System.out.println("appName="+appName); //获取到当前应用程序的标记 //packageInfo.applicationInfo.flags 我们写的答案 //ApplicationInfo.FLAG_SYSTEM表示老师的该卷器 int flags = packageInfo.applicationInfo.flags; //ApplicationInfo.FLAG_SYSTEM 表示系统应用程序 if((flags & ApplicationInfo.FLAG_SYSTEM) != 0 ){ //系统应用 taskInfo.setUserApp(false); }else{// /用户应用 taskInfo.setUserApp(true); } } catch (Exception e) { e.printStackTrace(); // 系统核心库里面有些系统没有图标。必须给一个默认的图标 taskInfo.setAppName(processName); taskInfo.setIcon(context.getResources().getDrawable( R.drawable.ic_launcher)); } TaskInfos.add(taskInfo); } return TaskInfos; }}
package com.itheima.mobileguard.activities;import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeoutException;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.pm.PackageManager;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.text.format.Formatter;import android.util.Log;import android.view.Gravity;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.view.animation.AlphaAnimation;import android.view.animation.Animation;import android.view.animation.AnimationSet;import android.view.animation.ScaleAnimation;import android.widget.AbsListView;import android.widget.AbsListView.OnScrollListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.PopupWindow;import android.widget.TextView;import android.widget.Toast;import com.itheima.mobileguard.R;import com.itheima.mobileguard.domain.AppInfo;import com.itheima.mobileguard.engine.AppInfoParser;import com.stericson.RootTools.RootTools;public class AppManagerActivity extends Activity implements OnClickListener { public static final String TAG = "AppManagerActivity"; private TextView tv_avail_rom; private TextView tv_avail_sd; private LinearLayout ll_loading; private Button button; private TextView textView = null; /** * 使用的应用程序信息集合 */ private Listinfos; /** * 用户程序集合 */ private List userAppInfos; /** * 系统程序集合 */ private List systemAppInfos; private TextView tv_appsize_lable; private ListView lv_appmanger; private LinearLayout ll_start; private LinearLayout ll_share; private LinearLayout ll_uninstall; private LinearLayout ll_setting; /** * 被点击的条目对应的,appinfo对象 */ private AppInfo clickedAppInfo; /** * 悬浮窗体 */ private PopupWindow popupwindow; private UninstallReceiver receiver; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { // 隐藏正在加载的界面 ll_loading.setVisibility(View.INVISIBLE); lv_appmanger.setAdapter(new AppManagerAdapter()); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_manager); tv_appsize_lable = (TextView) findViewById(R.id.tv_appsize_lable); ll_loading = (LinearLayout) findViewById(R.id.ll_loading); tv_avail_rom = (TextView) findViewById(R.id.tv_avail_rom); tv_avail_sd = (TextView) findViewById(R.id.tv_avail_sd); lv_appmanger = (ListView) findViewById(R.id.lv_appmanger); long avail_sd = Environment.getExternalStorageDirectory() .getFreeSpace(); long avail_rom = Environment.getDataDirectory().getFreeSpace(); String str_avail_sd = Formatter.formatFileSize(this, avail_sd); String str_avail_rom = Formatter.formatFileSize(this, avail_rom); tv_avail_rom.setText("剩余手机内部:" + str_avail_rom); tv_avail_sd.setText("剩余SD卡:" + str_avail_sd); fillData(); // 给listview设置一个滚动状态的监听器 lv_appmanger.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } // 当listview被滚动的时候调用的方法 @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { dismissPopupWindow(); if (userAppInfos != null && systemAppInfos != null) { if (firstVisibleItem >= (userAppInfos.size() + 1)) { tv_appsize_lable.setText("系统程序:" + systemAppInfos.size() + "个"); } else { tv_appsize_lable.setText("用户程序:" + userAppInfos.size() + "个"); } } } }); // 给listview注册一个点击事件 lv_appmanger.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Object obj = lv_appmanger.getItemAtPosition(position); if (obj != null && obj instanceof AppInfo) { clickedAppInfo = (AppInfo) obj; View contentView = View.inflate(getApplicationContext(), R.layout.popup_item, null); ll_uninstall = (LinearLayout) contentView .findViewById(R.id.ll_uninstall); ll_start = (LinearLayout) contentView .findViewById(R.id.ll_start); ll_share = (LinearLayout) contentView .findViewById(R.id.ll_share); ll_setting = (LinearLayout) contentView .findViewById(R.id.ll_setting); ll_share.setOnClickListener(AppManagerActivity.this); ll_start.setOnClickListener(AppManagerActivity.this); ll_uninstall.setOnClickListener(AppManagerActivity.this); ll_setting.setOnClickListener(AppManagerActivity.this); dismissPopupWindow(); popupwindow = new PopupWindow(contentView, -2, -2); // 动画播放有一个前提条件: 窗体必须要有背景资源。 如果窗体没有背景,动画就播放不出来。 popupwindow.setBackgroundDrawable(new ColorDrawable( Color.TRANSPARENT)); int[] location = new int[2]; view.getLocationInWindow(location); popupwindow.showAtLocation(parent, Gravity.LEFT + Gravity.TOP, 60, location[1]); ScaleAnimation sa = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f); sa.setDuration(200); AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f); aa.setDuration(200); AnimationSet set = new AnimationSet(false); set.addAnimation(aa); set.addAnimation(sa); contentView.startAnimation(set); } } }); receiver = new UninstallReceiver(); IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); registerReceiver(receiver, filter); } // 填充数据的业务方法 private void fillData() { ll_loading.setVisibility(View.VISIBLE); new Thread() { public void run() { infos = AppInfoParser.getAppInfos(AppManagerActivity.this); userAppInfos = new ArrayList (); systemAppInfos = new ArrayList (); for (AppInfo info : infos) { if (info.isUserApp()) { // 用户程序 userAppInfos.add(info); } else { // 系统程序 systemAppInfos.add(info); } } // 设置界面了。 handler.sendEmptyMessage(0); }; }.start(); } private void dismissPopupWindow() { if (popupwindow != null && popupwindow.isShowing()) { popupwindow.dismiss(); popupwindow = null; } } static class ViewHolder { ImageView iv_app_icon; TextView tv_app_name; TextView tv_app_size; TextView tv_app_location; } private class AppManagerAdapter extends BaseAdapter { @Override public int getCount() { // return infos.size(); // 多了两个显示条目个数的textview小标签 所有加2 return userAppInfos.size() + systemAppInfos.size() + 2; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { // 第0个位置显示的应该是 用户程序的个数的标签。 TextView tv = new TextView(getApplicationContext()); tv.setBackgroundColor(Color.GRAY); tv.setTextColor(Color.WHITE); tv.setText("用户程序:" + userAppInfos.size() + "个"); return tv; } else if (position == (userAppInfos.size() + 1)) { TextView tv = new TextView(getApplicationContext()); tv.setBackgroundColor(Color.GRAY); tv.setTextColor(Color.WHITE); tv.setText("系统程序:" + systemAppInfos.size() + "个"); return tv; } AppInfo appInfo; if (position < (userAppInfos.size() + 1)) { // 用户程序 appInfo = userAppInfos.get(position - 1);// 多了一个textview的标签 , // 位置需要-1 } else { // 系统程序 int location = position - 1 - userAppInfos.size() - 1; appInfo = systemAppInfos.get(location); } View view; ViewHolder holder; if (convertView != null && convertView instanceof LinearLayout) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = View.inflate(getApplicationContext(), R.layout.item_app_manager, null); holder = new ViewHolder(); holder.iv_app_icon = (ImageView) view .findViewById(R.id.iv_app_icon); holder.tv_app_name = (TextView) view .findViewById(R.id.tv_app_name); holder.tv_app_size = (TextView) view .findViewById(R.id.tv_app_size); holder.tv_app_location = (TextView) view .findViewById(R.id.tv_app_location); view.setTag(holder); } // 得到当前位置的appinfo对象 holder.iv_app_icon.setImageDrawable(appInfo.getIcon()); holder.tv_app_name.setText(appInfo.getName()); holder.tv_app_size.setText(Formatter.formatFileSize( getApplicationContext(), appInfo.getAppSize())); if (appInfo.isInRom()) { holder.tv_app_location.setText("手机内存"); } else { holder.tv_app_location.setText("外部存储"); } return view; } @Override public Object getItem(int position) { if (position == 0) { // 第0个位置显示的应该是 用户程序的个数的标签。 return null; } else if (position == (userAppInfos.size() + 1)) { return null; } AppInfo appInfo; if (position < (userAppInfos.size() + 1)) { // 用户程序 appInfo = userAppInfos.get(position - 1);// 多了一个textview的标签 , // 位置需要-1 } else { // 系统程序 int location = position - 1 - userAppInfos.size() - 1; appInfo = systemAppInfos.get(location); } return appInfo; } @Override public long getItemId(int position) { return position; } } @Override protected void onDestroy() { dismissPopupWindow(); unregisterReceiver(receiver); receiver = null; super.onDestroy(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll_share: Log.i(TAG, "分享:" + clickedAppInfo.getPackname()); shareApplication(); break; case R.id.ll_uninstall: Log.i(TAG, "卸载:" + clickedAppInfo.getPackname()); uninstallApplication(); break; case R.id.ll_start: Log.i(TAG, "开启:" + clickedAppInfo.getPackname()); startApplication(); break; case R.id.ll_setting: Log.i(TAG, "设置:" + clickedAppInfo.getPackname()); viewAppDetail(); break; } dismissPopupWindow(); } private void viewAppDetail() { Intent intent = new Intent(); intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.addCategory(Intent.CATEGORY_DEFAULT); // dat=package:com.itheima.mobileguard intent.setData(Uri.parse("package:" + clickedAppInfo.getPackname())); startActivity(intent); } /** * 卸载软件 */ private void uninstallApplication() { if (clickedAppInfo.isUserApp()) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + clickedAppInfo.getPackname())); startActivity(intent); }else{ //系统应用 ,root权限 利用linux命令删除文件。 if(!RootTools.isRootAvailable()){ Toast.makeText(this, "卸载系统应用,必须要root权限", 0).show(); return ; } try { if(!RootTools.isAccessGiven()){ Toast.makeText(this, "请授权黑马小护卫root权限", 0).show(); return ; } RootTools.sendShell("mount -o remount ,rw /system", 3000); RootTools.sendShell("rm -r "+clickedAppInfo.getApkpath(), 30000); } catch (Exception e) { e.printStackTrace(); } } } /** * 开启应用程序 */ private void startApplication() { // 打开这个应用程序的入口activity。 PackageManager pm = getPackageManager(); Intent intent = pm.getLaunchIntentForPackage(clickedAppInfo .getPackname()); if (intent != null) { startActivity(intent); } else { Toast.makeText(this, "该应用没有启动界面", 0).show(); } } /** * 分享应用 */ private void shareApplication() { Intent intent = new Intent("android.intent.action.SEND"); intent.addCategory("android.intent.category.DEFAULT"); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, "推荐您使用一款软件,名称叫:" + clickedAppInfo.getName() + "下载路径:https://play.google.com/store/apps/details?id=" + clickedAppInfo.getPackname()); startActivity(intent); } private class UninstallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String info = intent.getData().toString(); System.out.println(info); fillData(); } }}
package com.itheima.mobileguard.activities;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.View;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import com.itheima.mobileguard.R;import com.itheima.mobileguard.services.KillProcessService;import com.itheima.mobileguard.utils.SharedPreferencesUtils;import com.itheima.mobileguard.utils.SystemInfoUtils;public class TaskManagerSettingActivity extends Activity { private SharedPreferences sp; private CheckBox cb_status_kill_process; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initUI(); } private void initUI() { setContentView(R.layout.activity_task_manager_setting); CheckBox cb_status = (CheckBox) findViewById(R.id.cb_status); //设置是否选中 cb_status.setChecked(SharedPreferencesUtils.getBoolean(TaskManagerSettingActivity.this, "is_show_system", false)); cb_status.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SharedPreferencesUtils.saveBoolean(TaskManagerSettingActivity.this, "is_show_system", isChecked); /*public class SharedPreferencesUtils { public static final String SP_NAME = "config"; public static void saveBoolean(Context context,String key , boolean value){ SharedPreferences sp = context.getSharedPreferences(SP_NAME, 0); sp.edit().putBoolean(key, value).commit(); } public static boolean getBoolean(Context context,String key,boolean defValue){ SharedPreferences sp = context.getSharedPreferences(SP_NAME, 0); return sp.getBoolean(key, defValue); } }*/ } }); //定时清理进程 cb_status_kill_process = (CheckBox) findViewById(R.id.cb_status_kill_process); final Intent intent = new Intent(this,KillProcessService.class); cb_status_kill_process.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ startService(intent); }else{ stopService(intent); } } }); } @Override protected void onStart() { super.onStart(); if(SystemInfoUtils.isServiceRunning(TaskManagerSettingActivity.this, "com.itheima.mobileguard.services.KillProcessService")){ cb_status_kill_process.setChecked(true); }else{ cb_status_kill_process.setChecked(false); } }}
package com.itheima.mobileguard.services;import java.util.List;import java.util.Timer;import java.util.TimerTask;import android.app.ActivityManager;import android.app.ActivityManager.RunningAppProcessInfo;import android.app.Service;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.IBinder;import android.text.format.Time;public class KillProcessService extends Service { private LockScreenReceiver receiver; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } private class LockScreenReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //获取到进程管理器 ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); //获取到手机上面所以正在运行的进程 ListappProcesses = activityManager.getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : appProcesses) { activityManager.killBackgroundProcesses(runningAppProcessInfo.processName); } } } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); receiver = new LockScreenReceiver(); //锁屏的过滤器 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); //注册一个锁屏的广播 registerReceiver(receiver, filter); // Timer timer = new Timer();// // TimerTask task = new TimerTask() {// // @Override// public void run() {// // 写我们的业务逻辑// System.out.println("我被调用了");// }// };// //进行定时调度// /**// * 第一个参数 表示用那个类进行调度// * // * 第二个参数表示时间// */// timer.schedule(task, 0,1000); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); //当应用程序推出的时候。需要把广播反注册掉 unregisterReceiver(receiver); //手动回收 receiver = null; }}