Netstateネットワークが接続されているかどうかを確認
3789 ワード
ネットワーク権限android:name="androidを追加します.permission.ACCESS_NETWORK_STATE”>
MainActivity
NetStateUtil
MainActivity
package com.wzq.netstatedemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int netType = NetStateUtil.getNetType(MainActivity.this);
if (netType != -1) {
initdata();
}else {
Toast.makeText(this, " ", Toast.LENGTH_SHORT).show();
}
}
private void initdata() {
Toast.makeText(this, " ", Toast.LENGTH_SHORT).show();
}
}
NetStateUtil
package com.wzq.netstatedemo;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* author:Created by WangZhiQiang on 2017-11-01.
*/
class NetStateUtil {
/**
*
* -1 :
* 0 : ;
* 1 : wifi
* @return
* @param context
*/
public static int getNetType(Context context) {
int mState = -1;//
// android , ,
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo ==null){
return mState;
}
int type = activeNetworkInfo.getType();
if (type == ConnectivityManager.TYPE_WIFI) {// wifi
mState = 1;
}else if(type == ConnectivityManager.TYPE_MOBILE ){
mState = 0;
}
return mState;
}
}