美轮美奂的phonegap(八)---写phonegap插件实现本地的代码

phonegap可以通过继承CordovaPlugin来实现一些本地代码完成的事件,比如发短信,打电话等,整理于网络

关于打电话和发短信参考:http://blog.csdn.net/hotphen/article/details/8660441

官方文档插件开发:http://docs.phonegap.com/en/2.5.0/guide_plugin-development_index.md.html#Plugin%20Development%20Guide

还有很多实现插件:http://download.csdn.net/detail/senssic/7387603

1.编写java类继承CordovaPlugin

2.在xml文件夹下的config.xml中config.xml中注册插件

3.页面使用js调用

一,PhoneGap插件js 发送短信

java类:

package com.example.phonegap;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.telephony.SmsManager;

public class Message extends CordovaPlugin {
    
    private static final String SEND = "send";
    
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        System.out.println("SnedAction");
        if (SEND.equals(action)) {
            try {
                JSONObject jsonObj = new JSONObject();
                String target = args.getString(0);
                String content = args.getString(1);
                SmsManager sms = SmsManager.getDefault();
                sms.sendTextMessage(target, null, content, null, null);
                jsonObj.put("target", target);
                jsonObj.put("content", content);
                this.echo("SUCC", callbackContext);
                return true;
            } catch (JSONException ex) {
                this.echo("FAIL", callbackContext);
                return false;
            }catch(IllegalArgumentException ex){
                this.echo("FAIL", callbackContext);
                return false;
            }
        } else {
            this.echo("FAIL", callbackContext);
            return false;
        }

    }
    
     private void echo(String message, CallbackContext callbackContext) {
            if (message != null && message.length() > 0) { 
                callbackContext.success(message);
            } else {
                callbackContext.error("Expected one non-empty string argument.");
            }
        }

}

config.xml配置

<feature name="Message">
      <param name="android-package" value="com.example.phonegap.Message"/>
   </feature>

js端调用:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8" src="../js/jquery.min.js"></script>
 <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/phonegapPlugin.js"></script>
<script type="text/javascript">
    $(function(){
        var onSend = function(){
            var success = function(data){
                alert("tel : " + data.target + ', and content : ' + data.content);
            };
            var error = function(e){
                alert(e);
            };
            var tel = $('#tel').val();
            var content = $('#content').val();
            window.send(success, error, tel, content);
        };
        $('#send').bind('click', onSend);
    });
</script>
</head>
<body>
    <div id="messageDiv">
        <input type="tel" id="tel" value="5554" />
        <textarea rows="20" cols="25" id="content"></textarea>
        <button type="button" id="send">Send Me</button>
        <p><a href="index.html">返回</a>
    </div>
</body>
</html>

2.PhoneGap插件js 打电话 

java代码:

package com.example.phonegap;

import java.util.Date;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog.Calls;
import android.telephony.PhoneNumberUtils;

public class Phone extends CordovaPlugin {
    
    private static final int PHONE_CALL = 0;     // 拨打电话
    private Date start_time;
    private CallbackContext callbackContext;   
    private String phonenumber;
    
    @Override
    public boolean  execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        try{

        this.callbackContext = callbackContext;
        
        if ("call".equals(action)) {
            this.phonenumber=args.getString(0);
            this.call(args.getString(0),callbackContext);
            return true;
        }
        if ("abort".equals(action)) {
           this.abort(callbackContext);
            return true;
        }
        return false;
        }
        catch(Exception e){
            callbackContext.error(e.getMessage());
        }
        return false;
    }
    //拨打电话
    private  void call(String phonenumber, CallbackContext callbackContext) {

        if (phonenumber != null && phonenumber.length() > 0) { 
            
            if(PhoneNumberUtils.isGlobalPhoneNumber(phonenumber)){
             Intent i = new Intent();  
             i.setAction(Intent.ACTION_CALL); 
             i.setData(Uri.parse("tel:"+phonenumber));   
             start_time=new Date();
             this.cordova.startActivityForResult(this, i,PHONE_CALL);
             
            }
            else{
                callbackContext.error(phonenumber+"不是有效的电话号码。");
            }  
        } else {
            callbackContext.error("电话号码不能为空.");
        }
    }
    //中断电话
    private void abort(CallbackContext callbackContext) {

    }
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Date end_time=new Date();
        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == PHONE_CALL) {

                this.callbackContext.error("未知状态");
            } 
        }
        else if (resultCode == Activity.RESULT_CANCELED) {
            try{
                if (requestCode == PHONE_CALL) {
                long duration=GetLastCallDuration();
                    
                        PhoneResult result=new PhoneResult();

                        result.setNumber(Phone.this.phonenumber);
                        result.setStartTime(Phone.this.start_time);
                        result.setEndTime(end_time);
                        result.setDuration(duration);
                        this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
                        
                    } 
            }
            catch(Exception e){
                this.callbackContext.error(e.getMessage());
            }
    }

    else {
        this.callbackContext.error("其他错误!");
         
    }
    }
    long delayTime=0;
    long timeOut=2000;
    long GetLastCallDuration() throws InterruptedException{
        Activity activity = this.cordova.getActivity();
        Cursor cursor = activity.getContentResolver().query(Calls.CONTENT_URI, 
                new String[] {Calls.NUMBER,Calls.DATE, Calls.DURATION, Calls.TYPE, Calls.DATE }, 
                "number=?and type=?", 
                new String[]{this.phonenumber,"2"}, 
                Calls.DEFAULT_SORT_ORDER);
        activity.startManagingCursor(cursor);
        boolean hasRecord = cursor.moveToFirst();
        if (hasRecord) { 
            long endTime=cursor.getLong(cursor.getColumnIndex(Calls.DATE));
            Date date = new Date(endTime);
            long duration = cursor.getLong(cursor.getColumnIndex(Calls.DURATION));
            long dif=this.start_time.getTime()-date.getTime();
            long second=dif/1000;
            if(second<2&&second>-2){
                return duration;
            }else{
                if(delayTime>=timeOut){
                    return 0;
                }
                Thread.sleep(200);
                delayTime+=200;
                return GetLastCallDuration();
            }
        }else{
            if(delayTime>=timeOut){
                return 0;
            }
            Thread.sleep(200);
            delayTime+=200;
            return GetLastCallDuration();
        }
    }

}

config.xml配置:

<feature name="Phone">    
        <param name="android-package" value="com.example.phonegap.Phone" />
    </feature>

js端调用:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8" src="../js/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/phone.js"></script>

<script type="text/javascript">

$(function(){
    var onSend = function(){
        
        var tel = $('#tel').val();
        window.Phone.call(function (obj) { alert(JSON.stringify(obj));

        }, function (err) { alert(err); }, tel);
    };
    $('#call').bind('click', onSend);
});


</script>
</head>
<body>
    <div id="messageDiv">
        <input type="tel" id="tel" value="5554" />
        <button type="button" id="call">Call</button>
        <p><a href="index.html">返回</a>
    </div>
</body>
</html>

3.使用phonegap获取gps信息

<!DOCTYPE html>
<html>
<head>	
<title>PhoneGap Device Ready Example</title> 

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script> 
<script type="text/javascript" charset="utf-8"> 
//GPS
    document.addEventListener("deviceready", onDeviceReady, false); 
    function findGps(){
        var element = document.getElementById('geolocation');
        element.innerHTML = "<font color='red'>正在定位...</font>";
        document.addEventListener("deviceready", onDeviceReady, false);  
    }
       
    
    function onDeviceReady() {       
         findGps();
      //这东西,Android2.2+需要设置这东西 
        navigator.geolocation.getCurrentPosition(onSuccess, onError,{enableHighAccuracy: true });   
        //可设置定位超时
        //navigator.geolocation.getCurrentPosition(onSuccess, onError,{ maximumAge: 300000, timeout: 500000, enableHighAccuracy: true });
        }    
    
    function onSuccess(position) {        
        var element = document.getElementById('geolocation');        
        element.innerHTML = '<font color="red">Latitude: '           
        + position.coords.latitude              + '<br />' 
        +                            'Longitude: '          
        + position.coords.longitude             + '<br />'
        +                            'Altitude: '           
        + position.coords.altitude              + '<br />' 
        +                            'Accuracy: '           
        + position.coords.accuracy              + '<br />' 
        +                            'Altitude Accuracy: '  
        + position.coords.altitudeAccuracy      + '<br />' 
        +                            'Heading: '            
        + position.coords.heading               + '<br />' 
        +                            'Speed: '              
        + position.coords.speed                 + '<br />' 
        +                            'Timestamp: '          
        + position.timestamp                    + '<br /></font>'                        
        ;   
        var point = new BMap.Point(position.coords.latitude, position.coords.longitude);  
        map.addOverlay(new BMap.Marker(point));
        map.centerAndZoom(point, 15);                 
    }    
    // onError Callback receives a PositionError object    //    
    function onError(error) {        
        alert('错误: '    
                + error.code    + '\n' 
                +              '信息:: ' 
                + error.message + '\n'); 
        var element = document.getElementById('geolocation');
        element.innerHTML = "<font color='red'>超时无法获取位置</font>";
    }
    
</script>
</head>
<body>
   <div id="geolocation"></div>
</body>
</html>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值