出于某种原因,我的网络更改接收器无法正常工作,并在我的Android应用程序中向我的NetworkStateReceiver类广播CONNECTIVITY_CHANGE。我已经检查过我的对话框是否只是一个问题,但是应该打印出来的Log.d不是。
以下是AndroidManifest.xml的代码:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver android:name="com.main.main.NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
以下是NetworkStateReceiver.java的代码:
package com.main.main;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class NetworkStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Connection Failed")
.setMessage("Please Check Your Internet Connection")
.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Code for try again
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).create();
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Log.d("INTERNET_MESSAGE", "Connected to internet");
dialog.dismiss();
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.d("INTERNET_MESSAGE", "Disconnected from internet");
}
}
}
}
答案 0 :(得分:2)
最好检查互联网连接如下:
只需在Common实用程序类中创建一个通用函数
/*
* A Common function to check internet connection.
* */
public static boolean isOnline(Context c) {
try {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
现在,使用代码中需要互联网连接的地方,如下所示:
if (isOnline(YourActivity.this)) {
//Your Tasks..
} else {
//Display your AlertBox..
}
答案 1 :(得分:1)
你需要在清单中启用你的接收器..它会工作..
<receiver android:name="com.main.main.NetworkStateReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>