首页 > 解决方案 > 如何显示来自广播接收器类的通知?

问题描述

当设备电池​​电量低于 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() 函数?这样对吗?谢谢

标签: android-studioandroid-notifications

解决方案


推荐阅读