如何获取用户当前打开的应用程序?

时间:2013-01-08 06:21:10

标签: android broadcastreceiver launcher

我正在寻找一个解决方案,我想让用户在他的设备上打开或安装应用程序。我必须从我的BroadcastReceiver类中获取用户打开的应用程序。我已经实现了我的代码如下:

public class AppReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {

    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.v(" App Name : ", c.toString());


      }catch(Exception e) {
      }
    }


}

我还在清单文件中添加了关于此接收器的信息:

  <receiver android:name="AppReciever">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.PACKAGE_ADDED"></action>
            <action android:name="android.intent.action.PACKAGE_CHANGED"></action>
            <action android:name="android.intent.action.PACKAGE_INSTALL"></action>
            <action android:name="android.intent.action.PACKAGE_REPLACED"></action>
            <action android:name="android.intent.action.PACKAGE_RESTARTED"></action>
  <data android:scheme="package" />

  </intent-filter>
    </receiver>

从上面的代码中,当我打开已经存在(安装)在设备上的新应用程序时,AppReciver没有执行以获取应用程序名称在Log.v.It仅适用于在设备上运行的其他应用程序。

请任何机构帮我从BroadcastReceiver获取当前打开的应用程序

1 个答案:

答案 0 :(得分:2)

添加到您的服务registerReceiver()。不要忘记取消注册接收者;

    AppReceiver appReceiver = new AppReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.setPriority(900);
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL); //@deprecated This constant has never been used.
    intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
    registerReceiver(appReceiver, intentFilter);

取消注册:unregisterReceiver(appReceiver);