Giới thiệu
Hướng dẫn này trình bày cách khởi động lại (restart) một Activity hiện tại trên Android sử dụng Kotlin. Kỹ thuật này hữu ích khi cần reset trạng thái UI, thay đổi ngôn ngữ, theme, hoặc áp dụng cấu hình mới.
Các bước thực hiện
Bước 1: Tạo dự án mới
Tạo project: File → New Project.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_centerInParent="true"
android:layout_marginTop="16sp"
android:text="Restart Activity"
android:textColor="@android:color/background_dark" />
</RelativeLayout>
Bước 3: Xử lý logic (src/MainActivity.kt)
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.Random
class MainActivity : AppCompatActivity() {
private lateinit var textView: TextView
private lateinit var button: Button
private val random = Random()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
button = findViewById(R.id.button)
// Hiển thị số ngẫu nhiên mỗi lần tạo
textView.text = "Random Number: ${random.nextInt(100)}"
button.setOnClickListener {
restartActivity()
}
}
private fun restartActivity() {
val intent = intent
finish()
startActivity(intent)
// Tùy chọn: thêm animation
// overridePendingTransition(0, 0)
}
}
Bước 4: Cấu hình Manifest (androidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Mỗi lần nhấn "Restart Activity", số ngẫu nhiên sẽ thay đổi, chứng minh Activity đã được tạo lại (onCreate gọi lại).
Các cách restart Activity
1. Cách cơ bản (trên) - Giữ nguyên Intent
val intent = intent finish() startActivity(intent)
2. Restart với Intent mới (clear top)
val intent = Intent(this, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
startActivity(intent)
finish()
3. Recreate() (API 11+) - Đơn giản nhất
recreate()
Lưu ý: recreate() gọi onDestroy() → onCreate() nhưng không gọi onRestart(), onStart(), onResume() theo trình tự chuẩn. Có thể gây vấn đề với một số thư viện.
4. Restart cả ứng dụng (Process death)
fun restartApp(context: Context) {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
intent?.let { context.startActivity(it) }
android.os.Process.killProcess(android.os.Process.myPid())
System.exit(0)
}
Khi nào nên restart Activity?
- Thay đổi ngôn ngữ (Locale) tại runtime
- Thay đổi Theme (Day/Night mode)
- Cập nhật cấu hình cần apply ngay
- Reset state phức tạp
Lưu ý
- Restart Activity tốn tài nguyên, gây chập chờn UI. Nên ưu tiên cập nhật UI trực tiếp nếu có thể.
- Dữ liệu trong ViewModel sẽ được giữ lại (vì ViewModel scoped to Activity lifecycle, survive recreation).
- Dữ liệu trong onSaveInstanceState sẽ được restore.