如何使用适用于Android的Cordova CallLog插件获取呼叫日志历史记录 [英] How get call log history using Cordova CallLog plugin for Android

查看:59
本文介绍了如何使用适用于Android的Cordova CallLog插件获取呼叫日志历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目是我必须从电话获取呼叫记录历史记录并发送到服务器.我没有通过使用calllog插件获取呼叫记录历史记录,但是我是Cordova的新手,我不知道如何获取值在脚本文件中.任何人都可以帮助我..我已经在这里发布了代码.

My project is I have to get the calllog history from phone and send to the server.I don't get the calllog history by using calllog plugin, but I am new to cordova I don't know how to get the values in the script file.Can anybody pls help me..I have posted my code here.

我的CallLogPlugin.java文件

My CallLogPlugin.java file

public class CallLogPlugin extends CordovaPlugin {

private static final String ACTION_LIST = "list";
private static final String ACTION_CONTACT = "contact";
private static final String ACTION_SHOW = "show";
private static final String TAG = "CallLogPlugin";

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {

    Log.d(TAG, "Plugin Called");

    if (ACTION_CONTACT.equals(action)) {
        contact(args, callbackContext);
    } else if (ACTION_SHOW.equals(action)) {
        show(args, callbackContext);
    } else if (ACTION_LIST.equals(action)) {
        list(args, callbackContext);
    } else {
        Log.d(TAG, "Invalid action : " + action + " passed");
        callbackContext.sendPluginResult(new PluginResult(Status.INVALID_ACTION));
    }
    return true;
    }

    private void show(final JSONArray args, final CallbackContext callbackContext) {


    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            PluginResult result;
            try {
                String phoneNumber = args.getString(0);
                viewContact(phoneNumber);
                result = new PluginResult(Status.OK);
            } catch (JSONException e) {
                Log.d(TAG, "Got JSON Exception " + e.getMessage());
                result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            } catch (Exception e) {
                Log.d(TAG, "Got Exception " + e.getMessage());
                result = new PluginResult(Status.ERROR, e.getMessage());
            }
            callbackContext.sendPluginResult(result);
        }
     });
     }

     private void contact(final JSONArray args, final CallbackContext callbackContext) {

     cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            PluginResult result;
            try {
                final String phoneNumber = args.getString(0);
                String contactInfo = getContactNameFromNumber(phoneNumber);
                Log.d(TAG, "Returning " + contactInfo);
                result = new PluginResult(Status.OK, contactInfo);
            } catch (JSONException e) {
                Log.d(TAG, "Got JSON Exception " + e.getMessage());
                result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            }
            callbackContext.sendPluginResult(result);
        }
       });
       }

      private void list(final JSONArray args, final CallbackContext callbackContext) {

      cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            PluginResult result;
            try {

                String limiter = null;
                if (!args.isNull(0)) {
                    // make number positive in case caller give negative days
                    int days = Math.abs(Integer.valueOf(args.getString(0)));
                    Log.d(TAG, "Days is: " + days);
                    //turn this into a date
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());

                    calendar.add(Calendar.DAY_OF_YEAR, -days);
                    Date limitDate = calendar.getTime();
                    limiter = String.valueOf(limitDate.getTime());
                }

                //now do required search
                JSONObject callLog = getCallLog(limiter);
                Log.d(TAG, "Returning " + callLog.toString());
                result = new PluginResult(Status.OK, callLog);

            } catch (JSONException e) {
                Log.d(TAG, "Got JSON Exception " + e.getMessage());
                result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            } catch (NumberFormatException e) {
                Log.d(TAG, "Got NumberFormatException " + e.getMessage());
                result = new PluginResult(Status.ERROR, "Non integer passed to list");
            } catch (Exception e) {
                Log.d(TAG, "Got Exception " + e.getMessage());
                result = new PluginResult(Status.ERROR, e.getMessage());
            }
            callbackContext.sendPluginResult(result);
        }
    });
}

private void viewContact(String phoneNumber) {

    Intent i = new Intent(Intents.SHOW_OR_CREATE_CONTACT,
            Uri.parse(String.format("tel: %s", phoneNumber)));
    this.cordova.getActivity().startActivity(i);
}

private JSONObject getCallLog(String limiter) throws JSONException {

    JSONObject callLog = new JSONObject();

    String[] strFields = {
            android.provider.CallLog.Calls.DATE,
            android.provider.CallLog.Calls.NUMBER,
            android.provider.CallLog.Calls.TYPE,
            android.provider.CallLog.Calls.DURATION,
            android.provider.CallLog.Calls.NEW,
            android.provider.CallLog.Calls.CACHED_NAME,
            android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
            android.provider.CallLog.Calls.CACHED_NUMBER_LABEL };

    try {
        Cursor callLogCursor = this.cordova.getActivity().getContentResolver().query(
                android.provider.CallLog.Calls.CONTENT_URI,
                strFields,
                limiter == null ? null : android.provider.CallLog.Calls.DATE + ">?",
                limiter == null ? null : new String[] {limiter},
                android.provider.CallLog.Calls.DEFAULT_SORT_ORDER);

        int callCount = callLogCursor.getCount();

        if (callCount > 0) {
            JSONObject callLogItem = new JSONObject();
            JSONArray callLogItems = new JSONArray();

            callLogCursor.moveToFirst();
            do {
                callLogItem.put("date", callLogCursor.getLong(0));
                callLogItem.put("number", callLogCursor.getString(1));
                callLogItem.put("type", callLogCursor.getInt(2));
                callLogItem.put("duration", callLogCursor.getLong(3));
                callLogItem.put("new", callLogCursor.getInt(4));
                callLogItem.put("cachedName", callLogCursor.getString(5));
                callLogItem.put("cachedNumberType", callLogCursor.getInt(6));
                callLogItem.put("cachedNumberLabel", callLogCursor.getInt(7));
                //callLogItem.put("name", getContactNameFromNumber(callLogCursor.getString(1))); //grab name too
                callLogItems.put(callLogItem);
                callLogItem = new JSONObject();
            } while (callLogCursor.moveToNext());
            callLog.put("rows", callLogItems);
        }

        callLogCursor.close();
    } catch (Exception e) {
        Log.d("CallLog_Plugin", " ERROR : SQL to get cursor: ERROR " + e.getMessage());
    }

    return callLog;
}

private String getContactNameFromNumber(String number) {

    // define the columns I want the query to return
    String[] projection = new String[]{PhoneLookup.DISPLAY_NAME};

    // encode the phone number and build the filter URI
    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

    // query time
    Cursor c = this.cordova.getActivity().getContentResolver().query(contactUri, projection, null, null, null);

    // if the query returns 1 or more results
    // return the first result
    if (c.moveToFirst()) {
        String name = c.getString(c.getColumnIndex(PhoneLookup.DISPLAY_NAME));
        c.deactivate();
        return name;
    }
    // return the original number if no match was found
    return number;
  }
 }

我的CallLog.js文件

My CallLog.js file

    function CallLog() {
    }

    CallLog.prototype.list = function (period, successCallback, errorCallback) {
      cordova.exec(successCallback, errorCallback, "CallLog", "list", [period]);
    };

     CallLog.prototype.contact = 
     function (phoneNumber,  successCallback,errorCallback)           {
     cordova.exec(successCallback, errorCallback, "CallLog", "contact", [phoneNumber]);
      };

    CallLog.prototype.show = function (phoneNumber, successCallback, errorCallback) {
     cordova.exec(successCallback, errorCallback, "CallLog", "show", [phoneNumber]);
    };

    CallLog.install = function () {
    if (!window.plugins) {
     window.plugins = {};
    }

     window.plugins.calllog = new CallLog();
    return window.plugins.calllog;
     };

     cordova.addConstructor(CallLog.install);

我的index.js文件

My index.js file

    var app = {
  // Application Constructor
   initialize: function() {
    this.bindEvents();
   },
  // Bind Event Listeners
   //
  bindEvents: function() {
     document.addEventListener('deviceready', this.onDeviceReady, false);
  },


  onDeviceReady: function() {
     app.receivedEvent('deviceready');
    var f = window.plugins.calllog.list();
    alert(f);
  },
  // Update DOM on a Received Event
   receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
  }
  };

但是我没有任何结果.请帮助我.

But i don't get any result. Please help me.

谢谢

推荐答案

我并不是想解决所有问题,只是想提供一些启示. 您的Java看起来不错,但请检查 https://wiki.apache.org/cordova/DeprecationPolicy 并在下一个网址链接上查看针对此类弃用代码提供的解决方案.为您的Javascript.

I'm not trying to solve all your problem, just want to throw some light. Your Java seems fine, but check https://wiki.apache.org/cordova/DeprecationPolicy and see the solution offered for such deprecation code on the next url link. for your Javascript.

deprecation: window.addPlugin and window.plugins will be removed

http://simonmacdonald.blogspot.com.es/2012/08/so-you-wanna-write-phonegap-200-android.html

您的代码: window.plugins.calllog =新的CallLog(); 返回window.plugins.calllog;

Your Code: window.plugins.calllog = new CallLog(); return window.plugins.calllog;

提供的解决方案类似于:

The solution provided is something like:

    module.exports = new CallLog();

这篇关于如何使用适用于Android的Cordova CallLog插件获取呼叫日志历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆