gpt4 book ai didi

Android 不断检查互联网连接

转载 作者:行者123 更新时间:2023-11-29 14:44:34 26 4
gpt4 key购买 nike

我想在广播接收器的每项 Activity 中持续检查互联网连接。我已经编写了代码并且它运行良好。但我想在每项 Activity 中都使用它。我该如何修改这段代码?

public class MainActivity extends Activity {



private static final String LOG_TAG = "CheckNetworkStatus";
private NetworkChangeReceiver receiver;
private boolean isConnected = false;
private TextView networkStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);

networkStatus = (TextView) findViewById(R.id.networkStatus);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestory");
super.onDestroy();

unregisterReceiver(receiver);

}


public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);

}


private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if(!isConnected){
Log.v(LOG_TAG, "Now you are connected to Internet!");
networkStatus.setText("Now you are connected to Internet!");
isConnected = true;
//do your processing here ---
//if you need to post any data to the server or get status
//update from the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
networkStatus.setText("You are not connected to Internet!");
isConnected = false;
return false;
}
}


}

最佳答案

I want to use it in every activity. How can I modify this code?

创建一个扩展 AppCompatActivityBaseActivity 类,然后让所有的 Activity 类扩展这个 BaseActivity 类。将检查互联网连接的代码放在 BaseActivity 类中。干杯:)

关于Android 不断检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44519331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com