检查是否有2个实例在运行

时间:2012-07-14 11:11:53

标签: android

如果用户尝试再次输入,我正在尝试检查我的应用是否已在运行。 如果一个应用程序启动另一个应用程序,用户使用移动设备进入第二个应用程序,则可能是2个实例。

启动原始版本的启动器应用程序看起来像这样:

  Intent i = new Intent(Intent.ACTION_MAIN);
  PackageManager manager = getPackageManager();

  i = manager.getLaunchIntentForPackage("com.test.vayo");
  i.addCategory(Intent.CATEGORY_LAUNCHER);
   startActivity(i);

在我的原始代码中,我试图检查是否有2个实例,但总是在此代码上实现

    if (processName == null) {
        return false;
    }
    ActivityManager manager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
    for (RunningAppProcessInfo process : processes) {
        if (processName.equals(process.processName)) {

           return true;
        }
    }
    return false;

proccessName取自此代码,pid来自android.os.Process.myPid():

private String getAppName(int pID)

{

String processName = "";
ActivityManager am = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);

List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = context.getPackageManager();
while(i.hasNext()) 
{
      ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
      try 
      { 
          if(info.pid == pID)
          {
              CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
              //Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +"  Label: "+c.toString());
              //processName = c.toString();
              processName = info.processName;
          }
      }
      catch(Exception e) 
      {
            //Log.d("Process", "Error>> :"+ e.toString());
      }
 }
   return processName;
 }

希望你能说出我为什么在我的第一段代码中始终如一的错误。 非常感谢!!

0 个答案:

没有答案