Search code examples
androidandroid-intentmms

Android custom keyboard for sending images


I am currently trying to implement a custom keyboard that sends an image (possibly via an intent?) to a certain application. More specifically, I am trying to I am trying to create a key on a custom keyboard that would send an image to the default messaging app so that it can be sent as an MMS.

I have modified the sample SoftKeyboard project in order to do this. Here is what I have so far:

private void handleCharacter(int primaryCode, int[] keyCodes) {
    if (isInputViewShown()) {
        if (mInputView.isShifted()) {
            primaryCode = Character.toUpperCase(primaryCode);
        }
    }
    if (isAlphabet(primaryCode) && mPredictionOn) {
        mComposing.append((char) primaryCode);

        // Send message here
        Intent pictureMessageIntent = new Intent(Intent.ACTION_SEND);
        pictureMessageIntent.setType("image/png");
        Uri uri = Uri.parse("android.resource://" + this.getPackageName() + "/drawable/icon_en_gb");
        pictureMessageIntent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(pictureMessageIntent);

        getCurrentInputConnection().setComposingText(mComposing, 1);
        updateShiftKeyState(getCurrentInputEditorInfo());
        updateCandidates();
    } else {
        getCurrentInputConnection().commitText(
                String.valueOf((char) primaryCode), 1);
    }
}

The problem is I am getting a runtime exception that says:

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I'm unfamiliar with Android custom keyboards, but I'm not sure if starting a new Activity is the best idea. Does anyone have any suggestions?


Solution

  • The problem is that Activities are typically meant to be started from other Activities. Android added this error to make sure that developers only change this flow willingly and consciously.

    Add the following line before sending the intent to fix the problem:

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);