Saturday, January 20, 2018

Android Intent

Today, I'm going to discuss some small snippet of Intent. An Intent is basically a message that is passed between components (such as Activities, Services, Broadcast Receivers, and Content Providers). One component that wants to invoke another has to only express its intent to do a job. And any other component that exists and has claimed that it can do such a job through intent-filters, is invoked by the Android platform to accomplish the job. This means, neither components are aware of each other's existence but can still work together to give the desired result for the end-user.


An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a Background Service.


Intent perform late runtime binding between the code in different applications.

Action: The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.

Data: The data to operate on, such as a personal record in the contacts database, expressed as a Uri.


Now let's see some code snippet.

1. Open camera.

 public Intent openCamera(Uri mCameraOutput) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraOutput);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            cameraIntent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1);
        } else {
            cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
        }
        return cameraIntent;
    }

2. Open Gallery.

    public Intent getGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        String[] mimeTypes = {"image/jpeg", "image/jpg", "image/png"};
        galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        return galleryIntent;
    }





3. Open dialer screen.


@Override
    public void call(String mobile) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + mobile));
        startActivity(intent);
    }

4. Move to google play store.

@Override
    public void moveToGooglePlayStore() {
        if (fragmentBaseActivity != null) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + fragmentBaseActivity.getPackageName())));
        }
    }

5. Send a mail.

/**
     * Send invitation email.
     */
    private void onShareClick() {

            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_SUBJECT, fragmentBaseActivity.getString(R.string.share_referral_code));
            email.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(new StringBuilder()
                    .append("<html>")
                    .append("<p>" + fragmentBaseActivity.getString(R.string.hi) + "</p>")
                    .append("<p>" + fragmentBaseActivity.getString(R.string.refer_content) + "</p>")
                    .append("<p><h2>" + mReferCode + "</h2></p>")
                    .append("<p>" + fragmentBaseActivity.getString(R.string.app_google_play_store_content) + "</p>")
                    .append("<p>" + fragmentBaseActivity.getString(R.string.app_link)+" "+ "<a href=>" + "http://play.google.com/store/apps/details?id=" + fragmentBaseActivity.getPackageName() + "</a></p><br>")
                    .append("<p>" + fragmentBaseActivity.getString(R.string.regards) + "</p>")
                    .append("<p>" + mPresenter.getLoginUserName() + "</p>")
                    .append("</html>")
                    .toString()));

            email.setType("text/html");
            startActivity(Intent.createChooser(email, "Choose an Email client :"));
     
    }

Share:

Mobile number verification with Nexmo

Introduction: Nowadays, A small and big application using the user mobile number for registration on their application.
For verifying valid mobile number we have to depend on 3rd party application like Nexmo. Nexmo provides mobile number verification service with a voice call or SMS OTP.

I'm going to explain mobile number verification feature with Android SDK. We have to add a dependency to the application Gradle file.


implementation 'com.nexmo:verify:4.0.0'


Create an account on nexmo.com. After that register their app by using the following steps.

1. Go to Nexmo and click on verify tab.



2. Create an application.



Once you create an application. You can find your application credentials and use it in below snippet.

1. Get an instance of NexmoUtil class and use setListener(this) for the callback.

 public static NexmoUtil getInstance(Context context) {
        if (verifyClient == null) {
            mInstance = new NexmoUtil();
            try {
                NexmoClient nexmoClient = new NexmoClient.NexmoClientBuilder()
                        .context(context)
                        .applicationId(context.getString(R.string.nexmo_application_id))
                        .sharedSecretKey(context.getString(R.string.nexmo_shared_secret_key))
                        .build();
                verifyClient = new VerifyClient(nexmoClient);
            } catch (ClientBuilderException e) {
                Crashlytics.logException(e);
            }
        }
        return mInstance;
    }


2. To get OTP, call sendOtp("IN","mobile number") method of following utility with country code(INDIA-IN) and valid mobile number.

 private void sendOtp(String countryCode, String mobileNumber) {
        if (verifyClient != null && countryCode != null && mobileNumber != null) {
            verifyClient.getVerifiedUser(countryCode, mobileNumber);
        }
    }

3. After some time onVerifyInProgress() will notify you about the progress.

 @Override
    public void onVerifyInProgress(VerifyClient verifyClient, UserObject userObject) {
        if (mNexmoListener != null) {
            mNexmoListener.onMobileVerificationInProgress(verifyClient, userObject);
        }
    }

4. At the end, if you got OTP, verify it by using the checkPinCode("----") method.

 public void checkPinCode(String otp) {
        if (verifyClient != null && otp != null) {
            verifyClient.checkPinCode(otp);
        }
    }



5. If Nexmo find valid OTP onUserVerified() will invoke.


 @Override
    public void onUserVerified(VerifyClient verifyClient, UserObject userObject) {
        if (mNexmoListener != null) {
            mNexmoListener.onMobileNumberVerified(verifyClient, userObject);
        }
    }


View complete utility.



import com.nexmo.sdk.NexmoClient;
import com.nexmo.sdk.core.client.ClientBuilderException;
import com.nexmo.sdk.verify.client.VerifyClient;
import com.nexmo.sdk.verify.event.Command;
import com.nexmo.sdk.verify.event.CommandListener;
import com.nexmo.sdk.verify.event.SearchListener;
import com.nexmo.sdk.verify.event.UserObject;
import com.nexmo.sdk.verify.event.UserStatus;
import com.nexmo.sdk.verify.event.VerifyClientListener;
import com.nexmo.sdk.verify.event.VerifyError;

import java.io.IOException;

/**
 * Handle mobile number verification feature of app.
 */
public class NexmoUtil implements VerifyClientListener, SearchListener {

    private static VerifyClient verifyClient;
    private static NexmoUtil mInstance;
    private NexmoListener mNexmoListener;
    private String mCountryCode;
    private String mMobileNumber;

    public static NexmoUtil getInstance(Context context) {
        if (verifyClient == null) {
            mInstance = new NexmoUtil();
            try {
                NexmoClient nexmoClient = new NexmoClient.NexmoClientBuilder()
                        .context(context)
                        .applicationId(context.getString(R.string.nexmo_application_id))
                        .sharedSecretKey(context.getString(R.string.nexmo_shared_secret_key))
                        .build();
                verifyClient = new VerifyClient(nexmoClient);
            } catch (ClientBuilderException e) {
                Crashlytics.logException(e);
            }
        }
        return mInstance;
    }

    /**
     * Set Callback listener.
     *
     * @param listener instance.
     */
    public void setListener(NexmoListener listener) {
        mNexmoListener = listener;
        if (verifyClient != null) {
            verifyClient.removeVerifyListeners();
            verifyClient.addVerifyListener(this);
        }
    }

    @Override
    public void onException(IOException e) {
        Crashlytics.logException(e);
        if (mNexmoListener != null) {
            mNexmoListener.onMobileVerificationError(null);
        }
    }

    @Override
    public void onVerifyInProgress(VerifyClient verifyClient, UserObject userObject) {
        if (mNexmoListener != null) {
            mNexmoListener.onMobileVerificationInProgress(verifyClient, userObject);
        }
    }

    @Override
    public void onUserVerified(VerifyClient verifyClient, UserObject userObject) {
        if (mNexmoListener != null) {
            mNexmoListener.onMobileNumberVerified(verifyClient, userObject);
        }
    }

    @Override
    public void onError(VerifyClient verifyClient, VerifyError errorCode, UserObject user) {
        if (mNexmoListener != null) {
            mNexmoListener.onMobileVerificationError(errorCode);
        }
    }

    /**
     * Send number for get OTP.
     *
     * @param countryCode  country code.
     * @param mobileNumber mobile number.
     */
    public void getVerifiedUser(final String countryCode, final String mobileNumber) {
        mCountryCode = countryCode;
//        mCountryCode = "IN"
        mMobileNumber = mobileNumber;
        verifyClient.getUserStatus(mCountryCode, mobileNumber, NexmoUtil.this);
    }

    /**
     * Cancel verified number.
     *
     * @param countryCode  country code.
     * @param mobileNumber mobile number.
     */
    private void cancelVerification(final String countryCode, final String mobileNumber) {
        verifyClient.command(countryCode, mobileNumber, Command.LOGOUT, new CommandListener() {
            @Override
            public void onSuccess(Command command) {
                sendOtp(countryCode, mobileNumber);
            }

            @Override
            public void onError(Command command, VerifyError verifyError, String s) {
                if (mNexmoListener != null) {
                    mNexmoListener.onMobileVerificationError(verifyError);
                }
            }

            @Override
            public void onException(IOException e) {
                Crashlytics.logException(e);
                if (mNexmoListener != null) {
                    mNexmoListener.onMobileVerificationError(null);
                }
            }
        });
    }

    /**
     * Get OPT
     *
     * @param countryCode  country code.
     * @param mobileNumber mobile number.
     */
    private void sendOtp(String countryCode, String mobileNumber) {
        if (verifyClient != null && countryCode != null && mobileNumber != null) {
            verifyClient.getVerifiedUser(countryCode, mobileNumber);
//          verifyClient.getVerifiedUser("IN", mobileNumber)
        }
    }

    /**
     * Verify OTP.
     *
     * @param otp value.
     */
    public void checkPinCode(String otp) {
        if (verifyClient != null && otp != null) {
            verifyClient.checkPinCode(otp);
        }
    }

    @Override
    public void onUserStatus(UserStatus userStatus) {
        if (userStatus == UserStatus.USER_VERIFIED) {
            cancelVerification(mCountryCode, mMobileNumber);
        } else {
            sendOtp(mCountryCode, mMobileNumber);
        }
    }

    @Override
    public void onError(VerifyError verifyError, String s) {
        if (mNexmoListener != null) {
            mNexmoListener.onMobileVerificationError(verifyError);
        }
    }

    public interface NexmoListener {

        /**
         * Number verification under progress.
         *
         * @param verifyClient instance.
         * @param userObject   instance.
         */
        void onMobileVerificationInProgress(VerifyClient verifyClient, UserObject userObject);

        /**
         * Enter OTP verified.
         *
         * @param verifyClient instance.
         * @param userObject   instance.
         */
        void onMobileNumberVerified(VerifyClient verifyClient, UserObject userObject);

        /**
         * Nexmo API's error.
         *
         * @param verifyError instance.
         */
        void onMobileVerificationError(VerifyError verifyError);
    }
}
Share:

Get it on Google Play

React Native - Start Development with Typescript

React Native is a popular framework for building mobile apps for both Android and iOS. It allows developers to write JavaScript code that ca...