Wednesday 1 March 2017

Andorid marshmallow custom permission code

As we all know android has put some restrictions for permission check for security reasons from android M (6.0) Marshmallow.

Here we gonna share a simple code snippets to customize permission check and put it where you find suitable in your code.

 

Android developer training guide link:  Marshmallow permission


1) Declare permission 

 

public static final String PHONE_PERMISSION = "android.permission.READ_PHONE_STATE";


public static final String CAMERA_PERMISSION = "android.permission.CAMERA";

 

2) xml layout for custom alert dialog (custom_permission_alert.xml)


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainmenu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@null"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/background_color"
        android:clickable="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|left"
            android:text="@string/message"
            android:padding="10dp"
            android:textColor="@color/white_color"
            android:textSize="@dimen/header_text_size" />


        <TextView
            android:id="@+id/message_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:gravity="center|left"
            android:textColor="@color/white_color"
            android:textSize="@dimen/content_text_size" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/action_no_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toLeftOf="@+id/action_yes_tv"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:text="@string/no"
                android:padding="10dp"
                android:visibility="gone"
                android:textColor="@color/white_color"
                android:textSize="@dimen/content_text_size" />

            <TextView
                android:id="@+id/action_yes_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="5dp"
                android:text="@string/ok"
                android:padding="10dp"
                android:textColor="@color/white_color"
                android:textSize="@dimen/content_text_size" />


        </RelativeLayout>
    </LinearLayout>

</LinearLayout>

 

3) Now create an alert dialog using above xml layout

 

/**
     * This method shows alert dialog to prompt user to enable phone permissions.
     *
     * @param title   the title
     * @param message the message
     */

    public static void showPermissionAlertDialog(final String title, String message,
                                                 final Activity context) {
        try {
            final Dialog dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            dialog.setContentView(R.layout.app_custom_dialog);
   
            dialog.setCancelable(false);

            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

            // set the custom dialog components - text, image and button

            TextView titleTv = (TextView) dialog.findViewById(R.id.title_tv);
            titleTv.setText(title);

            TextView actionYesTv = (TextView) dialog.findViewById(R.id.action_yes_tv);
            actionYesTv.setText(context.getResources().getString(R.string.allow));

            TextView actionNoTv = (TextView) dialog.findViewById(R.id.action_no_tv);
            actionNoTv.setText(context.getResources().getString(R.string.deny));
            actionNoTv.setVisibility(View.VISIBLE);

            TextView messageTv = (TextView) dialog.findViewById(R.id.message_tv);
            messageTv.setText(message);


            actionYesTv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    // Open app settings screen to allow required permissions.
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                    intent.setData(uri);
                    context.startActivity(intent);
                    dialog.dismiss();
                }
            });

            actionNoTv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            if (dialog != null && !dialog.isShowing()) {
                dialog.show();
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4) Steps to call the above functions in real scenario 

 

/** 

* Check if device sdk version is greater than or equal to android M

*/

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!Util.checkDevicePermissionRuntime(this, 

Util.CAMERA_PERMISSION)) {
                        Util.showPermissionAlertDialog(getResources().getString(R.string.alert),
                                getResources().getString(R.string.allow_app_to_access_device_feature), this);

       }                   

}

 

Here we done with custom permission check implementation for Marshmallow and above versions.

 

Thanks!

Friday 10 February 2017

Network provider checksum for android (phone/tablet)

It is important to check network availability before starting search for network services like jmdns search, network check before doing any kind of network operations. 

 

1) Util class for network check

 

/**
 * This class checks network state in mobile device
 */
public class NetworkUtil {

    /**
     * The refrence.
     */
    public static NetworkUtil refrence = null;

    /**
     * Method returns class object.
     *
     * @return single instance of NetworkUtil
     */
    public static NetworkUtil getInstance() {
        if (null == refrence)
            refrence = new NetworkUtil();
        return refrence;
    }


    /**
     * Check network state.
     *
     * @param context the context
     * @return true, if successful
     */
    public static boolean checkNetworkStatus(Context context) {
        boolean hasConnectedWifi = false;
        boolean hasConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        //For loop to get all data provide in mobile device
        for (NetworkInfo ni : netInfo) {
            //If wifi detected then check for connection state
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected()){
                    hasConnectedWifi = true;
                }


            //If mobile data detected then check for connection state
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    hasConnectedMobile = true;
        }
        return hasConnectedWifi || hasConnectedMobile;
    }
}

 

Here is the code to access NetworkUtil class where you have to pass context of activity and will return true/false to show network availability.

 

boolean isNetworkAvailable=

    NetwrokUtil.checkNetworkStatus(context);

 

Here we done with Network check in android device (phone/tablet).

 

Thanks...!!!

 

Friday 27 January 2017

Android JMDNS Search Tutorial.

A simple example to getting start with Zero configuration service integration with your android app. Lets start with some simple steps below:


1) First of all create a simple JmdnsUtil class:


public class JmdnsUtil {

    public static final String SERVICE_TYPE="_http._tcp.local.";
    public static final String SERVICE_NAME="AppName";
    public static final int PORT=1234;


}



2) In step second create a helper class that will contain all method stuffs:


public class JmdnsHelper {

    private String[] serviceNames = null;

    /**
     * This method registers jmdns service
     */

    public void registerJmdnsService() {
        try {
            // Create a JmDNS instance
            JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());

            // Register a service
            ServiceInfo serviceInfo = ServiceInfo.create(JmdnsUtil.SERVICE_TYPE,
                    JmdnsUtil.SERVICE_NAME,
                    JmdnsUtil.PORT, "path=index.html");
            jmdns.registerService(serviceInfo);

            // Wait a bit
            Thread.sleep(100);//25000

            //Call discover services method
            discoverJmdnsService();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method discovers jmdns services or
     * connected devices in local network
     */

    public String[] discoverJmdnsService() {
        JmDNS jmdns = null;
        try {
            jmdns = JmDNS.create();

            //while (true) {

            ServiceInfo[] infos = jmdns.list(JmdnsUtil.SERVICE_TYPE);
            serviceNames = new String[infos.length];
        
            for (int i = 0; i < infos.length; i++) {
                serviceNames[i] = infos[i].getName();
                // Here we can fetch all required details of device.
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (jmdns != null) try {
                jmdns.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }

        if (serviceNames != null && serviceNames.length > 0) {
            return serviceNames;
        } else {
            return null;
        }
    }
}



3) Now create a service which runs in background to search for connected devices or registered services in local network.

public class JmdnsService extends Service {

    /**
     * Jmdns Constructor
     */

    public JmdnsService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        startSearchTcpIpLocalServices();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * This method starts searching of devices in local network
     */

    private void startSearchTcpIpLocalServices() {
        if (NetworkAvailablity.checkNetworkStatus(this)) {
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //Do network search operation
                        JmdnsHelper jmdnsHelper = new JmdnsHelper();
                        final String serviceName[] = jmdnsHelper.discoverJmdnsService();

                        if (serviceName != null && serviceName.length > 0) {
                            JmdnsService.this.stopSelf();
                        } else {

                        }
                    }
                }).start();
            } catch (NullPointerException n) {
                n.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            JmdnsService.this.stopSelf();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}


Here we done with simple JMDNS search integration. You can find jmdns jar at the path below.

Download JMDNS JAR

 

Thanks...!!!















Andorid marshmallow custom permission code

As we all know android has put some restrictions for permission check for security reasons from android M (6.0) Marshmallow. Here we gon...