Prashant Kadam
Prashant Kadam

Reputation: 1207

killBackgroundProcesses is not working

i ma trying to kill running app using killBackgroundProcesses() method in my project (android Api 2.2) killBackgroundProcesses() not kill the running apps. i declare all permission required to kill appiction in manifest file of application.

the blow code only remove the list item from list of running app. unable to kill the application.

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

Code :

 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;
        }
      }

    }

List view Adapter :

    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);
         }
      }
   }
}

Upvotes: 1

Views: 13217

Answers (3)

Bamerza
Bamerza

Reputation: 1375

You cannot kill another process which you do not own. See the Android documentation from : http://developer.android.com/reference/android/os/Process.html#killProcess(int)

However, you can call ActivityManager's API - killBackgroundProcesses http://developer.android.com/reference/android/app/ActivityManager.html#killBackgroundProcesses(java.lang.String)

Upvotes: 2

vodka182
vodka182

Reputation: 31

To kill a process using ActivityManager

First, add the permission (AndroidManifest.xml):

android.permission.KILL_BACKGROUND_PROCESSES

Second, use this method:

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);   
        }
    }
}

Usage:

amKillProcess("com.example.myapp");

Upvotes: 3

pangang
pangang

Reputation: 165

  1. In google API it says "the system will take care of restarting these processes in the future as needed." , so is your killed process restart by system ? you could check the killed process use this command "for i in {1..10000}; do sleep 0.3; adb shell ps | grep XXX; echo; done"

  2. Another way you could kill the package and it will not restart

    Method forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);  
    forceStopPackage.setAccessible(true);  
    forceStopPackage.invoke(am, yourpkgname); 
    

but for this method ,you need add a system sharedUserId android:sharedUserId="android.uid.system"

and a permission: android.permission.FORCE_STOP_PACKAGES

Upvotes: 0

Related Questions