我是android的初学者,我写这个类来检查网络连接:
public class ConnectivityDetector {
public static boolean IS_INTERNET_AVAILABLE(Context context){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
并且使用此代码我想要调用该类:
public class AlarmReciever extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityDetector.IS_INTERNET_AVAILABLE(AlarmReciever.this)) {
//write my code
}
}
}
但在这一行:
if (ConnectivityDetector.IS_INTERNET_AVAILABLE(AlarmReciever.this))
我该怎么解决?
答案 0 :(得分:3)
AlarmReciever
不是上下文,因此您无法使用this
。您在接收时有参数Context context
。你可以使用那个。
public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityDetector.IS_INTERNET_AVAILABLE(context)) {
//write my code