Created
February 23, 2022 19:15
-
-
Save alexstyl/aae318b781f94649ef20e400f2bf9b94 to your computer and use it in GitHub Desktop.
Factory functions for common Intents in Android such as starting a call or sending an e-mail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Intent | |
import android.net.Uri | |
import android.provider.CalendarContract | |
import android.provider.Settings | |
import java.util.Calendar | |
fun sendTextMessage(phoneNumber: String): Intent { | |
return Intent( | |
Intent.ACTION_SENDTO, | |
smrUri(phoneNumber) | |
) | |
} | |
fun sendTextMessage(recipients: List<String>): Intent { | |
return Intent( | |
Intent.ACTION_SENDTO, | |
smrUri(recipients.joinToString(",")) | |
) | |
} | |
private fun smrUri(phoneNumber: String) = | |
Uri.parse("sms:" + Uri.encode(phoneNumber)) | |
fun callNumber(phoneNumber: String): Intent { | |
return Intent( | |
Intent.ACTION_CALL, | |
phoneUri(phoneNumber) | |
) | |
} | |
fun dialNumber(phoneNumber: String): Intent { | |
return Intent( | |
Intent.ACTION_DIAL, | |
phoneUri(phoneNumber) | |
) | |
} | |
fun phoneUri(phoneNumber: String): Uri { | |
return Uri.fromParts("tel", phoneNumber, null) | |
} | |
fun openCalendar(onDate: Calendar): Intent { | |
return Intent( | |
Intent.ACTION_VIEW, | |
CalendarContract.CONTENT_URI.buildUpon() | |
.appendPath("time") | |
.appendEncodedPath(onDate.timeInMillis.toString()) | |
.build() | |
) | |
} | |
fun openBrowser(uri: Uri): Intent { | |
return Intent(Intent.ACTION_VIEW).apply { | |
data = uri | |
} | |
} | |
fun mailTo(toAddress: String): Intent { | |
return Intent(Intent.ACTION_SENDTO, mailUri(toAddress)) | |
} | |
fun mailTo(recipients: List<String>): Intent { | |
return Intent( | |
Intent.ACTION_SENDTO, | |
mailUri(recipients.joinToString(",")) | |
) | |
} | |
fun mailUri(mailAddress: String): Uri { | |
return Uri.fromParts("mailto", mailAddress, null) | |
} | |
fun shareText(text: String): Intent { | |
val intent = Intent(Intent.ACTION_SEND).apply { | |
type = "text/plain" | |
putExtra(Intent.EXTRA_TEXT, text) | |
} | |
return Intent.createChooser(intent, text) | |
} | |
fun openAppSystemSettings(packageName: String): Intent { | |
return Intent( | |
Settings.ACTION_APPLICATION_DETAILS_SETTINGS, | |
Uri.parse("package:${packageName}") | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment