第一步、自己写一个broadcast接收者
package com.bruce.netconnectionlistener; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * Created by Administrator on 2016/5/10 0010. */ public class ConnectionChangeReceiver extends BroadcastReceiver { private Context context; @Override public void onReceive(Context context, Intent intent) { this.context = context; ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) { showToast("网络不可以用"); //改变背景或者 处理网络的全局变量 } else { showToast("网络可以用"); //改变背景或者 处理网络的全局变量 } } /** * 解决思路: 不用计算Toast的时间之类的,就是定义一个全局的成员变量Toast, 这个Toast不为null的时候才去make,否则直接setText * .为了按返回键后立即使Toast不再显示,重写父类Activity的onBackPressed()方法里面去cancel你的Toast即可. * * @param text */ Toast mToast; public void showToast(String text) { if (mToast == null) { mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT); } else { mToast.setText(text); mToast.setDuration(Toast.LENGTH_SHORT); } mToast.show(); } public void cancelToast() { if (mToast != null) { mToast.cancel(); } } }
第二步、写一个baseactivity,作为基类,里面注册广播。
package com.bruce.netconnectionlistener; import android.app.Activity; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; /** * Created by Administrator on 2016/5/10 0010. */ public class BaseActivity extends Activity { private ConnectionChangeReceiver myReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(); } private void registerReceiver() { IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); myReceiver = new ConnectionChangeReceiver(); this.registerReceiver(myReceiver, filter); } private void unregisterReceiver() { if (myReceiver != null) { this.unregisterReceiver(myReceiver); } } }
3、在需要的类继承该baseactivity
package com.bruce.netconnectionlistener; import android.os.Bundle; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
4、需要的权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" />
时间: 2024-10-07 11:15:26