ACCESSandroid 检查是否上网

文章一:

率先以,AndroidManifest.xml 中追加访问权限:

<uses-permission
android:name=”android.permission.ACCESS_NETWORK_STATE”/>

package com.example.yanlei.myapplication;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //手工增加代码开始
        //将按钮绑定一个单操作的事件监听器。用于监听用户的单击操作。
        Button button = (Button) findViewById(R.id.button2);
        button.setOnClickListener(myOnClickListener);


    }
    public static String getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss");
        return df.format(new Date());
    }
    boolean checkNetwork() {

        // 实例化ConnectivityManager

        ConnectivityManager manager = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

        // 获得当前网络信息

        NetworkInfo info = manager.getActiveNetworkInfo();

        // 判断是否连接

        if (info == null || !info.isConnected()) {

            return false;

            }

        return true;

        }
    //手动增加代码开始
    private View.OnClickListener myOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            //增加自己的代码......
//            Button pButton = (Button) findViewById(R.id.button2);
//            pButton.setText("OnClick. " + "my 新");
            /*Intent intent=new Intent();
            intent.setComponent(new ComponentName("com.android.calendar", "com.android.calendar.LaunchActivity"));
            startActivity(intent);*/

            TextView pTextView=(TextView)findViewById(R.id.textView2);
            String str=pTextView.getText().toString();
            if (checkNetwork()) {
                pTextView.setText("已连上网");
            }
            else {
                pTextView.setText("已连不上网");
            }

        }
    };
    //手动增加代码结束


}

 

相关文章