Android基础--ConnectivityManager检查网络连接

PrimaryActivity.java

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;

/**
 * Created by JKerving on 2015/11/25.
 */
public class PrimaryActivity extends AppCompatActivity {
    public static final String TAG = "Basic Network Demo";

    private static boolean wifiConnected = false;

    private static boolean mobileConnected = false;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.primary_layout);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//这里使用toolbar,放弃使用actionbar
        setSupportActionBar(toolbar);

        SimpleTextFragment fragment = (SimpleTextFragment)      getFragmentManager().findFragmentById(R.id.intro_fragment);//界面显示使用Fragment,使得我们的UI更易管理,自从Fragment问世以来我们就应当更加频繁的使用Fragment
        fragment.setText(R.string.intro_message);
        fragment.getTextView().setTextSize(TypedValue.COMPLEX_UNIT_DIP,16.0f);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.test_action:
                checkNetworkConnection();
                return true;
            case R.id.clear_action:
                return true;
        }
        return false;
    }

    private void checkNetworkConnection() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()){
            wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
            mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;

            if (wifiConnected){
                Log.i(TAG,getString(R.string.wifi_connection));
            }else if (mobileConnected){
                Log.i(TAG,getString(R.string.mobile_connection));
            }
        }else {
            Log.i(TAG,getString(R.string.no_wifi_or_mobile));
        }
    }
}

SimpleTextFragment.java

import android.app.Fragment;
import android.os.Bundle;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Created by JKerving on 2015/11/25.
 */
public class SimpleTextFragment extends Fragment {
    String mText;

    int mTextId = -1;

    public static final String TEXT_KEY = "text";
    public static final String TEXT_ID_KEY = "text_id";

    private TextView mTextView;

    public SimpleTextFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        //Initialize the variables by using getArguments in Fragment
        //Fragment中的变量我们应当尽可能的使用setArgument与getArgument方法来进行初始化
        if (getArguments() != null){
            Bundle args = getArguments();
            if (args.containsKey(TEXT_KEY)){
                mText = args.getString(TEXT_KEY);
                Log.d("Constructors","Initialize Text");
            }else if (args.containsKey(TEXT_ID_KEY)){
                mTextId = args.getInt(TEXT_ID_KEY);
                mText = getString(mTextId);
                Log.d("Constructors","Initialize TextID and Text");
            }
        }else {
            Toast.makeText(getActivity(),"getAruments is null",Toast.LENGTH_SHORT).show();
        }

        mTextView = new TextView(getActivity());
        mTextView.setGravity(Gravity.CENTER);

        if (mText != null){
            mTextView.setText(mText);
        }

        return mTextView;
    }

    public TextView getTextView(){
        return mTextView;
    }

    public void setText(int stringId){
        getTextView().setText(getActivity().getString(stringId));
    }
}

布局文件
primary_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
        android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

    <fragment
        android:name="com.example.jkerving.basicnetwork.SimpleTextFragment"
        android:id="@+id/intro_fragment"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"/>

</LinearLayout>

在写这个程序的过程中,遇到了一些小问题。
Error:

java.lang.SecurityException: ConnectivityService: Neither user 10063 nor current process has android.permission.ACCESS_NETWORK_STATE.

观察错误发现是由于没有在AndroidManifest.xml中声明取得网络状态的权限,只要加上以下权限即可正常运行:

uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值