从Android中的广播接收器查找正在运行的活动

时间:2012-07-17 19:47:03

标签: android

我想从我的广播接收器中找到当前正在运行的其他活动。这是我在活动中使用的代码,用于查找其他正在运行的活动但是当我尝试在我的广播接收器中使用此代码时,我会在以下行中出现错误:

ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);

显示eclipse中的错误ACTIVITY_SERVICE无法解析为变量

 PackageManager pm = this.getPackageManager();

这显示了eclipse中的错误方法getPackageManager()未定义类型ScreenReceiver(我的广播接收器)

以下是完整代码:

public void getRunning(){
        ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while(i.hasNext()) {
          ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
          try {
            CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
            Log.w("LABEL", c.toString());
            runningApplications.add(c.toString());
          }catch(Exception e) {
            //Name Not Found Exception
          }
        }

    }

2 个答案:

答案 0 :(得分:4)

由于BroadcastReceiver不会从Context中下降,因此您无法使用 this ,就像在Activity中一样。您应该使用传递给onReceive()方法的Context实例。

public void getRunning(Context context){
        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 {
            CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
            Log.w("LABEL", c.toString());
            runningApplications.add(c.toString());
          }catch(Exception e) {
            //Name Not Found Exception
          }
        }

    }

答案 1 :(得分:1)

尝试:

public class ScreenReceiver  extends BroadcastReceiver {
private Context ctext;
    @Override
    public void onReceive(Context context, Intent intent) {
      ctext=context;
         //OR you can also pass context as param to  getRunning()
      //your code here....
    }
public void getRunning(){
        ActivityManager am = (ActivityManager)ctext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = ctext.getPackageManager();
        while(i.hasNext()) {
          ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
          try {
            CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
            Log.w("LABEL", c.toString());
            runningApplications.add(c.toString());
          }catch(Exception e) {
            //Name Not Found Exception
          }
        }

    }

}