如果无法使用互联网,我想将TextView显示为当前活动活动。
我正在上网状态但是如何通知当前的活动活动(我的注意力集中在哪个活动中)。
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent)
{
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("TAG", "Netowk Available");
} else {
//notify it to current active activity and show a textview as
//"No internet connection"
}
}
}
答案 0 :(得分:3)
在您的活动中:
public class YourActivity extends Activity {
private TextView mTextView;
public static final String NETWORK_DISABLE_ACTION = "yourpackagename.action.network_disbale";
private LocalBroadcastManager mLocalBroadcastManager;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(NETWORK_DISABLE_ACTION)) {
mTextView.setText("No internet connection");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_xml);
mTextView = (TextView) findViewById(R.id.your_textView_id);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(NETWORK_DISABLE_ACTION);
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}
}
并在您的NetworkChangeReceiver中:
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("TAG", "Netowk Available");
} else {
//notify it to current active activity and show a textview as
//"No internet connection"
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(
YourActivity.NETWORK_DISABLE_ACTION ));
}