現在我可以檢查單個活動的網絡狀態,並且它確實工作正常。但是,假設我想檢查每一項活動的互聯網。如何修改此代碼?我嘗試了很多方法但失敗了。Android檢查每個活動的網絡狀態(連續)
package com.example.wohhi.nointernetsnackbar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView status;
private static final String LOG_TAG = "CheckNetworkStatus";
private NetworkChangeReceiver receiver;
private boolean isConnected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView) findViewById(R.id.status);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
}
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.getActiveNetworkInfo();
if (info != null) {
if (info.isConnectedOrConnecting()) {
if(!isConnected){
Log.v(LOG_TAG, "Now you are connected to Internet!");
String status = "Now you are connected to Internet!";
Snackbar.make(findViewById(R.id.activity_main), status, Snackbar.LENGTH_LONG).show();
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!");
String status = "You are not connected to Internet!";
Snackbar.make(findViewById(R.id.activity_main), status, Snackbar.LENGTH_LONG).show();
isConnected = false;
return false;
}
}
}
不能使用'BaseActivity'或普通類嗎? – Piyush
我想創建一個普通的類,但問題是我嘗試了很多,但每次都會產生新問題。 –
準確產生了什麼問題? –