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