BroadcastReceiver中如何直接使用方法"getSystemService"?
how can method "getSystemService" be used directly in BroadcastReceiver?
我遇到了这个问题:getSystemService
在 Context
class 中定义,所以我假设它在 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();
}
}
}
}
因为你的 NetworkChangeReceiver
是 MainActivity
的内部 class。
您正在使用 Activity 上下文。
尝试在新文件中使用 NetworkChangeReceiver(不是 sub class),你会看到会发生什么。
MainActivity.this
虽然它指的是你自己的 class 扩展了 Activity class 但基础 class (Activity) 也扩展了上下文 class,因此它可用于提供 activity 上下文。
getSystemService()
是 Context
的一部分。您需要使用在 onReceive()
方法中收到的 Context
:
@Override
public void onReceive(Context context, Intent i) {
UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
}
我遇到了这个问题:getSystemService
在 Context
class 中定义,所以我假设它在 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();
}
}
}
}
因为你的 NetworkChangeReceiver
是 MainActivity
的内部 class。
您正在使用 Activity 上下文。
尝试在新文件中使用 NetworkChangeReceiver(不是 sub class),你会看到会发生什么。
MainActivity.this
虽然它指的是你自己的 class 扩展了 Activity class 但基础 class (Activity) 也扩展了上下文 class,因此它可用于提供 activity 上下文。
getSystemService()
是 Context
的一部分。您需要使用在 onReceive()
方法中收到的 Context
:
@Override
public void onReceive(Context context, Intent i) {
UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
}