[转]PhoneGap使用CordovaWebView时注意事项

在使用PhoneGap的CordovaWebView做界面渲染的时候使用插件的时候报这么一个异常

E/AndroidRuntime(543): java.lang.NullPointerException
10-31 13:02:16.075: E/AndroidRuntime(543):  at org.apache.cordova.api.Plugin.execute(Plugin.java:74)
10-31 13:02:16.075: E/AndroidRuntime(543):  at org.apache.cordova.api.CordovaPlugin.execute(CordovaPlugin.java:61)
10-31 13:02:16.075: E/AndroidRuntime(543):  at org.apache.cordova.api.PluginManager.exec(PluginManager.java:224)

从异常情况来看异常产生在插件这块。根据官方文档描述来看,使用CordovaWebView方式时,需要继承Activiti并实现org.apache.cordova.api.CordovaInterface接口。并实现以下三个方法,否则会报空指针异常

 

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

@Override
public Context getContext() {
	return this.getContext();
}

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

这里需要注意的是public ExecutorService getThreadPool()这个方法。该方法实际上是

private final ExecutorService threadPool =Executors.newCachedThreadPool();

若不实现该方法那么在使用插件的时候会报如上文所示的异常

http://stackoverflow.com/questions/13194537/android-phonegap-2-1-2-2-upgrade-error

完整的代码如下

package com.demo1;

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

import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class Demo1Activity extends Activity implements CordovaInterface {

	CordovaWebView cordovaWebView;

	private final ExecutorService threadPool = Executors.newCachedThreadPool();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		cordovaWebView = (CordovaWebView) findViewById(R.id.tutorialView);

		cordovaWebView.loadUrl("file:///android_asset/www/index.html");
	}

	@Override
	public void cancelLoadUrl() {

	}

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

	@Override
	public Context getContext() {
		return this.getContext();
	}

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

	@Override
	public Object onMessage(String string, Object object) {
		return null;
	}

	@Override
	public void setActivityResultCallback(CordovaPlugin cordovaPlugin) {

	}

	@Override
	public void startActivityForResult(CordovaPlugin plugin, Intent intent,
			int i) {

	}
}

最后上一个模拟器上的效果图:

 

赞 (0)
分享到:更多 ()