Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách bật/tắt thông báo Android từ Broadcast Receiver

Giới thiệu

Hướng dẫn này minh họa cách bắt đầu và dừng một thông báo Android từ một BroadcastReceiver. Ví dụ này sử dụng sự kiện trạng thái USB để bật/tắt thông báo.

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 thông tin cần thiết.

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">
</RelativeLayout>

Bước 3: Viết code MainActivity

package app.tutorialspoint.com.notifyme;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Bước 4: Tạo USBStateReceiver

package app.tutorialspoint.com.notifyme;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
import android.util.Log;

public class USBStateReceiver extends BroadcastReceiver {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String DEFAULT_CHANNEL_ID = "default";
    private boolean connected = true;

    @SuppressLint("UnsafeProtectedBroadcastReceiver")
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, DEFAULT_CHANNEL_ID);
        builder.setContentTitle("USB - Thông báo");
        
        String action = intent.getAction();
        Log.e("USB", action);
        
        builder.setContentText("Đã kết nối");
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);

        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager) 
            context.getSystemService(Context.NOTIFICATION_SERVICE);

        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);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }

        if (notificationManager != null) {
            if (connected) {
                notificationManager.notify(1, notification);
                connected = false;
            } else {
                notificationManager.cancel(1);
                connected = true;
            }
        }
    }
}

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" />

    <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>

        <receiver android:name=".USBStateReceiver">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_STATE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị Android thật, chạy ứng dụng từ Android Studio. Cắm/rút cáp USB để kiểm tra thông báo bật/tắt.

Cách bật/tắt thông báo Android từ Broadcast Receiver