Android : Start a Phone Call with Android API


For your app, you could need to start a phone call from it. Android API offers two methods (at least) to achieve that.

The first approach doesn’t require any specific permission but, it doesn’t really start the call. Instead, it displays the number to call to the user which could start it or not.

    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.fromParts("tel", phoneNumber, null));
    startActivity(intent);

When you want to prepend the phone number with some special chars sequence (here with #31# prefix)

    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.fromParts("tel", "#31# + phoneNumber, null));
    startActivity(intent);

The 2nd method is straitful : the call starts, but your app requires permission

    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.fromParts("tel", phoneNumber, null));
    startActivity(intent);

and do not forget to add the permissin in the manisfest:

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

For practical use, the 1st way is the right one as NO permission is required, so it’s a little bit less intrusive and less dangerous (for user’s billing).

Android : Memo, Tips and Tricks


This post is just a memo, kind of PasteBin.

Load data (bytes or string) for a file into Resources (raw directory)

    /**
     * Load a binary file from Resources
     *
     * @param context Context
     * @param resId   Resource to load
     * @return File content (byte[]), null if a failure occurs
     */
    public static byte[] loadResRawFile(Context context, int resId) {
        try {
            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
            long length = afd.getLength();
            InputStream is = afd.createInputStream();
            byte[] buffer = new byte[(int) length];
            is.read(buffer);
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Load a String file from Resources
     *
     * @param ctx   Context
     * @param resId Resource to load
     * @return File content (String), null if a failure occurs
     */
    public static String loadResStringFile(Context ctx, int resId) {
        try {
            return new String(loadResRawFile(ctx, resId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }