您好,登錄后才能下訂單哦!
在Android中,我們可以使用ConnectivityManager
來監(jiān)聽網(wǎng)絡(luò)狀態(tài)變化。以下是一個(gè)簡單的示例,展示了如何在異步任務(wù)中監(jiān)聽網(wǎng)絡(luò)狀態(tài):
NetworkStateReceiver
的廣播接收器,用于接收網(wǎng)絡(luò)狀態(tài)變化的事件:import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkStateReceiver extends BroadcastReceiver {
private OnNetworkStateChangeListener listener;
public void setOnNetworkStateChangeListener(OnNetworkStateChangeListener listener) {
this.listener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();
if (listener != null) {
listener.onNetworkStateChanged(isConnected);
}
}
}
public interface OnNetworkStateChangeListener {
void onNetworkStateChanged(boolean isConnected);
}
}
import android.content.Context;
import android.content.IntentFilter;
import android.os.AsyncTask;
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private Context context;
private NetworkStateReceiver networkStateReceiver;
public MyAsyncTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
registerNetworkStateReceiver();
}
@Override
protected Void doInBackground(Void... voids) {
// 在這里執(zhí)行你的異步任務(wù)
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
unregisterNetworkStateReceiver();
}
private void registerNetworkStateReceiver() {
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.setOnNetworkStateChangeListener(new NetworkStateReceiver.OnNetworkStateChangeListener() {
@Override
public void onNetworkStateChanged(boolean isConnected) {
// 在這里處理網(wǎng)絡(luò)狀態(tài)變化
}
});
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(networkStateReceiver, intentFilter);
}
private void unregisterNetworkStateReceiver() {
if (networkStateReceiver != null) {
context.unregisterReceiver(networkStateReceiver);
networkStateReceiver = null;
}
}
}
現(xiàn)在,當(dāng)網(wǎng)絡(luò)狀態(tài)發(fā)生變化時(shí),onNetworkStateChanged
方法將被調(diào)用,你可以在這里處理網(wǎng)絡(luò)狀態(tài)變化。請注意,不要忘記在異步任務(wù)結(jié)束時(shí)取消注冊廣播接收器。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。