macdonst / TelephoneNumberPlugin

67 stars 41 forks source link

Fix for everyone to get phonenumber #14

Open tsukasa1989 opened 7 years ago

tsukasa1989 commented 7 years ago

I've solved it with help of a stackoverflow answer at this url: http://stackoverflow.com/questions/2480288/programmatically-obtain-the-phone-number-of-the-android-phone

If you want to get the phonenumber you have to replace the TelephoneNumber.java file with the one below.

package com.simonmacdonald.cordova.plugins;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;

import android.content.Context;
import android.telephony.TelephonyManager;

import android.util.Log;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;

public class TelephoneNumber extends CordovaPlugin {

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("get")) {
        TelephonyManager telephonyManager =
            (TelephonyManager)this.cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        String result = telephonyManager.getLine1Number();

        if (result != null && !result.equals("")) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
            return true;
        } else {
            String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
            Object object = this.cordova.getActivity().getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
                    main_data, "mimetype=?",
                    new String[]{"vnd.android.cursor.item/phone_v2"},
                    "is_primary DESC");
            if (object != null) {
                do {
                    if (!((Cursor) (object)).moveToNext())
                        break;

                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, ((Cursor) (object)).getString(4)));
                    return true;
                } while (true);
                ((Cursor) (object)).close();
            }
        }
    }
    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
    return false;
}
}

Next add the following 2 permissions to the plugin.xml:

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

Thats all! Now you will be able to get the phonenumber