Andorid PhoneGap HelloWorld plugin

使用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 參考http://docs.phonegap.com/en/3.2.0/guide_platforms_android_plugin.md.html#Android%20Plugins

代碼:

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

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets"
        xmlns:gap="http://phonegap.com/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.w3.org/ns/widgets ">
    <name>Hello Cordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <access origin="*"/>
    <content src="index.html"/>
    <preference name="loglevel" value="DEBUG"/>
    <feature name="App">
        <param name="android-package" value="org.apache.cordova.App"/>
    </feature>

    <feature name="Echo">
        <param name="android-package" value="com.bbcvision.multiscreen.plugin.Echo"/>
    </feature>

    <name>HelloWorld</name>
    <description>
        Hello World sample application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="http://phonegap.com">
        PhoneGap Team
    </author>
    <feature name="http://api.phonegap.com/1.0/device"/>

    <preference name="permissions" value="none"/>
    <preference name="orientation" value="default"/>
    <preference name="target-device" value="universal"/>
    <preference name="fullscreen" value="true"/>
    <preference name="webviewbounce" value="true"/>
    <preference name="prerendered-icon" value="true"/>
    <preference name="stay-in-webview" value="false"/>
    <preference name="ios-statusbarstyle" value="black-opaque"/>
    <preference name="detect-data-types" value="true"/>
    <preference name="exit-on-suspend" value="false"/>
    <preference name="show-splash-screen-spinner" value="true"/>
    <preference name="auto-hide-splash-screen" value="true"/>
    <preference name="disable-cursor" value="false"/>
    <preference name="android-minSdkVersion" value="7"/>
    <preference name="android-installLocation" value="auto"/>
    <icon src="icon.png"/>
    <icon gap:density="ldpi" gap:platform="android" src="res/icon/android/icon-36-ldpi.png"/>
    <icon gap:density="mdpi" gap:platform="android" src="res/icon/android/icon-48-mdpi.png"/>
    <icon gap:density="hdpi" gap:platform="android" src="res/icon/android/icon-72-hdpi.png"/>
    <icon gap:density="xhdpi" gap:platform="android" src="res/icon/android/icon-96-xhdpi.png"/>
    <icon gap:platform="blackberry" src="res/icon/blackberry/icon-80.png"/>
    <icon gap:platform="blackberry" gap:state="hover" src="res/icon/blackberry/icon-80.png"/>

    <icon gap:platform="winphone" src="res/icon/windows-phone/icon-48.png"/>
    <icon gap:platform="winphone" gap:role="background" src="res/icon/windows-phone/icon-173.png"/>
    <gap:splash gap:density="ldpi" gap:platform="android"
                src="res/screen/android/screen-ldpi-portrait.png"/>
    <gap:splash gap:density="mdpi" gap:platform="android"
                src="res/screen/android/screen-mdpi-portrait.png"/>
    <gap:splash gap:density="hdpi" gap:platform="android"
                src="res/screen/android/screen-hdpi-portrait.png"/>
    <gap:splash gap:density="xhdpi" gap:platform="android"
                src="res/screen/android/screen-xhdpi-portrait.png"/>

    <access origin="http://127.0.0.1*"/>
</widget>
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

<!DOCTYPE html>
<html>
<head>
    <title>JS-Native Hello World</title>
    <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>

</head>
<body>
<input type="button" value="Say GAP hello" onClick="app.addToCal()" />
</body>
</html>

3 開始寫Android的activity類

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >

    <org.apache.cordova.CordovaWebView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            ></org.apache.cordova.CordovaWebView>
    <Button
            android:id="@+id/load"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Load URL"
            ></Button>
</LinearLayout>

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

《完》



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章