Get battery level before broadcast receiver responds for Intent.ACTION_BATTERY_CHANGED

后端 未结 6 1780
囚心锁ツ
囚心锁ツ 2020-11-28 03:56

I have a broadcast receiver in my program to get react to the battery level like so:

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
           


        
6条回答
  •  感情败类
    2020-11-28 04:04

    Please be aware, that the intent you get from registerReceiver call

    Intent intent  = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    

    can be null. So please make a check before using the intent, e.g.

    if(intent != null){ 
    // do your stuff here... 
    }
    

    I just got a null pointer exception, causing the app to crash!

提交回复
热议问题