Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when invoking registerBroadcast

I have written a service that should be informed of changes in connectivity. I have written a BroadcastReceiver for that:

public class ConnectivityBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // ...
    }
}

and I've already added it to my AndroidManifest.xml:

<application> <!-- ... -->
    <receiver android:name="com.mycompany.mobile.android.services.impl.ConnectivityBroadcastReceiver"
              android:label="NetworkConnection">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>
</application>

But when I try to register my receiver like that:

class MyService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.registerReceiver(new ConnectivityBroadcastReceiver(this), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        return START_STICKY;
    }
}

I get a NPE:

java.lang.NullPointerException
    at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:308)
    at com.mycompany.mobile.android.services.impl.MyService.onStartCommand(...)

which occurs in the line where i call registerReceiver. Neither the ConnectivityBroadcastReceiver nor the IntentFilter can be null, or am I wrong? Did I miss to implement a method? Is the invocation in onStarCommand illegal?

like image 768
wonderb0lt Avatar asked Sep 10 '25 15:09

wonderb0lt


1 Answers

You probably resolved your problem a long time ago, but the solution may be useful for google wanderers.

I had the same NPE inside of an IntentService. I tried to register the receiver in the constructor of this service. It started working when I moved the registering to onHandleIntent().

Also I didn't need a receiver which would outlive my app, so I just created and registered it outside AndroidManifest.

It looks like this:

private final BroadcastReceiver connectivityReceiver = new BroadcastReceiver(){

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

        //do your thing

    }

};

public MyService() {
    super("MyService");

}

@Override
protected void onHandleIntent(Intent intent) {

    registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    //do your thing

}
like image 145
Michał Klimczak Avatar answered Sep 13 '25 06:09

Michał Klimczak