[英]Internet Connectivity Change Broadcast Not Happening
出於某種原因,我的網絡更改接收器無法工作,並在我的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");
}
}
}
}
最好檢查Internet連接如下:
只需在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..
}
您需要在清單中啟用接收器..它將起作用..
<receiver android:name="com.main.main.NetworkStateReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.