关闭

Android 判断当前网络状态从而改变某些控件的状态

标签: android 判断当前网络状态
66人阅读 评论(0) 收藏 举报

   我们做Android 应用时,会遇到这样一种情况,例如:当前界面或控件当有网时展示数据,无网时提示网络出现问题(吐司),或是在控件之上覆盖一个控件,根据网络的状态让显示隐藏,当然这是我粗浅的一种想法,我在这写的是咋样判断网络状态(有网 没网),判断网络我这有两种想法,一种是在你组件使用之前利用下面一的方法的得到网络状态true或false,从而进行相对应操作;二是写一个服务service让他监听当前网络状态然后通过广播将网络状态记录到sharedPreferences·,控件通过·当前的sharePreferences得到网络状态,从而进行相应的操作。(我现在知识有限,也许大家有更好的方法请指教,提点)

/**

* 判断网络链接
*
* @param context
* @return
*/
public static boolean isNetWorkAvailable(Context context) {

ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;

}



package com.example.networkstatusdemo;


import android.support.v7.app.ActionBarActivity;


import org.w3c.dom.Text;


import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class MainActivity extends Activity {
MyService myservice;
SharedPreferences sharedpreferences;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView)findViewById(R.id.textview_main);
myservice=new MyService();
Intent intent=new Intent(MainActivity.this,myservice.getClass());
MainActivity.this.startService(intent);
if(write()!=4){
text.setText("网络出现错误!");
}
}
public int write(){
SharedPreferences preferences=getSharedPreferences("wangluo",MODE_PRIVATE);
int num=preferences.getInt("code",-1);
return num;
}
}




package com.example.networkstatusdemo;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.AvoidXfermode.Mode;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.preference.Preference;
import android.widget.Toast;


public class MyService extends Service{
private ConnectivityManager connectivitymanager;
private NetworkInfo networkinfo;


SharedPreferences sharedPreferences=null;



private BroadcastReceiver mRecevicer=new BroadcastReceiver(){


@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action=intent.getAction();
if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){
Toast.makeText(getApplicationContext(),"网络状态改变",Toast.LENGTH_LONG).show();
}
connectivitymanager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkinfo=connectivitymanager.getActiveNetworkInfo();
if(networkinfo!=null&&networkinfo.isAvailable()){
String name=networkinfo.getTypeName();
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
read();
}
}).start();
}else{
Toast.makeText(getApplicationContext(),"没有可用网路",Toast.LENGTH_SHORT).show();
delete();
}
}

};


@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
sharedPreferences=getSharedPreferences("wangluo",Context.MODE_PRIVATE);
IntentFilter intent=new IntentFilter();
intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mRecevicer, intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub

return super.onStartCommand(intent, flags, startId);
}
public void read(){
Editor editor=sharedPreferences.edit();
editor.putInt("code",4);
editor.commit();
}

public void delete(){
sharedPreferences.edit().clear().commit();
}


}


请单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.networkstatusdemo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
   


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <service android:name="com.example.networkstatusdemo.MyService">
            
        </service>
    </application>


</manifest>



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4178次
    • 积分:102
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:4篇
    • 译文:0篇
    • 评论:1条
    文章存档