我正在寻找一种解决方案,我想让用户在他的设备上打开或安装应用程序。我必须从我的 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) {
}
}
}
我还在 list 文件中添加了有关此接收器的信息:
<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 获取当前打开的应用程序
最佳答案
为您添加服务 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);
关于android - 如何获取用户当前打开的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14209306/