您的位置:首页 > 移动开发

Andorid PhoneGap HelloWorld plugin

2013-12-03 15:36 357 查看
使用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="support@phonegap.com" 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

《完》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息