好吧我試圖實現一個手機差距插件,它由兩部分組成。我正在使用cordova 2.0.0和eclipse。如何在javascript中調用手機插件
這裏是java部分:
package org.apache.cordova;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import android.graphics.Bitmap;
import android.os.Environment;
import android.view.View;
public class Screenshot extends Plugin {
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
// starting on ICS, some WebView methods
// can only be called on UI threads
final Plugin that = this;
final String id = callbackId;
super.cordova.getActivity().runOnUiThread(new Runnable() {
//@Override
public void run() {
View view = webView.getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
try {
File folder = new File(Environment.getExternalStorageDirectory(), "Pictures");
if (!folder.exists()) {
folder.mkdirs();
}
File f = new File(folder, "screenshot_" + System.currentTimeMillis() + ".png");
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
that.success(new PluginResult(PluginResult.Status.OK), id);
} catch (IOException e) {
that.success(new PluginResult(PluginResult.Status.IO_EXCEPTION, e.getMessage()), id);
}
}
});
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
return result;
}
}
這裏是JavaScript的一部分:
cordova.define("cordova/plugin/screenshot", function(require, exports, module) {
var exec = require('cordova/exec');
/**
* This class exposes the ability to take a Screenshot to JavaScript
*/
var Screenshot = function() {};
/**
* Save the screenshot to the user's Photo Library
*/
Screenshot.prototype.saveScreenshot = function() {
exec(null, null, "Screenshot", "saveScreenshot", []);
};
var screenshot = new Screenshot();
module.exports = screenshot;
});
if (!window.plugins) {
window.plugins = {};
}
if (!window.plugins.screenshot) {
window.plugins.screenshot = cordova.require("cordova/plugin/screenshot");
}
我試圖與另一頁面上的其他javascript函數調用此方法,但都沒有成功。我隱藏在畫布上的圖像的錨,那麼這行:
setTimeout(takeScreenShot,500);
編輯 - 西蒙·麥克唐納的答案後做出 這就涉及到一個JavaScript函數:
function takeScreenShot() {
window.plugins.screenshot.saveScreenshot();
}
以下java的打印:
System.out.println(folder);
System.out.println("screenshot_" + System.currentTimeMillis() + ".png");
產生以下結果:
/mdt/sdcard/Pictures
screenshot_1347893081276.png
編輯再次關閉並打開設備後,我把出現的截屏,手機似乎對它們進行緩存,並沒有真正將它們存儲到所選文件夾。
我確保我的config.xml和我的android清單具有正確的權限和代碼行。任何人都可以看到我的錯在哪裏
我實現了這個功能,並且在screenshot.java文件中添加了一些日誌消息,並且它完全按照你的說法輸出。的System.out.println(文件夾); =/mnt/sdcard/Pictures和System.out.println(「screenshot_」+ System.currentTimeMillis()+「.png」); = screenshot_1347892058037.png。我沒有收到任何錯誤,但它實際上並未將圖像保存到該目錄或任何目錄。有任何想法嗎? – Bohdi
確保你的應用程序有權寫入外部存儲 –
我解決了這個問題,把它變成了base64,因爲我不想將它保存到手機。然而,手機緩存圖像似乎並沒有問題,也沒有將它們存儲到圖庫中。我確實有寫入外部存儲權限。 – Bohdi