Giới thiệu
Hướng dẫn này minh họa cách tạo một thông báo Android có hành động (action) mà khi người dùng nhấn vào hành động đó, ứng dụng không bị mở ra. Thay vào đó, chúng ta sẽ sử dụng BroadcastReceiver để xử lý hành động trong nền.
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à điền đầy đủ thông tin cần thiết để tạo dự án mới.
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"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCreateNotification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="createNotification"
android:text="Tạo thông báo" />
</RelativeLayout>
Bước 3: Viết code MainActivity
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String DEFAULT_CHANNEL_ID = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createNotification(View view) {
int notificationId = (int) System.currentTimeMillis();
// PendingIntent rỗng cho contentIntent (không mở app khi nhấn vào body thông báo)
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(),
PendingIntent.FLAG_IMMUTABLE);
// Intent cho BroadcastReceiver xử lý hành động "Cancel"
Intent buttonIntent = new Intent(this, NotificationBroadcastReceiver.class);
buttonIntent.putExtra("notificationId", notificationId);
PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,
PendingIntent.FLAG_IMMUTABLE);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID);
builder.setContentTitle("Thông báo của tôi");
builder.setContentIntent(pendingIntent);
builder.addAction(R.drawable.ic_launcher_foreground, "Hủy", btPendingIntent);
builder.setContentText("Ví dụ Notification Listener Service");
builder.setSmallIcon(R.drawable.ic_launcher_foreground);
builder.setAutoCancel(true);
builder.setDeleteIntent(getDeleteIntent());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "TÊN_KÊNH_THÔNG_BÁO", importance);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(notificationId, builder.build());
}
}
protected PendingIntent getDeleteIntent() {
Intent intent = new Intent(this, NotificationBroadcastReceiver.class);
intent.setAction("notification_cancelled");
return PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
}
}
Bước 4: Tạo BroadcastReceiver (NotificationBroadcastReceiver.java)
package app.tutorialspoint.com.notifyme;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
// Hủy thông báo khi người dùng nhấn nút "Hủy"
NotificationManager manager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
Bước 5: 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.tutorialspoint.com.notifyme">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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">
<receiver
android:name=".NotificationBroadcastReceiver"
android:enabled="true"
android:exported="true">
</receiver>
<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ị Android thật với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn và quan sát màn hình thiết bị.
