javascript - SmsInboxPlugin 总是失败

标签 javascript cordova cordova-plugins

我试图在我的应用程序中实现 SmsInboxPlugin,他们的以下示例代码总是提示错误:

  smsInboxPlugin.isSupported ((function(supported) {
    if(supported) 
      alert("SMS supported !");
    else
      alert("SMS not supported");
  }), function() {
    alert("Error while checking the SMS support");
  });

问题出在哪里?

Plugin at Githut

还有这个替代品Cordova-SMS-Reception-Plugin给出同样的错误。

最佳答案

创建下面给出的文件:-

Plugin.xml

<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="com.root.smsplugin"
    version="0.2.11">
    <name>SMSPlugin</name>
    <description>SMS Reading implemented</description>
    <license>Apache 2.0</license>
    <keywords>cordova,coolest</keywords>
    <repo></repo>
    <issue></issue>

    <js-module src="www/SMSPlugin.js" name="SMSPlugin">
        <clobbers target="SMSPlugin" />
    </js-module>

    <!-- android -->
    <platform name="android">
        <config-file target="res/xml/config.xml" parent="/*">
            <feature name="SMSPlugin" >
                <param name="android-package" value="SMSPlugin"/>
            </feature>
        </config-file>
        <source-file src="src/android/SMSPlugin.java" target-dir="src/com/root/smsplugin/" />

    <config-file target="AndroidManifest.xml" parent="/*">
            <uses-permission android:name="android.permission.RECEIVE_SMS" />
    </config-file>

    <config-file target="AndroidManifest.xml" parent="/manifest/application">
        <receiver android:name="com.root.smsplugin.SMSReceiver">
                    <intent-filter>
                        <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
                    </intent-filter>
            </receiver>
    </config-file>

    <source-file
        src="src/android/SMSReceiver.java"
        target-dir="src/com/root/smsplugin/" />
    </platform>
</plugin>

SMSPlugin.js

var exec = require('cordova/exec');

  var SMSPlugin = function() {};


  /**
   * Check if the device has a possibility to send and receive SMS
   */
  SMSPlugin.prototype.isSupported = function(successCallback,failureCallback) {
    return exec(successCallback, failureCallback, 'SMSPlugin', 'HasSMSPossibility', []);
  }

  SMSPlugin.prototype.startReception = function(successCallback,failureCallback) {
    return exec(successCallback, failureCallback, 'SMSPlugin', 'StartReception', []);
  }

  /**
   * Stop the receiving sms.
   */
  SMSPlugin.prototype.stopReception = function(successCallback,failureCallback) {
    return exec(successCallback, failureCallback, 'SMSPlugin', 'StopReception', []);
  }

  var SMSPlugin = new SMSPlugin();
  module.exports = SMSPlugin;
//});

SMSPlugin.java

import android.app.Activity;
import android.content.IntentFilter;
import android.content.pm.PackageManager;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import com.root.smsplugin.SMSReceiver;
/**
 * Created by root on 14/10/16.
 */
public class SMSPlugin extends CordovaPlugin {
    public final String ACTION_IS_SMS_POSSIBILITY = "HasSMSPossibility";
    public final String ACTION_START_RECEPTION_SMS = "StartReception";
    public final String ACTION_STOP_RECEPTION_SMS = "StopReception";

    private CallbackContext callback_receive;
    private SMSReceiver smsReceiver = null;
    private boolean isReceiving = false;

    public SMSPlugin() {
        super();
    }

    @Override
    public boolean execute(String action, JSONArray arg1,
                           final CallbackContext callbackContext) throws JSONException {

        if (action.equals(ACTION_IS_SMS_POSSIBILITY)) {

            Activity ctx = this.cordova.getActivity();
            if (ctx.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true));
            } else {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, false));
            }
            return true;
        } else if (action.equals(ACTION_START_RECEPTION_SMS)) {

            // if already receiving (this case can happen if the startReception is called
            // several times
            if (this.isReceiving) {
                // close the already opened callback ...
                PluginResult pluginResult = new PluginResult(
                        PluginResult.Status.NO_RESULT);
                pluginResult.setKeepCallback(false);
                this.callback_receive.sendPluginResult(pluginResult);

                // ... before registering a new one to the sms receiver
            }
            this.isReceiving = true;

            if (this.smsReceiver == null) {
                this.smsReceiver = new SMSReceiver();
                IntentFilter fp = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
                fp.setPriority(1000);
                // fp.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
                this.cordova.getActivity().registerReceiver(this.smsReceiver, fp);
            }

            this.smsReceiver.startReceiving(callbackContext);

            PluginResult pluginResult = new PluginResult(
                    PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
            this.callback_receive = callbackContext;

            return true;
        } else if (action.equals(ACTION_STOP_RECEPTION_SMS)) {

            if (this.smsReceiver != null) {
                smsReceiver.stopReceiving();
            }

            this.isReceiving = false;

            // 1. Stop the receiving context
            PluginResult pluginResult = new PluginResult(
                    PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(false);
            this.callback_receive.sendPluginResult(pluginResult);

            // 2. Send result for the current context
            pluginResult = new PluginResult(
                    PluginResult.Status.OK);
            callbackContext.sendPluginResult(pluginResult);

            return true;
        }

        return false;
    }
}

SMSReciever.java

package com.root.smsplugin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;

/**
 * Created by root on 14/10/16.
 */
public class SMSReceiver extends BroadcastReceiver {


    public static final String SMS_EXTRA_NAME = "pdus";
    private CallbackContext callback_receive;
    private boolean isReceiving = true;

    // This broadcast boolean is used to continue or not the message broadcast
    // to the other BroadcastReceivers waiting for an incoming SMS (like the native SMS app)
    private boolean broadcast = false;

    @Override
    public void onReceive(Context ctx, Intent intent) {

        // Get the SMS map from Intent
        Bundle extras = intent.getExtras();
        if (extras != null)
        {
            // Get received SMS Array
            Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);

            for (int i=0; i < smsExtra.length; i++)
            {
                SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
                if(this.isReceiving && this.callback_receive != null) {
                    String formattedMsg = sms.getMessageBody();
                    PluginResult result = new PluginResult(PluginResult.Status.OK, formattedMsg);
                    result.setKeepCallback(true);
                    callback_receive.sendPluginResult(result);
                }
            }

            // If the plugin is active and we don't want to broadcast to other receivers
            if (this.isReceiving && !broadcast) {
                this.abortBroadcast();
            }
        }
    }

    public void broadcast(boolean v) {
        this.broadcast = v;
    }

    public void startReceiving(CallbackContext ctx) {
        this.callback_receive = ctx;
        this.isReceiving = true;
    }

    public void stopReceiving() {
        this.callback_receive = null;
        this.isReceiving = false;
    }
}

按照 Create own custom Cordova Plugin. 中给出的程序进行操作仅引用创建目录结构。

然后像下面这样调用插件:-

SMSPlugin.startReception (function(msg) {
    alert(msg);
  }, function() {
    alert("Error while receiving messages");
  });

对我来说效果很好,希望对你也有帮助

关于javascript - SmsInboxPlugin 总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882302/

相关文章:

facebook-javascript-sdk - Cordova插件facebook4,如何使用?

ios - Firebase 通知不在前台,但在 iOS Ionic 2 应用程序中为后台工作

javascript - [attribute != "value"] 是否存在于 CSS 中的任何位置,还是我刚刚编造的?

javascript - 如何在 html 或 css 中禁用选择时的突出显示 View ?

android - 从外部页面调用 phonegap API

javascript - PhoneGap/ Cordova 2.3。 : how to open all external links in InAppBrowser?

javascript - Cordova 文件传输 |如何将标题中的字符串放入 TargetPath?

javascript - 如何在 Typescript 中序列化/反序列化复杂对象,例如反序列化对象与序列化对象的类型相同

javascript - 发送有关丢失互联网连接的 Google Analytics 事件

javascript - angularjs - 指令中的动态回调