Giới thiệu
Bài viết này minh họa cách khởi động lại (restart) Activity hiện tại bằng cách gọi finish() rồi startActivity(getIntent()). Kỹ thuật này hữu ích khi cần reset trạng thái UI, áp dụng thay đổi ngôn ngữ, theme, hoặc cấu hình mà không cần khởi động lại toàn bộ ứng dụng.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và tạo dự án.
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:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
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="16dp"
android:text="Khởi động lại Activity" />
</RelativeLayout>
Bước 3: Viết code logic (src/MainActivity.java)
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
Random random = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
// Hiển thị số ngẫu nhiên mỗi lần Activity tạo
textView.setText("Số ngẫu nhiên: " + random.nextInt(100));
button.setOnClickListener(v -> {
Intent intent = getIntent();
finish(); // Kết thúc Activity hiện tại
startActivity(intent); // Khởi động lại với cùng Intent
// overridePendingTransition(0, 0); // Tùy chọn: tắt animation
});
}
}
Bước 4: Cấu hình AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<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. TextView hiển thị số ngẫu nhiên (ví dụ: 42). Nhấn "Khởi động lại Activity" -> Activity reload, số ngẫu nhiên mới hiển thị (ví dụ: 87).
Các cách restart Activity khác
1. Dùng recreate() (API 11+) – Cách đơn giản nhất
button.setOnClickListener(v -> recreate());
recreate() tự động gọi finish() và startActivity(getIntent()) với animation mặc định. Khuyên dùng cho đa số trường hợp.
2. Restart với Intent mới (clear top, new task)
Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent);
3. Restart toàn bộ Application (kill process)
// Chỉ dùng khi thực sự cần thiết Process.killProcess(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) không dùng AppCompatDelegate
- Reset trạng thái phức tạp về trạng thái ban đầu
- Sau khi cập nhật cấu hình từ server
Lưu ý & Cảnh báo
- Mất trạng thái: onCreate() chạy lại, mọi biến thành viên reset. Dùng
onSaveInstanceState()/ViewModelđể giữ dữ liệu quan trọng - Animation: Mặc định có animation chuyển cảnh. Dùng
overridePendingTransition(0, 0)sau startActivity() để tắt - Back stack: Cách finish()+startActivity() giữ nguyên back stack. Dùng FLAG_ACTIVITY_CLEAR_TOP để xóa
- Không lạm dụng: Restart tốn tài nguyên, gây giật lag. Ưu tiên cập nhật UI trực tiếp (setText, notifyDataSetChanged...)