我想在我的Android应用程序运行时在后台连续检查互联网连接。我的意思是从应用程序的启动到应用程序的结束。我该怎么做?该方法应该是什么?
答案 0 :(得分:3)
创建扩展BroadcastReceiver的类,使用ConnectivityManager.EXTRA_NO_CONNECTIVITY获取连接信息。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
public class CheckConnectivity extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent arg1) {
boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(isConnected){
Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}
}
}
在mainfest中添加此权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
答案 1 :(得分:1)
Android系统已经为您完成了这项工作。注册BroadcastReceiver
以获取WiFi和网络状态更改,并在WiFi或网络状态发生变化时处理系统发送的Intent
,而不是经常轮询手机的网络状态。
有关详细信息,请查看this question。
注册BroadcastReceiver
后,网络状态更改侦听将在后台(在操作系统中)发生,并且Intent
将在UI线程上发送给您的接收器(最有可能)网络状态发生变化。如果您想在后台主题上收到Intent
,请查看this question以获取更多信息。
答案 2 :(得分:1)
我知道我迟到了回答这个问题。 但这是一种在活动/片段中连续监视网络连接的方法。
我们将使用网络回调来监控活动/片段中的连接
首先,在类
中声明两个变量// to check if we are connected to Network
boolean isConnected = true;
// to check if we are monitoring Network
private boolean monitoringConnectivity = false;
接下来,我们将编写网络回调方法
private ConnectivityManager.NetworkCallback connectivityCallback
= new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
isConnected = true;
LogUtility.LOGD(TAG, "INTERNET CONNECTED");
}
@Override
public void onLost(Network network) {
isConnected = false;
LogUtility.LOGD(TAG, "INTERNET LOST");
}
};
现在我们已经编写了Callback,现在我们将编写一个监视网络连接的方法,在这个方法中,我们将注册我们的NetworkCallback。
// Method to check network connectivity in Main Activity
private void checkConnectivity() {
// here we are getting the connectivity service from connectivity manager
final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
// Getting network Info
// give Network Access Permission in Manifest
final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
// isConnected is a boolean variable
// here we check if network is connected or is getting connected
isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
if (!isConnected) {
// SHOW ANY ACTION YOU WANT TO SHOW
// WHEN WE ARE NOT CONNECTED TO INTERNET/NETWORK
LogUtility.LOGD(TAG, " NO NETWORK!");
// if Network is not connected we will register a network callback to monitor network
connectivityManager.registerNetworkCallback(
new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(), connectivityCallback);
monitoringConnectivity = true;
}
}
我们所有的工作几乎完成了,我们只需要调用checkonnectivity(),我们的Activity / Fragment的onPause()中的方法
@Override
protected void onResume() {
super.onResume();
checkConnectivity();
}
*取消注册onPause()中的NetworkCallback,Activity / Fragment *的方法
@Override
protected void onPause() {
// if network is being moniterd then we will unregister the network callback
if (monitoringConnectivity) {
final ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.unregisterNetworkCallback(connectivityCallback);
monitoringConnectivity = false;
}
super.onPause();
}
就是这样,只需添加此代码,其中您需要监视网络的每个类的Activity / Fragment!。并且不要忘记取消注册!!!
答案 3 :(得分:0)
答案 4 :(得分:0)
要检查Internet连接,只需为 CONNECTIVITY_CHANGE 和 WIFI_STATE_CHANGED 注册广播。因此,每当互联网连接或断开连接时,都会在我们可以编写逻辑的地方调用BroadcastReceiver的onReceive方法。
在AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
android:name="NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
在NetworkChangeReceiver类中。
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
int status = NetworkUtil.getConnectivityStatusString(context);
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
//write code for internet is disconnected...
} else {
//write code for internet is connected...
}
}
}
}
要检查互联网状态。
public class NetworkUtil {
public static final int TYPE_NOT_CONNECTED = 0;
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int NETWORK_STATUS_NOT_CONNECTED = 3;
public static final int NETWORK_STATUS_WIFI = 4;
public static final int NETWORK_STATUS_MOBILE = 5;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}
答案 5 :(得分:0)
在活动或片段中
public static final String BROADCAST = "checkinternet";
IntentFilter intentFilter;
在oncreate里面
intentFilter = new IntentFilter();
intentFilter.addAction(BROADCAST);
Intent serviceIntent = new Intent(this,Networkservice.class);
startService(serviceIntent);
if (Networkservice.isOnline(getApplicationContext())){
Toast.makeText(getApplicationContext(),"true",Toast.LENGTH_SHORT).show();
}else
Toast.makeText(getApplicationContext(),"false",Toast.LENGTH_SHORT).show();
外部oncreate
public BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BROADCAST)){
if (intent.getStringExtra("online_status").equals("true")){
Toast.makeText(getApplicationContext(),"true",Toast.LENGTH_SHORT).show();
Log.d("data","true");
}else {
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
Log.d("data", "false");
}
}
}
};
@Override
protected void onRestart() {
super.onRestart();
registerReceiver(broadcastReceiver,intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,intentFilter);
}
//类
public class Networkservice extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.post(perioud);
return START_STICKY;
}
public static boolean isOnline(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cm.getActiveNetworkInfo();
if (nf!=null&&nf.isConnectedOrConnecting())
return true;
else
return false;
}
Handler handler=new Handler();
private Runnable perioud =new Runnable() {
@Override
public void run() {
handler.postDelayed(perioud,1*1000- SystemClock.elapsedRealtime()%1000);
Intent intent = new Intent();
intent.setAction(MainActivity.BROADCAST);
intent.putExtra("online_status",""+isOnline(Networkservice.this));
sendBroadcast(intent);
}
};
}