如何检测在Android上打开了哪个应用 [英] How to detect which app is opened on android

查看:97
本文介绍了如何检测在Android上打开了哪个应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个android自定义键盘,我想向我的朋友发送即时贴,例如通过键盘在视频群聊上.我为此添加了一些png.

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.

当我使用android的share API时,我必须首先选择要共享的应用.是否可以通过键盘检测当前打开的应用程序?例如,如果我正在与视频群聊聊天,那么我想调用意图告诉它与"com.something.hangouts"共享

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"

如果我在FB Messenger中,则告诉它"com.something.facebook.messenger"等...

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

我试图这样获得它:

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

推荐答案

这是非常简单的任务.

String packageName = getCurrentInputEditorInfo().packageName;

InputMethodService类的方法.

method of your InputMethodService class.

这篇关于如何检测在Android上打开了哪个应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆