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

7

我正在寻找一种解决方案,希望能够获取用户在设备上打开或安装的应用程序。我需要从我的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。它仅适用于其他应用程序在设备上运行一次。

请有经验的人帮助我从BroadcastReceiver中获取当前打开的应用程序。


我只能获取应用程序名称新的package_added,但我需要获取package_restarted/package_install/package_replaced/package_restarted。 - prasad.gai
抱歉,我不明白你的问题,请重新用其他方式表达一下吧?你想获取所有已安装的应用程序吗? - Dheeraj Bhaskar
1个回答

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);

在优先级中使用Integer.MAX_VALUE会有什么危害吗? - gonzobrains
1
从IntentFilter类的文档中了解到SYSTEM_HIGH_PRIORITY值:应用程序不应使用此优先级或更高优先级的过滤器。 - resource8218

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接