Opening email client via Intent (but not to send a message)

后端 未结 4 2097
挽巷
挽巷 2020-12-15 04:52

Is there a way to programically open email client, without a need to forcing message send? I just want the app to let user open his email client for email checking purposes

4条回答
  •  轮回少年
    2020-12-15 05:21

    In Kotlin, but this version creates a chooser for user to pick which email app to use. You basically do what Oved does in his answer, except create an actual chooser using LabeledIntent.

    fun emailAppIntent(): Intent? {
        val emailIntent = Intent(Intent.ACTION_VIEW, Uri.parse("mailto:"))
        val packageManager = appLaunchContext.packageManager
    
        val activitiesHandlingEmails = packageManager.queryIntentActivities(emailIntent, 0)
        if (activitiesHandlingEmails.isNotEmpty()) {
            // use the first email package to create the chooserIntent
            val firstEmailPackageName = activitiesHandlingEmails.first().activityInfo.packageName
            val firstEmailInboxIntent = packageManager.getLaunchIntentForPackage(firstEmailPackageName)
            val emailAppChooserIntent = Intent.createChooser(firstEmailInboxIntent, "")
    
            // created UI for other email packages and add them to the chooser
            val emailInboxIntents = mutableListOf()
            for (i in 1 until activitiesHandlingEmails.size) {
                val activityHandlingEmail = activitiesHandlingEmails[i]
                val packageName = activityHandlingEmail.activityInfo.packageName
                val intent = packageManager.getLaunchIntentForPackage(packageName)
                emailInboxIntents.add(
                    LabeledIntent(
                        intent,
                        packageName,
                        activityHandlingEmail.loadLabel(packageManager),
                        activityHandlingEmail.icon
                    )
                )
            }
            val extraEmailInboxIntents = emailInboxIntents.toTypedArray()
            return emailAppChooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraEmailInboxIntents)
        } else {
            return null
        }
    }
    

    .. then later call it with

    val emailChooserIntent = emailAppIntent()
    
    if (emailChooserIntent != null) {
        startActivity(emailAppIntent())
    }
    

    or handle null however you want.

提交回复
热议问题