如何在BroadcastReceiver中直接使用方法"getSystemService"?

Sam*_*han 2 java android android-intent android-activity android-broadcast

我遇到了这个问题:getSystemService在Context类中定义,所以我假设它在调用时调用context.getSystemService.我无法理解以下getSystemService直接调用的代码BroadcastReceiver.我运行代码,没有错误显示!

代码:

 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();
    }
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*dev 10

getSystemService()是的一部分Context.您需要使用Context您在onReceive()方法中收到的内容:

@Override
public void onReceive(Context context, Intent i) {
    UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
}
Run Code Online (Sandbox Code Playgroud)