Read battery level

When I use the following battery reading code from Battery Level - Processing Forum, I get a compiler error: "The method registerReceiver(BroadcastReceiver, IntentFilter) is undefined for the type test. “test” is the name of the program. Is there a fix for this?

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

int BatteryLevel;

void setup()
{
	;
}

void draw()
{
	println(BatteryLevel);
}


private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context c, Intent i)
    {
        BatteryLevel = i.getIntExtra("level", 0);
    }
};

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    
    registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

I’m using Processing 3 and Android mode 4.1.1. I can not upgrade to Processing 4 because my app randomly crashes under Processing 4 if the window is resized. I tried upgrading the Android mode but after that, nothing compiled anymore and I had to restore my C: drive from a backup to get back a working SDK installation.

Hi @dtmr,

The method registerReceiver belongs to the context, so
getContext().registerReceiver(...

Cheers
— mnse

Thanks, that worked.