Search code examples
javaandroidandroid-intentandroid-activitybroadcastreceiver

Broadcast Receiver - MainActivity is not an enclosing class


I know this was asked numerous times, but I couldn't find the right answer for me. I'm only in my third semester of my bachelor degree, so not that much knowledge yet.

Currently having my first Android course after I finished my beginner Java course (emphasis on beginner).

Due to Corona there is next to no Tutor support and the script is lacking decent explanations.

Im struggling with implementing my first Broadcast receiver. It's supposed to make a toast when a power cord is plugged in.

I tried a dynamic receiver so I registered the Receiver in my MainActivity as follows:

import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;


public class MainActivity extends AppCompatActivity {
[...]
private PowerConnectedReceiver mPowerConnectedReceiver;

    public void onResume() {

        super.onResume();

        IntentFilter powerFilter = new IntentFilter(Intent.ACTION_POWER_CONNECTED );

        mPowerConnectedReceiver = new PowerConnectedReceiver();

        getApplicationContext().registerReceiver(mPowerConnectedReceiver , powerFilter);

    }

    @Override

    protected void onPause() {

        getApplicationContext().unregisterReceiver(mPowerConnectedReceiver);

        super.onPause();

    }

With the Broadcast Receiver looking as follows and this is where the error pops up. It says for the Context of the Toast that MainActivity is not an enclosed class.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_LONG;

public class PowerConnectedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(MainActivity.this, "POWER CONNECTED received", LENGTH_LONG ).show();
    }
}

This is the way of implementing that is taught in the script.

As I mentioned I am fairly new to programming and this might be something totally obvious, but I'm not seeing it.

The only thing I tried was changing it to MainAcivity.class, but that did nothing. Thanks for support.


Solution

  • Your code is correct, but in the toast message you have to use context of the receiver i.e the first parameter of the onReceive method.

    Update your toast message from:

    Toast.makeText(MainActivity.this, "POWER CONNECTED received", LENGTH_LONG ).show();
    

    to

    Toast.makeText(context, "POWER CONNECTED received", LENGTH_LONG ).show();