为了能够让我们的应用得到网络状态需要在application外部增加权限
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.hello.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> <activity android:name="com.example.hello.SystemInfo"> </activity> </application> <!-- Internet Permissions --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Network State Permissions --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
下面我们在MainActivity中增加ListView,并增加ClickListener
public class MainActivity extends Activity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listView = new ListView(this); listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, getData())); listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView)parent; String item = (String) listView.getItemAtPosition(position); if (item.equals("SystemInfo")) { Intent ii=new Intent();
/* 可以向SystemInfo Activity传递数据,这里没有用到 */ ii.putExtra("myKey", "value"); ii.setClass(MainActivity.this, SystemInfo.class); startActivity(ii); } } }); setContentView(listView); } private List<String> getData(){ List<String> data = new ArrayList<String>(); data.add("SystemInfo"); data.add("测试数据2"); data.add("测试数据3"); data.add("测试数据4"); return data; } }
进入SystemInfo Activity
public class SystemInfo extends Activity { /* 保存网络状态 */ private String network_state; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* 获取网络状态 */ ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); Boolean isInternetPresent; isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { network_state = "connecting"; } else { network_state = "disconnect"; } /* 根据res/layout/activity_main.xml中的内容设置TextView内容 */ ((TextView)findViewById(R.id.network_state)).setText(network_state); } }
获取网络状态部分
/* ConnectionDetector.java */ public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context){ this._context = context; } public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { 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; } }
源码:http://pan.baidu.com/share/link?shareid=437617&uk=218977851