先决条件:
Android API 28 或更高版本
网络连接权限
步骤:
1. 创建 NotificationReceiver 类:
java
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 获取流量使用情况
long usedBytes = intent.getLongExtra(NetworkStatsManager.EXTRA_NETWORK_INFO, 0L);
// 创建通知
Notification notification = createNotification(context, usedBytes);
// 显示通知
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
}
}
2. 在清单文件中注册广播接收器:
xml
android:name=".NotificationReceiver"
android:enabled="true"
android:exported="false">




3. 在代码中注册广播接收器:
java
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(notificationReceiver, intentFilter);
4. 创建 Notification:
java
private Notification createNotification(Context context, long usedBytes) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
// 设置通知标题和内容
builder.setContentTitle("流量使用情况");
builder.setContentText("已使用 " + humanReadableByteCount(usedBytes));
// 设置通知图标
builder.setSmallIcon(R.drawable.ic_data_usage);
// 设置通知优先级
builder.setPriority(NotificationCompat.PRIORITY_LOW);
// 返回通知
return builder.build();
}
5. 实用函数:
java
// 将字节数转换成可读格式
public static String humanReadableByteCount(long bytes) {
if (bytes < 1024) {
return bytes + " B";
} else if (bytes < 1048576) {
return bytes / 1024 + " KB";
} else if (bytes < 1073741824) {
return bytes / 1048576 + " MB";
} else {
return bytes / 1073741824 + " GB";
}
}
注意:
CHANNEL_ID 是要创建通知频道的 ID。
建议使用 NotificationManagerCompat 代替 NotificationManager,以支持旧版本 Android 设备。
点赞 (1883) 收藏 (1883)

大王卡超过四十g后是怎么收费的

抖音免流量在哪里显示

电视使用手机热点可以投屏么

流量限速了买流量包还是提速包

美团流量卡如何开启