Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
   }
 }
}
like image 398
PodBlood Avatar asked Oct 23 '25 09:10

PodBlood


1 Answers

getSystemService() is part of the Context. You need to use the Context you receive in your onReceive() method:

@Override
public void onReceive(Context context, Intent i) {
    UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
}
like image 121
Jaydev Avatar answered Oct 24 '25 23:10

Jaydev