Tuesday, July 23, 2013

Android - BroadcastReceiver when wifi or 3g network state changed

You need to set a permissions on android manifest

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

Set up your receiver

<receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>

Receiver code

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() || mobile != null && mobile.isConnectedOrConnecting(); 
        if (isConnected) {
            Log.d("Network Available ", "YES");
        }else{
           Log.d("Network Available ", "NO");
        }
    }
}

Monday, July 22, 2013

Convert binary image to image file

String strBinary = "binary data";
byte[] imageBytes= Base64.decodeBase64(strBinary.getBytes());
InputStream in = new ByteArrayInputStream(imageBytes);
Bitmap b = BitmapFactory.decodeStream(in);