2013年1月4日 星期五

task killer kill task


ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
 final PackageManager pm = getPackageManager();
 // get a list of installed apps.
 List<ApplicationInfo> packages = pm
   .getInstalledApplications(PackageManager.GET_META_DATA);
 for (ApplicationInfo packageInfo : packages) {
 if (pm.getLaunchIntentForPackage(packageInfo.packageName) != null) {
 am.killBackgroundProcesses(packageInfo.packageName.toString());
   }
 }
---------------------------------------------------------------------------------



Im trying to write a simple task killer. I know I shouldnt kill tasks in Android, but Im eager to try something like this. I have the following code:
List<RunningAppProcessInfo> procInfo = activityManager.getRunningAppProcesses();
for (int i = 0; i < procInfo.size(); i++) {
Log.v("proces " + i,procInfo.get(i).processName + " pid:" + procInfo.get(i).pid + " importance: " + procInfo.get(i).importance + " reason: " + procInfo.get(i).importanceReasonCode);
//First I display all processes into the log
}
for (int i = 0; i < procInfo.size(); i++) {
RunningAppProcessInfo process = procInfo.get(i);
int importance = process.importance;
int pid = process.pid;
String name = process.processName;
if (name.equals("manager.main")) {
//I dont want to kill this application
continue;
}
if (importance == RunningAppProcessInfo.IMPORTANCE_SERVICE) {
//From what I have read about importances at android developers, I asume that I can safely kill everithing except for services, am I right?
Log.v("manager","task " + name + " pid: " + pid + " has importance: " + importance + " WILL NOT KILL");
continue;
}
Log.v("manager","task " + name + " pid: " + pid + " has importance: " + importance + " WILL KILL");
android
.os.Process.killProcess(procInfo.get(i).pid);
}
procInfo
= activityManager.getRunningAppProcesses();
//I get a new list with running tasks
for (int i = 0; i < procInfo.size(); i++) {
Log.v("proces after killings" + i,procInfo.get(i).processName + " pid:" + procInfo.get(i).pid + " importance: " + procInfo.get(i).importance + " reason: " + procInfo.get(i).importanceReasonCode);
}
My problem here is that when I perform this code, I first get the list of all tasks, thats ok. Than I see in the log several lines of:
Sending signal. pid: (processId) SIG: 9
I asume thats a signal to die. But at the end of my code, when I display all running processes, the list is the same as before, no task has been killed. Any ide why? Thank you!
share|improve this question

feedback


You can't kill other tasks that way because the Kernel will enforce permissions. Try this instead:
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
activityManager
.restartPackage(packageName);
you will need the following permissions in the manifest:
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
EDIT:
Actually restartPackage is deprecated. use killBackgroundProcesses() instead!
share|improve this answer
feedback

To achieve best result form killProcess , try calling killProcess many times.as
for (int i = 0; i < 10; i++)
{
android
.os.Process.killProcess(procInfo.get(i).pid);
}
NOTE:
version 2.2 - killBackgroundProcesses : " This is the same as the kernel killing those processes to reclaim memory; the system will take care of restarting these processes in the future as needed."
ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
am
.killBackgroundProcesses("com.est.testetst");
Required Permissions:
android.Manifest.permission.KILL_BACKGROUND_PROCESSES
version 2.1 - restartPackage -" This method is deprecated. (works for version less than 2.2. This is now just a wrapper for killBackgroundProcesses(String); the previous behavior here is no longer available to applications because it allows them to break other applications by removing their alarms, stopping their services, etc."
 ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am
.restartPackage(getPackageName());
Required Permissions:
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
share|improve this answer
Thanks, I went with the killBackgroundProcesses and it seems to be working fine – Tomáš 'Guns Blazing' Frček May 6 '12 at 15:07
feedback

Fortunately, killProcess() will only work for you to kill your own processes. You can tell this byreading the documentation.
share|improve this answer
Was this post useful to you?     

2013年1月2日 星期三

final app list


package com.example.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.Menu;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  String outt = "";

  final PackageManager pm = getPackageManager();
  // get a list of installed apps.
  List<ApplicationInfo> packages = pm
    .getInstalledApplications(PackageManager.GET_META_DATA);

  /*
   * for (ApplicationInfo packageInfo : packages) {
   *
   * outt=
   * outt+packageInfo.loadLabel(getPackageManager()).toString()+"\n"; outt
   * = outt + packageInfo.packageName + "\n"; outt = outt +
   * pm.getLaunchIntentForPackage(packageInfo.packageName) +
   * "\n--------------\n";
   *
   * }// the getLaunchIntentForPackage returns an intent that you can use
   * // with startActivity()
   */

  // ListView "ListView1"
  ListView list = (ListView) findViewById(R.id.ListView1);// 綁定Layout裡面的ListView
  final List clickintent = new ArrayList();
  final List pkn = new ArrayList();

  // 生成動態數組,加入數據
  ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
  for (ApplicationInfo packageInfo : packages) {
   if (pm.getLaunchIntentForPackage(packageInfo.packageName) != null) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("ItemImage", packageInfo.loadIcon(getPackageManager()));// Photo
    // ID
    map.put("ItemTitle", packageInfo.loadLabel(getPackageManager())
      .toString()); // Title
    map.put("ItemText",
      pm.getLaunchIntentForPackage(packageInfo.packageName)); // Content
    map.put("ItemText",
      pm.getLaunchIntentForPackage(packageInfo.packageName)); // Content
    listItem.add(map);
    clickintent.add(pm.getLaunchIntentForPackage(
      packageInfo.packageName).toString());
    pkn.add(packageInfo.packageName.toString());

   }
  }
  // 生成適配器的Item和動態數組對應的元素
  SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 數據源
    R.layout.list_item,// ListItem的XML實現
    // 動態數組與ImageItem對應的子項
    new String[] { "ItemImage", "ItemTitle", "ItemText" },
    // ImageItem的XML文件裡面的一個ImageView,兩個TextView ID
    new int[] { R.id.ItemImage, R.id.ItemTitle, R.id.ItemText });

  // Add and Show
  list.setAdapter(listItemAdapter);

  // One Click
  list.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
     long arg3) {
    // One Click To-Do
    // Write File"clciked" to Internal Storage
    String fileName = "clicked";
    String content = (String) clickintent.get(arg2);
    FileOutputStream writer = null;
    try {
     writer = openFileOutput(fileName, Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    try {
     writer.write(content.getBytes());
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    try {
     writer.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    // End of Write File"clciked" to Internal Storage
    // Write File"pkn" to Internal Storage
    String fileName2 = "pkn";
    String content2 = (String) pkn.get(arg2);
    FileOutputStream writer2 = null;
    try {
     writer2 = openFileOutput(fileName2, Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    try {
     writer2.write(content2.getBytes());
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    try {
     writer2.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    // End of Write File"pkn" to Internal Storage
   }
  });

  // 添加長按點擊
  list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

   public void onCreateContextMenu(ContextMenu menu, View v,
     ContextMenuInfo menuInfo) {
    // Long Press To-Do
    // Read in. st. from File"pkn"
    String fileName = "pkn";
    int readed;
    String content = "";
    byte[] buff = new byte[256]; // input stream buffer
    // Input stream
    try {
     FileInputStream reader = openFileInput(fileName);
     // FileInputStream reader =
     // context.getApplicationContext().openFileInput(fileName);
     while ((readed = reader.read(buff)) != -1) {
      content += new String(buff).trim();
     }
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
    // End of Read in. st. from File"pkn"
    // Read in. st. from File"clicked"
    String fileName2 = "clicked";
    int readed2;
    String content2 = "";
    byte[] buff2 = new byte[256]; // input stream buffer
    // Input stream
    try {
     FileInputStream reader2 = openFileInput(fileName2);
     // FileInputStream reader =
     // context.getApplicationContext().openFileInput(fileName);
     while ((readed2 = reader2.read(buff2)) != -1) {
      content2 += new String(buff2).trim();
     }
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
    // End of Read in. st. from File"clicked"
    Toast.makeText(getApplicationContext(), content,
      Toast.LENGTH_SHORT).show();
    Toast.makeText(getApplicationContext(), content2,
      Toast.LENGTH_SHORT).show();

    Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(content);
    startActivity( LaunchIntent );

   }
  });
  // End of ListView "ListView1"

  // Write File"test" to Internal Storage
  String fileName = "test";
  String content = outt;
  FileOutputStream writer = null;
  try {
   writer = openFileOutput(fileName, Context.MODE_PRIVATE);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   writer.write(content.getBytes());
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   writer.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // End of Write File"test" to Internal Storage
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

start application knowing package name


Can someone tell me how to start new application knowing only its package name? I do not have information about what activity is the main one.
share|improve this question

feedback
Try using PackageManager and getLaunchIntentForPackage()
share|improve this answer
Thanks, I missed this function while looking at PackageManager... – bart Aug 6 '10 at 10:33
feedback
Just use these following two lines,so you can launch any installed application whose package name is known:
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc");
startActivity
( LaunchIntent );
share|improve this answer
Related Posts Plugin for WordPress, Blogger...