How to open Gmail Compose when a button is clicked in Android App?

后端 未结 11 1000
别跟我提以往
别跟我提以往 2020-12-01 06:25

I am trying to open up Gmail Compose screen when a button is clicked in my Android App. Do I need some API key for this from Google? or what do I need to do in my button onC

11条回答
  •  执笔经年
    2020-12-01 07:18

    This code will directly start the gmail application to send an email.

    I found out using this post that the important part here is to find the "packageName" and the "activityInfo.name"

    I wanted to only use gmail without a chooser. Note that the package name is hard coded so if Gmail changes its packagename it won't work any more.

    The key to this was the setComponent where the first param is the package name and the second param is the activityInfo name.

    But like i said use with caution, I repeat myself; if the user doesn't have the gmail app installed or gmail changes its package name or Activty name to send an email this (hard)code will break. Thy have been warned ;)

    Here is my code

    Intent myIntent = new Intent(Intent.ACTION_SEND);
    
    PackageManager pm = getPackageManager();
    Intent tempIntent = new Intent(Intent.ACTION_SEND);
    tempIntent.setType("*/*");
    List resInfo = pm.queryIntentActivities(tempIntent, 0);
    for (int i = 0; i < resInfo.size(); i++) {
        ResolveInfo ri = resInfo.get(i);
        if (ri.activityInfo.packageName.contains("android.gm")) {
            myIntent.setComponent(new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name));
            myIntent.setAction(Intent.ACTION_SEND);
            myIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"exampleto@gmail.com"});
            myIntent.setType("message/rfc822");
            myIntent.putExtra(Intent.EXTRA_TEXT, "extra text");
            myIntent.putExtra(Intent.EXTRA_SUBJECT, "Extra subject");
            myIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("uri://your/uri/string");
        }
    }
    startActivity(myIntent);
    

提交回复
热议问题