检查Internet连接并在TextView类中显示结果

时间:2015-07-18 13:09:31

标签: android

我写了以下代码,如果互联网连接为是,textView对象会显示连接,如果没有则显示断开连接

但是下面的代码不能正常工作。 Null 值是问题的原因吗?

public class MainActivity extends Activity {
    EditText editText;
NetworkInfo networkInfo;
    String string;
    ConnectivityManager connectivityManager = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.textView);
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(networkInfo.isConnected())
  editText.setText("Connect");
        else if(!networkInfo.isConnected())
    editText.setText("Disconnect");
    }

1 个答案:

答案 0 :(得分:0)

在您的代码中,connectivityManager为null。试试这个。

connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnected();