22 May 2017

Runtime Permissions in Android Marshmallow

Today I will show you Android Marshmallow Permissions Example. One of the major changes in Android Marshmallow is the new permission system. In earlier versions we were declaring the permission in the AndroidManifest.xml file. But with Android Marshmallow we need to ask the permission at run time.  In this post I will show you a simple Android Marshmallow Permissions Example. So lets begin.

Permission Groups

Different types of permissions are separated into groups based on which data or resource it requests access for. Once permission from a group has been granted, then other permissions within that group do not need to be granted again.

For example, a permission group for SMS can send or receive the SMS. Those are two different permissions but the user only needs to allow one.

Android 6.0 Marshmallow has nine main groups of permissions:

Calendar: Read and/or write to the calendar.

Camera: Give the application the ability to access the camera.

Location: Access fine or coarse location.

Microphone: The ability to record audio.

Phone: Includes phone state; the ability to make calls, read, and write to the call log; and voicemail.

Sensor: The ability to use various sensors in the device, like a gyroscope.

SMS: Similar to how the phone is handled including sending and receiving texts. MMS and cell broadcasts.

Storage: Read and write to device’s external storage.

Here, i have added relation Permissions to provide multiple permission at once in the app.

Main Activity :

In this example, its acquiring permission for Location and Camera. Below is the code snippet check whether permission is allow or not by user. if it's not then its requesting for permission.

if ( !checkPermission() )
                {

                    requestPermission();

                }
                else
                {

                    Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();

                }
Below are the full code snippet :

static int PERMISSION_REQUEST_CODE=100;
private boolean checkPermission()
    {
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
        {
            int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
            int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);

            return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
        }
        else
        {
            return  true;
        }
    }

    private void requestPermission()
    {

        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);

    }

    @Override
    public void onRequestPermissionsResult( int requestCode, String permissions[], int[] grantResults )
    {
        switch ( requestCode )
        {
            case PERMISSION_REQUEST_CODE:
                if ( grantResults.length > 0 )
                {

                    boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if ( locationAccepted && cameraAccepted )
                    {
                        Snackbar.make(view, "Permission Granted, Now you can access location data and camera.", Snackbar.LENGTH_LONG).show();
                        Log.v("Main Activity ==>", "All permission Granted");
                    }
                    else
                    {

                        Snackbar.make(view, "Permission Denied, You cannot access location data and camera.", Snackbar.LENGTH_LONG).show();

                        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
                        {
                            if ( shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) )
                            {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                                    new DialogInterface.OnClickListener()
                                                    {
                                                        @Override
                                                        public void onClick( DialogInterface dialog, int which )
                                                        {
                                                            if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
                                                            {
                                                                requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA},
                                                                                   PERMISSION_REQUEST_CODE);
                                                            }
                                                        }
                                                    });
                                return;
                            }
                        }

                    }
                }


                break;
        }
    }


    private void showMessageOKCancel( String message, DialogInterface.OnClickListener okListener )
    {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

7 Apr 2016

Retrofit 2.0 Android | Web service using Retrofit.

Retrofit is developed by Square, Inc. It is one of the most popular HTTP Client Library for Android as a result of its simplicity and its great performance compare to the others.

A part from development,Old method to using web service which is quite lengthy and time consuming.

Here retrofit set everything for you automatically. Now Lets implement Retrofit in our code.

Step 1 : Create studio project.
Now we will Add Retrofit library to our project : Visit Retrofit Official Site
For Android Studio you just need to paste below line of code under dependency of  build.gradle file.

compile 'com.squareup.retrofit2:retrofit:2.0.1'

Now, Add Another library called Okhttp to our project
compile 'com.squareup.okhttp:okhttp:2.4.0' 

Now, Add two more Library Gson and GsonConverter to build.gradle
compile 'com.google.code.gson:gson:1.7.2' 
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Now, Add one more lib to display log of request and response from retrofit.
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'

SERVICE : 
Let's take Login service to implement using retrofit. below is the service for user login which have two parameter Username and password.
http://xyz/service/userlogin?Username=xyz&password=abc

Step 2: Create POJO/Class
Now we will make all POJO of JSON data coming from server. in my case here is the JSON response of the server.
{"status":"true","message":"Login successfully","data":{"id":1,"first_name":"Hasmukh","last_name":"Bhadani"}}

POJO class in Retrofit by Most Easiest Way :

  • Visit pojo.sodhanalibrary - This is Official website to Convert JSON Data into POJO class. Just You have to Copy Paste all the Codes. Rename pojo as per your requirement.


Here I am creating Three POJO : (1)BaseResponse (2)LoginResponse. (3)UserInfo

BaseResponse :
It contain common filed which is used for whole server in the project.

  public class BaseResponse {

    private String message;

    private String status;

    public String getMessage ()
    {
        return message;
    }

    public void setMessage (String message)
    {
        this.message = message;
    }

    public boolean getStatus ()
    {
        return status.equalsIgnoreCase("true");
    }

    public void setStatus (boolean status)
    {
        this.status = String.valueOf(status);
    }
}
LoginResponse :
   public class LoginResponse extends BaseResponse
{
    private Data data;
    public Data getData ()
    {
        return data;
    }
    public void setData (Data data)
    {
        this.data = data;
    }
   
}
UserInfo: 
   public class UserInfo
{
     private String id;

    private String first_name;

    private String last_name;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public String getFirst_name ()
    {
        return first_name;
    }

    public void setFirst_name (String first_name)
    {
        this.first_name = first_name;
    }

    public String getLast_name ()
    {
        return last_name;
    }

    public void setLast_name (String last_name)
    {
        this.last_name = last_name;
    }
   
}
Step 3: Create RestClient.java
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
import com.truckforload.app.AppUrls;
import java.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

public class RestClient
{
    private static ApiInterface restClient;
    static
    {
        setupRestClient();
    }
    private RestClient() {}

    public static ApiInterface get()
    {
        return restClient;
    }
    private static void setupRestClient()
    {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

        HttpLoggingInterceptor interceptorBody = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        client.interceptors().add(interceptor);
        client.interceptors().add(interceptorBody);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppUrls.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        restClient = retrofit.create(ApiInterface.class);
    }
}
Step 4: Create ApiInterface.java
Now create an Interface for all http methods and parameter.

import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query;

public interface ApiInterface
{
    // Login
    @GET("service/userlogin")
    Call<LoginResponse> login( @Query("Username") String strUsername, @Query("password") String strpassword);

}
Step 5: Create AppWs.java
It contain all method of project which are used for service.And it will provide response using call back listener.

import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class AppWs
{
    private static final String TAG = "AppWs";

    public static String login( final LoginRequest request, final Context context, final WsListener listener )
    {
        String unm= request.getUsername();
        String password = request.getPassword();

        Call<LoginResponse> call = RestClient.get().login(unm, password);
        try
        {
            call.enqueue(new Callback<LoginResponse>()
            {
                @Override
                public void onResponse( Response<LoginResponse> response, Retrofit retrofit )
                {
                    LoginResponse baseResponse = response.body();
                    if ( baseResponse != null && response.isSuccess() )
                    {
                        if ( listener != null )
                        {
                            listener.onResponseSuccess(baseResponse);
                        }
                    }
                    else
                    {
                        if ( listener != null )
                        {
                            ResponseBody errorBody = response.errorBody();

                            if ( errorBody != null )
                            {
                                listener.notifyResponseFailed(errorBody.toString(), null);
                            }
                        }

                    }
                }

                @Override
                public void onFailure( Throwable t )
                {
                    retrofitError(t, listener, context);
                }

            });

        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        return "";
    }


    public static void retrofitError( Throwable t, WsListener listener, Context context )
    {
        if ( listener != null )
        {
            t.printStackTrace();
            listener.notifyResponseFailed(null, null);
        }
    }

    public interface WsListener
    {
        void onResponseSuccess( BaseResponse baseResponse );

        void notifyResponseFailed( String message, BaseRequest request );
    }
}
Step 6: Create MainActivity.java
Below is the Method which is call on SignIn Button in the activity

private void callServiceLogin()
    {
  ProgressDialog progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("Loading...");
  progressDialog.setCancelable(false);

        LoginRequest loginRequest = new LoginRequest();

        String phone = etUserName.getText().toString();
        loginRequest.setUsername(phone);

        String password = etPassword.getText().toString();
        loginRequest.setPassword(password);

        AppWs.login(loginRequest, this, new AppWs.WsListener()
        {
            @Override
            public void onResponseSuccess( BaseResponse baseResponse )
            {
  if (progressDialog != null && progressDialog.isShowing())
             {
                 progressDialog.dismiss();
             }

                if ( baseResponse instanceof LoginResponse )
                {
                    LoginResponse loginResponse = (LoginResponse) baseResponse;

                    boolean status = loginResponse.getStatus();
                    UserInfo userInfo = loginResponse.getData();
                }
            }

            @Override
            public void notifyResponseFailed( String message, BaseRequest request )
            {
                dismissProgressDialog();                
            }
        });

    }
Here is the official site to get more API interface declaration for service. Visit here.

Find following are the reference links to go in deep for retrofi 2.0 :
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.iayon.com/consuming-rest-api-with-retrofit-2-0-in-android/

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)