问题
I am new in phonegap, just start learning it...
I made a demo application from the tutorials given on the phonegap.com, This is my index.html
<!DOCTYPE HTML>
<html>
<head>
<title>mobiletuts phonegap</title>
<script src="cordova-2.7.0.js"></script>
<script>
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
document.addEventListener("backbutton", function(e){
if($.mobile.activePage.is('index.html')){
e.preventDefault();
navigator.app.exitApp();
}
else {
navigator.app.backHistory()
}
}, false);
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onPhotoDataSuccess(imageData)
{
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoURISuccess(imageURI)
{
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
function capturePhoto()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function onSuccess(position)
{
var element = document.getElementById('geolocation');
element.innerHTML = '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 />';
}
function onError(error)
{
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function onLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function changeBG(){
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
document.bgColor = '#aaa';
}
function Alert()
{
alert('Ther alert dialog from the javascript method');
}
function onAlert()
{
AndroidFunction.showAlert();
}
</script>
</head>
<body>
<button onClick="capturePhoto();">Capture Photo</button> <br>
<button onClick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onClick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onClick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<button onClick="Alert();">Show Alert msg from javascript</button><br>
<button onClick="onAlert();">Show Alert msg from java</button><br>
<p id="geolocation">Finding geolocation...</p>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
It works properly, but now i want to control some functions from the java, so i made a webview in layout file, and make sone changes in java file, here is my java code...
public class MainActivity extends Activity {
WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(
this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
webView.loadUrl("file:///android_asset/www/index.html");
webView.setWebViewClient(new MyWebViewClient());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode != RESULT_CANCELED) {
if (requestCode == 33) {
/*
* Bitmap photo = (Bitmap) data.getExtras().get("data");
* imageView.setImageBitmap(photo);
*/
}
}
}
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void showAlert() {
webView.loadUrl("javascript:Alert()");
}
@JavascriptInterface
public void startNewActivity() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivity(intent);
}
}
class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost()
.equals("file:///android_asset/www/index.html")) {
// This is my web site, so do not override; let my WebView load
// the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
Now i want to call java methods from the javascript, so that i have add a button and two script methods in index.html, they are...
function Alert()
{
alert('Ther alert dialog from the javascript method');
}
function onAlert()
{
AndroidFunction.showAlert();
}
add a button to call onAlert() function, But when i run it on device, no button will work... I cant understand what is the issue, can anyone help me....
回答1:
In your case there is a need to Embedding Cordova WebView on Android here is link for it
Modify your main Activity as
public class MainActivity extends Activity implements CordovaInterface {
CordovaWebView cwv;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cwv = (CordovaWebView) findViewById(R.id.tutorialView);
cwv.loadUrl("file:///android_asset/www/index.html");
}
And in your layout replace your webview with
<org.apache.cordova.CordovaWebView
android:id="@+id/tutorialView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
回答2:
I've found the Cordova CLI to be pretty easy to get started with and you don't have to write any native code to get up and running.
There is some info here: http://www.gauntface.co.uk/blog/2013/07/18/cordova-web-best-practices/
Essentially the commands come down to:
Install the Cordova Command Line Interface using NPM
npm install -g cordova
Create a new Cordova project
cordova create <Project Directory> <Package Name> <Project Name>
Examples:
cordova create my-project co.uk.gauntface.myproject.cordova "My Project"
Add the Android platform to the project
cd my-project
cordova platform add android
Start Emulator: cordova emulate android
OR Run on a device:
cordova run android
来源:https://stackoverflow.com/questions/20299814/how-to-control-javascript-in-android-phonegap