您好,登錄后才能下訂單哦!
在Android中,我們可以使用ConnectivityManager
來監聽網絡狀態變化。以下是一個簡單的示例,展示了如何在異步任務中監聽網絡狀態:
NetworkStateReceiver
的廣播接收器,用于接收網絡狀態變化的事件: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) {
// 在這里執行你的異步任務
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) {
// 在這里處理網絡狀態變化
}
});
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(networkStateReceiver, intentFilter);
}
private void unregisterNetworkStateReceiver() {
if (networkStateReceiver != null) {
context.unregisterReceiver(networkStateReceiver);
networkStateReceiver = null;
}
}
}
現在,當網絡狀態發生變化時,onNetworkStateChanged
方法將被調用,你可以在這里處理網絡狀態變化。請注意,不要忘記在異步任務結束時取消注冊廣播接收器。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。