嗨,我是 Android 的新手。我需要检查整个应用程序的网络连接,并在状态改变时通知用户网络状态。请告诉我如何处理一些示例代码。提前致谢
问问题
402 次
1 回答
0
您可以使用runOnUiThread
和ConnectivityManager
在固定时间后检查网络状态并向用户显示消息:
private boolean mNetworkRunning=false;
private ConnectivityManager connMgr;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.main);
mClockRunning=true;
NetworkStatusThread();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Stop Thread Here.
mNetworkRunning=false;
}
public void NetworkStatusThread(){
Thread th=new Thread(){
@Override
public void run(){
try
{
while(mNetworkRunning)
{
Thread.sleep(1000L);// set time here for refresh time in show update to user
NetworkActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(mNetworkRunning)
{
boolean statu=isMobileNetworkAvailable();
if(statu==true)
Toast.makeText(YourCurrentActivity.this, "Network Available",Toast.LENGTH_LONG).show();
else
Toast.makeText(YourCurrentActivity.this, "Network Not Available",Toast.LENGTH_LONG).show();
}
};
}
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
public boolean isMobileNetworkAvailable(Context con){
if(null == connMgr){
connMgr = (ConnectivityManager)con.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo wifiInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifiInfo.isAvailable()){
return true;
}else if(mobileInfo.isAvailable()){
return true;
}else{
return false;
}
}
第二个选项不使用线程,那么您可以将CONNECTIVITY_CHANGE
Manifest.xml 的接收器注册为:
< !-- Needed to check when the network connection changes -->
< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
< receiver android:name="you_package_name.ConnectionChangeReceiver"
android:label="NetworkConnection">
< intent-filter>
< action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
< /intent-filter>
< /receiver>
在代码中:
public class ConnectionChangeReceiver extends BroadcastReceiver {
private static final String TAG =ConnectionChangeReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
boolean success = false;
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
//WIFI
if (State.CONNECTED == state) {
success = true;
}
//GPRS
state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
if (State.CONNECTED != state) {
success = true;
}
if (!success) {
Toast.makeText(context, "SHOW STATUS HERE", Toast.LENGTH_LONG).show();
}
}
于 2012-06-23T10:10:55.313 回答