简体   繁体   中英

How to save value from Broadcast receiver and return it?

I try to save and return the value i've got from the broadcast receiver method i wrote, but it wont work. Peculiarly using Log inside the receiver to print the value works fine, but i cant save the value. Hope someone got a simple solution for me.

//Gives current battery temperature in celsius
public String  getBatteryTemperature()
{
    final int[] batTemp = new int[1];
    BroadcastReceiver batteryTemperatureReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            batTemp[0] = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0)/10;
            //optional Log output for debug (works)
            Log.i("Log battery temperature", String.valueOf(batTemp[0]) + "°C");
        }
    };
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    this.getContext().registerReceiver(batteryTemperatureReceiver, intentFilter);
//only returns 0 
    return String.valueOf(batTemp[0]);
}

This is because your method returns before you receive a notification. In this case, your receiver class has just a local scope but includes a reference to the enclosing class (which I assume an Activity) and it's doesn't get destroyed when you're out of the method.

So you can make it a member variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM