killBackgroundProcesses不起作用

时间:2012-03-27 09:15:45

标签: android android-activity android-package-managers

我试图在我的项目中使用killBackgroundProcesses()方法杀死正在运行的应用程序(android Api 2.2)killBackgroundProcesses()不会杀死正在运行的应用程序。我声明在应用程序的清单文件中杀死appiction所需的所有权限。

吹码仅从正在运行的应用列表中删除列表项。无法杀死该应用程序。

Before killing running application After killing running application "launcher" refreshing list view it again show "launcher" still running

代码:

 public class RunningAppActivity extends Activity implements OnItemClickListener {

       /* whether or not to include system apps */
       private ListView mAppsList;
       private RunningAppListAdapter mAdapter;
       private List<RunningAppEntity> mApps;
       private Context mContext;
       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.appmanager);
          mContext = this;
       }

       @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
              mAppsList = (ListView) findViewById(R.id.appslist);
              mAppsList.setOnItemClickListener(this);
              mApps = loadRunningApps();
              mAdapter = new RunningAppListAdapter(getApplicationContext());
              mAdapter.setListItems(mApps);
              mAppsList.setAdapter(mAdapter);
              new LoadIconsTask().execute(mApps.toArray(new RunningAppEntity[]{}));


        }
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

          final RunningAppEntity app = (RunningAppEntity) parent.getItemAtPosition(position);
          final int appPosition = position;
          ActivityManager am = (ActivityManager)mContext.getSystemService(ACTIVITY_SERVICE);
          am.killBackgroundProcesses(app.getPackageName());
          am.restartPackage(app.getPackageName());
          Log.d("","Kill : "+app.getPackageName());
          mApps.remove(appPosition);
          mAdapter.notifyDataSetChanged();

       }

       private List<RunningAppEntity> loadRunningApps() {
          List<RunningAppEntity> apps = new ArrayList<RunningAppEntity>();
          ActivityManager am = (ActivityManager) mContext.getSystemService(Activity.ACTIVITY_SERVICE);
          List<RunningTaskInfo> rt =am.getRunningTasks(Integer.MAX_VALUE);
          PackageManager pack = this.getPackageManager();
          for(int i=0;i<rt.size();i++){
             RunningAppEntity rapp = new RunningAppEntity();
              String packageName = rt.get(i).baseActivity.getPackageName();
           // Drawable d=null;
              String appName = null;
              try {
                //  d = pack.getApplicationIcon(packageName);
                  appName = ((String)pack.getApplicationLabel(pack.getApplicationInfo(packageName,PackageManager.GET_META_DATA)));

              } catch (NameNotFoundException e) {
                  e.printStackTrace();
              }
              rapp.setPackageName(packageName);
              rapp.setAppName(appName);
              apps.add(rapp);
       }
          return apps;
       }



       /**
        * An asynchronous task to load the icons of the installed applications.
        */
       private class LoadIconsTask extends AsyncTask<RunningAppEntity, Void, Void> {

          @Override
          protected void onPostExecute(Void result) {
             mAdapter.notifyDataSetChanged();
          }

        @Override
        protected Void doInBackground(RunningAppEntity... params) {
            // TODO Auto-generated method stub

              Map<String, Drawable> icons = new HashMap<String, Drawable>();
                 PackageManager manager = getApplicationContext().getPackageManager();

                 for (RunningAppEntity app : params) {
                    String pkgName = app.getPackageName();
                    Drawable ico = null;
                    try {
                       Intent i = manager.getLaunchIntentForPackage(pkgName);
                       if (i != null) {
                          ico = manager.getActivityIcon(i);
                       }
                    } catch (NameNotFoundException e) {
                       Log.e("ERROR", "Unable to find icon for package '" + pkgName + "': " + e.getMessage());
                    }
                    icons.put(app.getPackageName(), ico);
                 }
                 mAdapter.setIcons(icons);
            return null;
        }
      }

    }

列表视图适配器:

    public class RunningAppListAdapter extends BaseAdapter {

   private LayoutInflater mInflater;

   private List<RunningAppEntity> mApps;
   private Map<String, Drawable> mIcons;
   private Drawable mStdImg;


   public RunningAppListAdapter(Context context) {
      mInflater = LayoutInflater.from(context);
      mStdImg = context.getResources().getDrawable(R.drawable.icon);
   }

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

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

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

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {

      AppViewHolder holder;
      if(convertView == null) {
         convertView = mInflater.inflate(R.layout.row, null);
         holder = new AppViewHolder();
         holder.mTitle = (TextView) convertView.findViewById(R.id.apptitle);
         holder.mIcon = (ImageView) convertView.findViewById(R.id.appicon);
         convertView.setTag(holder);
      } else {
         holder = (AppViewHolder) convertView.getTag();
      }

      RunningAppEntity app = mApps.get(position);
      holder.setTitle(app.getAppName());
      if (mIcons == null || mIcons.get(app.getPackageName()) == null) {
         holder.setIcon(mStdImg);
      } else {
         holder.setIcon(mIcons.get(app.getPackageName()));
      }

      return convertView;
   }


   public void setListItems(List<RunningAppEntity> list) {
      mApps = list;
   }


   public void setIcons(Map<String, Drawable> icons) {
      this.mIcons = icons;
   }


   public Map<String, Drawable> getIcons() {
      return mIcons;
   }

   public class AppViewHolder {

      private TextView mTitle;
      private ImageView mIcon;


      public void setTitle(String title) {
         mTitle.setText(title);
      }


      public void setIcon(Drawable img) {
         if (img != null) {
            mIcon.setImageDrawable(img);
         }
      }
   }
}

3 个答案:

答案 0 :(得分:2)

使用ActivityManager杀死进程

首先,添加权限(AndroidManifest.xml):

android.permission.KILL_BACKGROUND_PROCESSES

其次,使用此方法:

public void amKillProcess(String process)
{
    ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();

    for(RunningAppProcessInfo runningProcess : runningProcesses) 
    {
        if(runningProcess.processName.equals(process)) 
        {               
            android.os.Process.sendSignal(runningProcess.pid, android.os.Process.SIGNAL_KILL);   
        }
    }
}

用法:

amKillProcess("com.example.myapp");

答案 1 :(得分:2)

你不能杀死你不拥有的另一个进程。请参阅:http://developer.android.com/reference/android/os/Process.html#killProcess(int)

中的Android文档

但是,您可以调用ActivityManager的API - killBackgroundProcesses http://developer.android.com/reference/android/app/ActivityManager.html#killBackgroundProcesses(java.lang.String)

答案 2 :(得分:0)

  1. 在Google API中,它表示“系统将根据需要在将来重新启动这些流程。” ,系统会重启您的被杀死进程吗?你可以检查被杀死的进程使用这个命令“for i in {1..10000}; do sleep 0.3; adb shell ps | grep XXX; echo; done”

  2. 另一种可以杀死软件包的方法,它不会重启

    Method forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);  
    forceStopPackage.setAccessible(true);  
    forceStopPackage.invoke(am, yourpkgname); 
    
  3. 但是对于此方法,您需要添加系统sharedUserId android:sharedUserId="android.uid.system"

    permission: android.permission.FORCE_STOP_PACKAGES