I'm trying to implement a Keyboard app which should be capable of sending images to the current activity (Whatsapp, Messaging app, etc).
Is there a way to actually achieve this? Of course it would be limited to apps which accept images, but I wonder what's the best approach.
Tried using a StringBuilder with an ImageSpan but couldn't get it to work. I was wondering if there was a better way. Using Intents maybe?
Finally achieved this by sending Intents to the foreground app, but this has limitations: messaging apps usually require to select the conversation, which breaks the user flow and adds an unnecessary step (unless they expose a way to send the intent to a specific chat).
This can be achieved as follows:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setPackage(getCurrentAppPackage(context, editorInfo));
return sendIntent;
Where getCurrentAppPackage(...)
is a method that returns the foreground Activity given a Context
and an EditorInfo
, which you can get from your IME implementation when binded to an input field.
public String getCurrentAppPackage(Context context, EditorInfo info) {
if(info != null && info.packageName != null) {
return info.packageName;
}
final PackageManager pm = context.getPackageManager();
//Get the Activity Manager Object
ActivityManager aManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//Get the list of running Applications
List<ActivityManager.RunningAppProcessInfo> rapInfoList = aManager.getRunningAppProcesses();
//Iterate all running apps to get their details
for (ActivityManager.RunningAppProcessInfo rapInfo : rapInfoList) {
//error getting package name for this process so move on
if (rapInfo.pkgList.length == 0) {
Log.i("DISCARDED PACKAGE", rapInfo.processName);
continue;
}
try {
PackageInfo pkgInfo = pm.getPackageInfo(rapInfo.pkgList[0], PackageManager.GET_ACTIVITIES);
return pkgInfo.packageName;
} catch (PackageManager.NameNotFoundException e) {
// Keep iterating
}
}
return null;
}
Update: Commit Content API was added on API level 25 (and support library makes it work from API 13). More info here: https://developer.android.com/preview/image-keyboard.html Until apps start implementing it, the method above can be used as fallback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With