ide/androidstudio

네트워크 상태로 자동 실행

C/H 2017. 1. 20. 08:30

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

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

    <application  ...>
        ...
            <receiver
                android:name=".network.NetworkChangeReceiver"
                android:label="NetworkChangeReceiver" >
                <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                </intent-filter>
            </receiver>
        ...
    </application>
</manifest>
package com.domain.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import kr.step1.lotto.MainActivity;

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        int status = NetworkUtil.getConnectivityStatus(context);
        if( status > 0 ){
            // Code
        }
    }
}
package com.domain.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;


    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        String status = null;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}


반응형

'ide > androidstudio' 카테고리의 다른 글

Android 광고, ANDROID_ID  (0) 2017.01.24
초기화 값 저장/호출 SharedPreferences  (0) 2017.01.23
Android Swipe  (0) 2017.01.19
Android Drawable Shape Syntax  (0) 2017.01.18
android SQLite DB 열기  (0) 2017.01.17