how to get running application/package name using broadcast receiver

十年热恋 提交于 2019-12-24 13:00:26

问题


in my application i want to write code of receiving broadcast for which application is running.like when we run/open any application my broadcast receiver should receive it. how can i get the app name/ package name???

 public class Receiver extends BroadcastReceiver {

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

    if("android.intent.action.PACKAGE_FIRST_LAUNCH".equals(intent.getAction()))
     System.out.println("context..."+context.getPackageName());


}
 }

androidmanifest file-

  <receiver
        android:name="com.veg.app.Receiver"
        android:enabled="true"

        android:label="StartReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_FIRST_LAUNCH" />      
            <category android:name="android.intent.category.DEFAULT"/> 
        </intent-filter>
    </receiver>

回答1:


Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
 // get the info from the currently running task
     List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); 

     Log.d("topActivity", "CURRENT Activity ::"
             + taskInfo.get(0).topActivity.getClassName());

     ComponentName componentInfo = taskInfo.get(0).topActivity;
   componentInfo.getPackageName();

You will need the following permission on your manifest:

uses-permission android:name="android.permission.GET_TASKS"

And there is no such event fired when any application is invoked. Any intent is not broadcasted on start of an application, so u might need a thread running parallely in background to monitor the top activity.




回答2:


you can use use ActivityManager.getRunningAppProcesses() to find the runnig application at current moment. It will return the ActivityManager.RunningAppProcessInfo of currently running application. Then you can get the name using PckageManager



来源:https://stackoverflow.com/questions/16098042/how-to-get-running-application-package-name-using-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!