0

如果用户尝试再次输入它,我正在尝试检查我的应用程序是否已经在运行。如果一个应用程序启动另一个应用程序并且用户使用移动设备进入第二个应用程序,则可能是 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;
 }

希望你能告诉我为什么我的第一个代码块总是正确的。多谢!!

4

0 回答 0