Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Andorid PhoneGap HelloWorld plugin

Andorid PhoneGap HelloWorld plugin

編輯:關於Android編程

使用phonegap進行js(web)-native-server模型的混合應用(hybird)的開發,最主要的就是一個Plugin的開發

1.安裝phonegap

1.1 先安裝node.js

參考:http://nodejs.org/

1.2安裝phonegap

參考:http://phonegap.com/install/

得等好一會的時間

2.創建一個phonegap應用,查看目錄結構

在裡面有 platforms/目錄下面是具體的平台代碼目錄結構,導入到IDEA中進行編輯

2.1創建Echo plugin 

代碼:

 

package com.bbcvision.multiscreen.plugin;

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

/**
 * Created with IntelliJ IDEA.
 * User: bbcv
 * Date: 13-12-3
 * Time: AM 10:36
 */
public class Echo extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals(echo)) {
            String message = args.getString(0);
            this.echo(message, callbackContext);
            return true;
        }
        return false;
    }

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

 

在res/xml/中有個confi.xml配置文件,在這個配置文件中增加plugin

 



    Hello Cordova
    
        A sample Apache Cordova application that responds to the deviceready event.
    
    
    
    
    
    

    
    

    HelloWorld
    
        Hello World sample application that responds to the deviceready event.
    
    
        PhoneGap Team
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    
    

    

2.3編寫js代碼(橋梁)

 

在assert/www/js/ 目錄中創建echo.js 內容如下:

 

var echoPlugin =
    { createEvent: function(title, location, notes, startDate, endDate, successCallback, errorCallback)
        {
            cordova.exec(
                successCallback, // success callback function
                errorCallback, // error callback function
                'Echo', // mapped to our native Java class called CalendarPlugin
                'echo', // with this action name
                [{                  // and this array of custom arguments to create our entry
                    title: title,
                    description: notes,
                    eventLocation: location,
                    startTimeMillis: startDate.getTime(),
                    endTimeMillis: endDate.getTime()
                }]
            );

        }
    }

2.4 在index.js裡面增加與Java的通訊代碼如下:

 

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * License); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    addToCal: function() {
        var startDate = new Date(July 19, 2013 8:00:00);
        var endDate = new Date(July 19, 2013 18:00:00);
        var notes = Arrive on time, don't want to miss out (from Android);
        var title = PhoneGap Day;
        var location = Portland, OR;
        var notes = Arrive on time, don't want to miss out!;
        var success = function(message) { alert(Success: + message); };
        var error = function(message) { alert(Oopsie!  + message); };
        echoPlugin.createEvent(title, location, notes, startDate, endDate, success, error);
    },
    // 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);
    }
};

2.5 寫界面html:assert/www/ 目錄下面的hello.html

 

 



<script type=text/javascript src=phonegap.js></script><script type=text/javascript src=js/index.js></script><script type=text/javascript src=js/echo.js></script><script type=text/javascript>
        app.initialize();
    </script>
3 開始寫Android的activity類

 

3.1 使用PhoneGap的WebView來進行界面定制 參考:http://docs.phonegap.com/en/3.2.0/guide_platforms_android_webview.md.html#Android%20WebViews

本文使用的界面是布局如下:(注意,可以不用從新到入lib包)

 




    


 

3.2 寫Activity代碼(全部參考別人的)

 

package com.bbcvision.multiscreen;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import roboguice.activity.RoboActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Date: 13-12-2
 * Time: PM 4:24
 */
@ContentView(R.layout.phonegap1)
public class HelloPhoneGap2 extends RoboActivity implements CordovaInterface {
    private final ExecutorService threadPool = Executors.newCachedThreadPool();
    private CordovaPlugin activityResultCallback;
    private boolean activityResultKeepRunning;
    private boolean keepRunning;
    @InjectView(R.id.content)
    private CordovaWebView mWebView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWebView.loadUrl(file:///android_asset/www/hello.html);
    }

    @Override
    public void setActivityResultCallback(CordovaPlugin plugin) {
        this.activityResultCallback = plugin;
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public Object onMessage(String s, Object o) {
        return null;
    }

    @Override
    public ExecutorService getThreadPool() {
        return threadPool;
    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (this.activityResultCallback != null) {
            String cClass = this.activityResultCallback.getClass().getName();
            outState.putString(callbackClass, cClass);
        }
    }

    /**
     * Launch an activity for which you would like a result when it finished. When this activity exits,
     * your onActivityResult() method will be called.
     *
     * @param command     The command object
     * @param intent      The intent to start
     * @param requestCode The request code that is passed to callback to identify the activity
     */
    public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
        this.activityResultCallback = command;
        this.activityResultKeepRunning = this.keepRunning;

        // If multitasking turned on, then disable it for activities that return results
        if (command != null) {
            this.keepRunning = false;
        }

        // Start activity
        super.startActivityForResult(intent, requestCode);
    }
}

注意本文中使用了roboguice進行注入管理。

 

運行就可以看當了~

作為筆記

參考:http://bbs.9ria.com/thread-231696-1-1.html

《完》

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved