android-studio - 如何显示来自广播接收器类的通知?
问题描述
当设备电池电量低于 10% 并且拔下电源时,我需要显示通知。这种情况在广播接收器类中,那么,如何显示来自该类的通知?
广播接收器类中的代码:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int batteryLevel = intent.getIntExtra("level",0);
int chargingStatus = intent.getIntExtra("status",0);
if(batteryLevel <= 10 && (chargingStatus == DISCHARGING || chargingStatus == NOT_CHARGING))
{
Log.d("test", "Notification!!!");
}
}
MainActivity 中的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
notificationsSetup();
broadcastSetup();
gameView = findViewById(R.id.GameView);
}
private void broadcastSetup()
{
batteryReceiver = new BatteryReceiver();
filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
private void notificationsSetup()
{
// 1. Get reference Notification Manager system Service
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// 2. Create Notification-Channel. ONLY for Android 8.0 (OREO API level 26) and higher.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID, // Constant for Channel ID
CHANNEL_NAME, // Constant for Channel NAME
NotificationManager.IMPORTANCE_HIGH); // for popup use: IMPORTANCE_HIGH
notificationManager.createNotificationChannel(notificationChannel);
}
notificationID = 1;
}
public void notify(View view)
{
Intent intent = new Intent(this, MainActivity.class);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_battery_alert)
.setContentTitle("("+ notificationID +")")
.setContentText("LOW BATTERY, PLEASE CHARGE")
.build();
notificationManager.notify(notificationID, notification);
}
@Override
protected void onStart() {
super.onStart();
registerReceiver(batteryReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(batteryReceiver);
}
}
我应该在哪里使用 notify() 函数?这样对吗?谢谢
解决方案
推荐阅读
- c# - 在 switch 中设置的委托不能在 switch 之外使用
- java - 带有可选结尾逗号的正则表达式模式匹配
- mysql - 使用全文索引和其他带索引的列优化 mysql 查询
- sql - 如何在 SQL 中有效地对一组列进行转置和求和?
- c# - 如何从 OnTextChanged 事件中获取 GridViewEventArgs?
- google-maps - 在颤振中实现短信“分享我的当前位置”
- html - 当按钮悬停时,类的背景颜色被强制更改为不同的颜色
- reactjs - react-transition-group 和 react-abc (abcjs) Midi 不能同时工作(取决于父组件的 Key)?
- c++11 - 编译玩具程序时找不到-lHalide
- python - 在线性时间和常量内存中旋转数组(列表)