// Khởi tạo Intent và điều hướng sang Product Activity
Intent i = new Intent(“.ProductActivity”);
// Hoặc khởi tạo Intent từ class
Intent I = new Intent(getContext(), ProductActivity.class)
startActivity(i);
External: Gọi Activity của hệ thống
// Gọi ứng dụng phone để quay số
Intent phoneIntent = new Intent(Intent.ACTION_DIAL);
phoneIntent.setData(Uri.parse(“tel:”+”+84 97 595 1910”));
if(phoneIntent.resolveActivity(getPackageManager()) != null){
startActivity(phoneIntent);
}
// Gọi ứng dụng Google Maps thông qua package name
Uri intentUri = Uri.parse("geo:43.095, -77.5736?Z=20");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, intentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
Implicit Intent vs Explicit Intent
Explicit Intent: chính là các internal intent, chỉ sử dụng trong nội bộ ứng dụng
Implicit Intent: chính là external intent, sử dụng để thực hiện các action bên ngoài, như gửi email, thực hiện phone call…
Các activities có thể bị giả mạo intent >> Các ứng dụng độc hại khởi chạy 1 activity ở ứng dụng khác bởi việc giả mạo intent.
Mặc định explicit intent filter sẽ thiết lập thuộc tính android:exported là true >> Có nghĩa là bất kỳ app nào có thể gọi activity này nếu biết được đầy đủ tên của Activity đó (ex: com.ourcompany.catalog.NewsActivity)
Nếu ứng dụng chỉ cần các internal intent hoặc có Activity xử lý các dữ liệu nhạy cảm (sensitive information) thì phải đảm bảo intent filter của activity đó có thuộc tính android:exported là false
3. Các loại Common Intent
4. Truyền dữ liệu giữa các Acitivty thông qua Intent Extras
Trước khi khởi chạy activity có thể truyền thêm dữ liệu cho activity thông qua phương thức putExtra()
// Gửi thêm dữ liệu trước khi chạy activity
Intent i = new Intent(“.CatalogDetailActivity”);
i.putExtra(“price”, selectedPrice);
startActivity(i)
// Lấy thông tin về giá của sản phẩm khi CatalogDetailActivity được khởi chạy
Intent i = getIntent();
String productPrice = i.getExtras().getString(“price”);
5. Intent Flags
// Code xử lý khi nhấn button Return to Main từ các activity detail ở các level sau Intent i = new Intent(“.Main”);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
FLAG_ACTIVITY_CLEAR_TOP: cờ này thực hiện theo cơ chế: nếu Main activity đang được chạy thì thay vì khởi tạo 1 instance mới, tất cả các activities ở stack trên Main activity sẽ bị đóng hết >> Quay trực tiếp về Main activity