1.创建Android程序
2.编写代码
MainActity:
package com.example.network; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; public class MainActivity extends Activity { private Button netWrkBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取控件 netWrkBtn = (Button)findViewById(R.id.netBtn1); //绑定单击事件 netWrkBtn.setOnClickListener(new netWrkService(this)); } }
绑定单击事件的类:
package com.example.network; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class netWrkService implements OnClickListener{ private Context context; private TextView tv1; public netWrkService(Context context){ this.context = context; } @Override public void onClick(View v) { Activity c = (Activity)context; tv1 = (TextView)c.findViewById(R.id.textView1); String netStatus; int color; try { //查看有无网络 ConnectivityManager cm = (ConnectivityManager)c.getSystemService(c.CONNECTIVITY_SERVICE); //查看连接是否成功 NetworkInfo netWrkInfo = cm.getActiveNetworkInfo(); //判断连接给出相应的结果 if(netWrkInfo==null){ netStatus = c.getResources().getString(R.string.net_status1); color = c.getResources().getColor(R.color.red); }else{ netStatus = c.getResources().getString(R.string.net_status0); color = c.getResources().getColor(R.color.green); } } catch (Exception e) { //发生异常时给出的结果 netStatus = c.getResources().getString(R.string.net_status3); color = c.getResources().getColor(R.color.yellow); } tv1.setText(netStatus); tv1.setBackgroundColor(color); } }
string.xml资源文件
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">netWork</string> <string name="net_test">网络测试</string> <string name="net_btn1">测试</string> <string name="net_status0">网络通过</string> <string name="net_status1">网络异常</string> <string name="net_status3">权限不足</string> <string name="action_settings">Settings</string> </resources>
3.测试