出於某種原因,我的網絡更改接收器不工作,並在我的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");
}
}
}
}
其中是dialog.show(); ??日誌沒有顯示,因爲這兩個條件都不是真的,所以在結束時再多加一些,再次檢查。 –
@DhawalSodhaParmar好的,我在最後加了一個else和一個日誌,並且日誌正在打印。你能粘貼一個修改後的if和else if塊來確定是否有互聯網連接嗎? – fedorp1
檢查我的答案之一http://stackoverflow.com/a/15546897/1168654 –