0

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

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

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

 PackageManager pm = this.getPackageManager();

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

这是完整的代码:

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

    }
4

2 回答 2

4

由于 BroadcastReceiver 不会从 Context 下降,因此您不能像在 Activity 中那样使用this 。您应该使用传递给 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
          }
        }

    }
于 2012-07-17T19:56:53.907 回答
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
          }
        }

    }

}
于 2012-07-17T19:52:58.813 回答