Android简易任务管理器


Android简易任务管理器

程序运行界面:


 

1.AndroidManifest

<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.pigrush.taskmanager"
   android:versionCode="1"
   android:versionName="1.0.0" >
 
    <uses-permissionandroid:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
   
    <application
       android:icon="@drawable/icon"
       android:label="@string/app_name" >
        <activity
           android:name="com.pigrush.taskmanager.TaskManagerActivity"
           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>


2. 布局文件

TaskManagerActivity对应的布局文件,文件名为avtivity_taskmanager.xml

<?xml version="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="#999999"
   android:orientation="vertical" >
 
    <ListView
       android:id="@+id/taskmanager_listview"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:padding="10dp" >
    </ListView>
</LinearLayout>

RunningProcessAdapter对应的布局文件,文件名为process_info_list_item.xml

<?xml version="1.0"encoding="UTF-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal" >
 
    <ImageView
       android:id="@+id/process_info_item_img"
       android:layout_width="30dp"
         android:layout_height="30dp"
         android:scaleType="fitXY"
       />
    <TextView
       android:id="@+id/process_info_item_name"
       android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginLeft="10dp"
         android:layout_marginRight="10dp"
       />
    <TextView
       android:id="@+id/process_info_item_size"
       android:layout_gravity="right"
       android:gravity="right"
       android:layout_marginLeft="20dp"
       android:layout_marginRight="20dp"
       android:layout_width="fill_parent"
         android:layout_height="wrap_content"
       />
</LinearLayout>

3. 源码

应用启动时的activity对应的类为源码如下:

 

/*
 *@App Name: task manager
 *@Author: Johnny
 *@Date: Sept. 25th 2014
 *@Email: xuanjianyongsd@163.com
 *@Introduction: show task which r running background
 *and do some operation, if any question ,send me email.
 */
 
/*
 *main activity used to show tasks running background
 */
public class TaskManagerActivity extendsActivity {
        
         private static final String TAG = "TaskManagerActivity";
        
         private static final String REFRESH_FINISH_ACTION="com.pigrush.taskmanager.refreshfinish";
        
         public ActivityManager activityManager;
        
         private RunningProcessAdapter runningProcessAdapter;
        
         private ListView runningProcessList;
        
         private PackageDetail processDetail;
        
         //broadcastReceiver when refresh isover
         private BroadcastReceiver refreshFinishBrdCst=new BroadcastReceiver() {
                   @Override
                   public void onReceive(Context arg0, Intent arg1) {
                            // TODO Auto-generated method stub
                            runningProcessList.setAdapter(runningProcessAdapter);
                            TaskManagerActivity.this.setProgressBarIndeterminateVisibility(false);
                            Log.i(TAG,"refreshFinishBrdCst");
                   }
         };
        
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.avtivity_taskmanager);
        IntentFilter flt=new IntentFilter(REFRESH_FINISH_ACTION);
        registerReceiver(refreshFinishBrdCst, flt);
        runningProcessList=(ListView) findViewById(R.id.taskmanager_listview);
        Log.i(TAG,"onCreate");
    }
 
    //refresh everytime the application show on the screen
         @Override
         protected void onResume() {
                   // TODO Auto-generated method stub
                   super.onResume();
                   processDetail=new PackageDetail(this.getApplicationContext());
                   refreshTaskManager();
                  
                   Log.i(TAG, "onResume");
         }
        
         public void refreshTaskManager(){
                   TaskManagerActivity.this.setProgressBarIndeterminateVisibility(true);
                   Thread refreshThread=newThread(new Runnable() {
                            public void run() {
                                     // TODO Auto-generated method stub
                                     getRunningProcess();
                                     Intent i=new Intent(REFRESH_FINISH_ACTION);
                                     sendBroadcast(i);
                            }
                   });
                   refreshThread.start();
         }
        
         private void getRunningProcess() {
                   List<AppInfo> appInfoList=new ArrayList<AppInfo>();
                   if (activityManager == null) {
                            activityManager =(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                   }
                   List<RunningAppProcessInfo> runInfoList = activityManager.getRunningAppProcesses();
                   for (RunningAppProcessInfo runInfo : runInfoList) {
                            if(runInfo.processName.equals("system")
                                               || runInfo.processName.equals("com.android.phone")) {
                                     continue;
                            }
                            AppInfo appInfo=processDetail.getApplicationInfo(runInfo.processName);
                            appInfoList.add(appInfo);
                   }
                   runningProcessAdapter=new RunningProcessAdapter(this,appInfoList);
         }
        
         public ActivityManager getActivityManager(){
                   if(activityManager==null){
                            activityManager =(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                   }
                   return activityManager;
         }
}

该类涉及到的类有PackageDetailRunningProcessAdapter以及AppInfo

AppInfo为应用的相关信息,类定义如下:

 

public class AppInfo {
         public String appName;
         public Drawable icon;
         public String size;
         public String packageName;
}

PackageDetail为应用的包信息,源码如下:

public class PackageDetail{
        
         private PackageManager packageManager;
        
         private List<ApplicationInfo> appInfoList;
        
         private Map<String, String> mapProcessSize;
        
         public PackageDetail(Context context){
                   packageManager=context.getPackageManager();
                   appInfoList = packageManager.getInstalledApplications
                                     (PackageManager.GET_UNINSTALLED_PACKAGES);
                   mapProcessSize=RunScript.getProcessInfo();
         }
        
         public AppInfo getApplicationInfo(StringprocessName){
                   if(processName==null){
                            return null;
                   }
                   for(ApplicationInfo info:appInfoList){
                            if(processName.equals(info.processName)){
                                     AppInfoappInfo=new AppInfo();
                                     appInfo.appName=(String) info.loadLabel(packageManager);
                                     appInfo.icon=info.loadIcon(packageManager);
                                     appInfo.size=mapProcessSize.get(processName);
                                     appInfo.packageName=processName;
                                     return appInfo;
                            }
                   }
                   return null;
         }
}


应用信息里通过RunScript.getProcessInfo();来获得当前运行的应用信息,通过执行

Runtime.getRuntime().exec("ps") 来实现,并对返回的数据进行解析得到当前程序的RSS,在该处可以根据自己的需要获得应用的其他信息,如PID等。

 

public class RunScript {
 
         privatestatic int retVal;
 
         publicstatic Map<String, String> getProcessInfo() {
 
                   finalMap<String, String> mapProcessInfo = new HashMap<String, String>();
 
                   try{
                            finalProcess process = Runtime.getRuntime().exec("ps");
 
                            ThreadtOut = new Thread(new Runnable() {
 
                                     publicvoid run() {
                                               //TODO Auto-generated method stub
                                               StringstrLine = null;
                                               BufferedReaderbufReader = new BufferedReader(
                                                                 newInputStreamReader(process.getInputStream()));
                                               try{
                                                        while((strLine = bufReader.readLine()) != null) {
                                                                 //processInfo.put(arg0,arg1);
                                                                 String[]pStr = strLine.split("[\\s]+");
                                                                 if(pStr.length==9){
                                                                           mapProcessInfo.put(pStr[8],pStr[4]);
                                                                 }
                                                        }
                                               }catch (IOException e) {
                                                        //TODO Auto-generated catch block
                                                        e.printStackTrace();
                                               }finally{
                                                        try{
                                                                 bufReader.close();
                                                        }catch (IOException e) {
                                                                 //TODO Auto-generated catch block
                                                                 e.printStackTrace();
                                                        }
                                               }
                                     }
                            });
                            tOut.start();
                            while(tOut.isAlive()) {
                try {
                                               Thread.sleep(50);
                                     }catch (InterruptedException e) {
                                               //TODO Auto-generated catch block
                                               e.printStackTrace();
                                     }
           }
                            try{
                                     retVal= process.waitFor();
                                    
                            }catch (InterruptedException e) {
                                     //TODO Auto-generated catch block
                                     e.printStackTrace();
                            }
                   }catch (IOException e) {
                            //TODO Auto-generated catch block
                            e.printStackTrace();
                   }
                   returnmapProcessInfo;
         }
 
         publicint getRetVal() {
                   returnretVal;
         }
}

RunningProcessAdapter为listview对应的自定义adapter,定义如下:

 

public class RunningProcessAdapter extendsBaseAdapter {
 
         privateActivity mActivity;
 
         privateList<AppInfo> mAppInfoList;
 
         privateLayoutInflater mInflater;
        
         publicRunningProcessAdapter(Activity activity, List<AppInfo> appInfoList) {
                   mAppInfoList= appInfoList;
                   mActivity= activity;
                   //detailDlg=newDetailDialog(activity);
         }
 
         publicint getCount() {
                   //TODO Auto-generated method stub
                   returnmAppInfoList.size();
         }
 
         publicObject getItem(int arg0) {
                   //TODO Auto-generated method stub
                   returnmAppInfoList.get(arg0);
         }
 
         publiclong getItemId(int arg0) {
                   //TODO Auto-generated method stub
                   returnarg0;
         }
 
         publicView getView(final int postion, View contentView, ViewGroup arg2) {
                   //TODO Auto-generated method stub
                   ViewHolderholder;
                   if(mInflater == null) {
                            mInflater= LayoutInflater.from(mActivity);
                   }
                   if(contentView == null) {
                            contentView= mInflater.inflate(R.layout.process_info_list_item,null);
                            holder= new ViewHolder();
                            holder.name= (TextView) contentView.findViewById(R.id.process_info_item_name);
                            holder.img=(ImageView)contentView.findViewById(R.id.process_info_item_img);
                            holder.size=(TextView)contentView.findViewById(R.id.process_info_item_size);
                           
                            contentView.setTag(holder);
                   }else {
                            holder= (ViewHolder) contentView.getTag();
                   }
                   holder.name.setText(mAppInfoList.get(postion).appName);
                   holder.img.setImageDrawable(mAppInfoList.get(postion).icon);
                   holder.size.setText(mAppInfoList.get(postion).size);
                   contentView.setOnClickListener(newOnClickListener() {
                           
                            publicvoid onClick(View arg0) {
                                     //TODO Auto-generated method stub
                                     DetailDialog.show((TaskManagerActivity)mActivity,
                                                        mAppInfoList.get(postion).packageName);
                            }
                   });
                   returncontentView;
         }
 
         privateclass ViewHolder {
                   TextViewname;
                   ImageViewimg;
                   TextViewsize;
         }
}

RunningProcessAdapter里定义了用户单击的响应,显示DetailDialog,用来显示用户可以进行的操作:返回,切换至该程序,结束进程以及卸载程序

 

public class DetailDialog{
        
         privatestatic final String TAG="DetailDialog";
        
         privatestatic List<ResolveInfo> infoList = null;
 
         publicstatic void show(final TaskManagerActivity activity,final String packageName){
                   AlertDialogaltDlg=new AlertDialog.Builder(activity)
                   .setTitle("Operation")
                   .setItems(R.array.task_operation,new OnClickListener() {
                           
                            publicvoid onClick(DialogInterface arg0, int arg1) {
                                     //TODO Auto-generated method stub
                                     switch(arg1){
                                     case1:     //切换至该程序
                                               if(activity.getPackageName().equals(packageName))return;
                                               Intenti=getIntent(activity,packageName);
                                               if(i!=null){
                                                        activity.startActivity(i);
                                               }
                                               break;
                                     case2:     //结束进程
                                               Log.w("kill",packageName);
                                              if(activity.getPackageName().equals(packageName))return;
                                               activity.getActivityManager().killBackgroundProcesses(packageName);
                                               Toast.makeText(activity,"进程被杀死!",Toast.LENGTH_SHORT).show();
                                               activity.refreshTaskManager();
                                               break;
                                     case3:     //卸载程序
                                               Uriuri = Uri.fromParts("package", packageName, null);
                    Intent it = newIntent(Intent.ACTION_DELETE, uri);
                    try {
                       activity.startActivity(it);
                    } catch (Exception e) {
                       Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                                               break;
                                     default:
                                               break;
                                     }
                            }
                   })
                   .create();
                   altDlg.show();
         }
        
         publicstatic Intent getIntent(Activity activity,String packageName){
                   PackageManagerpm=activity.getApplicationContext().getPackageManager();
                   Intenti=pm.getLaunchIntentForPackage(packageName);
                   if(i!=null){
                            i= i.cloneFilter();
                      i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                       Log.i(TAG,"getLaunchIntentForPackage");
                       return i;
                   }
                  
                   try{
                            PackageInfopi=pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
                            if(pi.activities.length==1){
                                     i= new Intent(Intent.ACTION_MAIN);
                                i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                                i.setClassName(packageName,pi.activities[0].name);
                               Log.i(TAG,"pi.activities.length==1");
                                return i;
                            }
                   }catch (NameNotFoundException e) {
                            //TODO Auto-generated catch block
                            e.printStackTrace();
                   }
                 
                   i= getIntent(packageName, pm);
                   if(i!=null){
                            i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                            Log.i(TAG,"IntentList.getIntent(packageName,pm)");
                       return i;
                   }
                   returni;
         }
        
   public static synchronized List<ResolveInfo> getRunableList(PackageManagerpm, boolean reload) {
       if (infoList == null || reload == true) {
           Intent baseIntent = new Intent(Intent.ACTION_MAIN);
           baseIntent.addCategory(Intent.CATEGORY_LAUNCHER);
           infoList = pm.queryIntentActivities(baseIntent, 0);
       }
       return infoList;
    }
 
   public static Intent getIntent(String packageName, PackageManager pm) {
       List<ResolveInfo> list = getRunableList(pm, false);
       for (ResolveInfo info : list) {
           if (packageName.equals(info.activityInfo.packageName)) {
                Intent i = newIntent(Intent.ACTION_MAIN);
               i.addCategory(Intent.CATEGORY_LAUNCHER);
                i.setClassName(packageName,info.activityInfo.name);
                return i;
           }
       }
       return null;
    }
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值