Search code examples
javaandroidandroid-intentandroid-activityandroid-broadcast

how can method "getSystemService" be used directly in BroadcastReceiver?


I got this problem: getSystemService defines in Context class, so I assume it is called when context.getSystemService. I can't understand the following code where getSystemService is called directly in BroadcastReceiver. I run the code and no error show!

Codes:

 public class MainActivity extends Activity {
    ……
 class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
  public void onReceive(Context context, Intent intent) {
    ConnectivityManager connectionManager = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isAvailable()) 
    {
    Toast.makeText(context, "network is available",
    Toast.LENGTH_SHORT).show();
    } else {
    Toast.makeText(context, "network is unavailable",
    Toast.LENGTH_SHORT).show();
    }
   }
 }
}

Solution

  • Because your NetworkChangeReceiver is an inner class of MainActivity.
    You are using the Activity context.
    Try using NetworkChangeReceiver in a new file(not sub class), you will see what happens.

    MainActivity.this though its referring to your own class which extends Activity class but the base class (Activity) also extends Context class, so it can be used to offer activity context.