← Back to Tutorials Chapter 9

Advanced Concepts

Notifications

// Create notification channel (Android 8+)
val channel = NotificationChannel(
    "general",
    "General Notifications",
    NotificationManager.IMPORTANCE_DEFAULT
).apply {
    description = "General app notifications"
    enableVibration(true)
}

val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)

// Build notification
val notification = NotificationCompat.Builder(this, "general")
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("New Message")
    .setContentText("You have a new message from Alice")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setAutoCancel(true)
    .addAction(R.drawable.ic_reply, "Reply", pendingIntent)
    .build()

// Show notification
notificationManager.notify(1001, notification)

Location Services

// Add dependency: implementation("com.google.android.gms:play-services-location:21.0.1")

val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

// Request permission first
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    fusedLocationClient.lastLocation.addOnSuccessListener { location ->
        if (location != null) {
            val lat = location.latitude
            val lng = location.longitude
            println("Location: $lat, $lng")
        }
    }
}

// Request location updates
val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10000)
    .setMinUpdateIntervalMillis(5000)
    .build()

fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())

Sending Email & SMS

// Send email via Intent
fun sendEmail(to: String, subject: String, body: String) {
    val intent = Intent(Intent.ACTION_SENDTO).apply {
        data = Uri.parse("mailto:")
        putExtra(Intent.EXTRA_EMAIL, arrayOf(to))
        putExtra(Intent.EXTRA_SUBJECT, subject)
        putExtra(Intent.EXTRA_TEXT, body)
    }
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    }
}

// Send SMS
fun sendSMS(phoneNumber: String, message: String) {
    val intent = Intent(Intent.ACTION_SENDTO).apply {
        data = Uri.parse("smsto:$phoneNumber")
        putExtra("sms_body", message)
    }
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    }
}

Dialogs

// AlertDialog
AlertDialog.Builder(this)
    .setTitle("Delete Item")
    .setMessage("Are you sure you want to delete this item?")
    .setIcon(R.drawable.ic_warning)
    .setPositiveButton("Delete") { _, _ -> deleteItem() }
    .setNegativeButton("Cancel", null)
    .show()

// BottomSheetDialog
BottomSheetDialog(this).apply {
    setContentView(R.layout.dialog_bottom_sheet)
    show()
}

// Custom Dialog Fragment
class CustomDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return AlertDialog.Builder(requireActivity())
            .setView(layoutInflater.inflate(R.layout.dialog_custom, null))
            .create()
    }
}

Firebase Integration

// build.gradle.kts
// implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
// implementation("com.google.firebase:firebase-analytics")
// implementation("com.google.firebase:firebase-auth")
// implementation("com.google.firebase:firebase-firestore")

// Firebase Authentication
fun signInWithEmail(email: String, password: String) {
    Firebase.auth.signInWithEmailAndPassword(email, password)
        .addOnSuccessListener { println("Signed in") }
        .addOnFailureListener { println("Error: ${it.message}") }
}

// Firestore CRUD
val db = Firebase.firestore
db.collection("users").document("alice")
    .set(hashMapOf("name" to "Alice", "age" to 30))
    .addOnSuccessListener { println("Document saved") }

db.collection("users").get()
    .addOnSuccessListener { result ->
        for (document in result) {
            println("${document.id} => ${document.data}")
        }
    }
Exercise: Create an app that shows a notification with a "View" action button that opens the app. Add location tracking that updates a TextView with the current coordinates every 30 seconds (handle permissions gracefully). Show a confirmation dialog before sending analytics data.