«   2018/09   »
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            
Archives
Today
283
Total
1,153,504
안정적인 DNS서비스 DNSEver
관리 메뉴

Blue Breeze

네트워크 상태로 자동 실행 본문

Editor IDE/AndroidStudio

네트워크 상태로 자동 실행

푸른바람 C/H 2017.01.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;
    }
}


'Editor IDE > AndroidStudio' 카테고리의 다른 글

Android 광고, ANDROID_ID  (0) 2017.01.24
초기화 값 저장/호출 SharedPreferences  (0) 2017.01.23
네트워크 상태로 자동 실행  (0) 2017.01.20
Android Swipe  (0) 2017.01.19
Android Drawable Shape Syntax  (0) 2017.01.18
android SQLite DB 열기  (0) 2017.01.17
0 Comments
댓글쓰기 폼