Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect which app is opened on android

I am developing an android custom keyboard and i want to send stickies to my friends for example on hangouts from my keyboard. I added some png for this.

When I use the android's share api I have to select first an app to share with. Is it possible to detect the current opened application from my keyboard? For example if I am chatting with hangouts then I want to call the intent telling it to share with "com.something.hangouts"

If I am in FB messenger then telling it "com.something.facebook.messenger" etc...

I tried to get it like this:

fun getOpenedApplication() {
    var am = this.getSystemService(ACTIVITY_SERVICE) as ActivityManager;

    var l = am.getRecentTasks(1,
            ActivityManager.RECENT_WITH_EXCLUDED);
    var i = l.iterator();

    var pm = this.packageManager;

    while (i.hasNext()) {
        try {
            var intent = i.next().baseIntent;
            var list = pm.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);

            var c = pm.getApplicationLabel(pm.getApplicationInfo(
                    list[0].activityInfo.packageName,
                    PackageManager.GET_META_DATA));

            Toast.makeText(this, "Application name: " + c.toString(),
                    Toast.LENGTH_LONG).show();

        } catch (e: Exception) {
            Toast.makeText(this,
                    "Application name not found: " + e.toString(),
                    Toast.LENGTH_LONG).show();
        }
    }
}

But it is not working well... It gives back the launcher or the keyboard. (randomly)

I tried to get the first app from Recent Apps list but it wasn't working

like image 532
MegaX Avatar asked Mar 05 '16 07:03

MegaX


1 Answers

It's very easy task.

String packageName = getCurrentInputEditorInfo().packageName;

method of your InputMethodService class.

like image 165
Bharat Beladiya Avatar answered Oct 12 '22 18:10

Bharat Beladiya