I'm building a phonegap app for Android and need a way to set wallpapers from a .jpg included in the www directory of the app using javascript. How would I go about building a phonegap plugin that works with resources in my phonegap apps www folder?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
just read file from asset folder. with Plugin
import java.io.IOException; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult.Status; import org.json.JSONArray; import android.app.WallpaperManager; import android.content.Context; public class testPlugin extends Plugin { public final String ACTION_SET_WALLPAPER = "setWallPaper"; @Override public PluginResult execute(String action, JSONArray arg1, String callbackId) { PluginResult result = new PluginResult(Status.INVALID_ACTION); if (action.equals(ACTION_SET_WALLPAPER)) { WallpaperManager wallpaperManager = WallpaperManager.getInstance((Context) this.ctx); try { InputStream bitmap=null; bitmap=getAssets().open("www/img/" + arg1.getString(0));//reference to image folder Bitmap bit=BitmapFactory.decodeStream(bitmap); wallpaperManager.setBitmap(bit); result = new PluginResult(Status.OK); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); result = new PluginResult(Status.ERROR, e.getMessage()); } } return result; } }
this is javascript file test.js
var TestPlugin = function () {}; TestPlugin.prototype.set = function (ms, successCallback, failureCallback) { // navigator.notification.alert("OMG"); return cordova.exec(successCallback, failureCallback, 'testPlugin', "setWallPaper", [ms]); }; PhoneGap.addConstructor(function() { PhoneGap.addPlugin("test", new TestPlugin()); })
and main file call Plugin with imagefilename
window.plugins.test.set("imageFileName.jpg", function () { navigator.notification.alert("Set Success"); }, function (e) { navigator.notification.alert("Set Fail: " + e); } ); ;
with android device permission
<uses-permission android:name="android.permission.SET_WALLPAPER" />
and plugin.xml
<plugin name="testPlugin" value="com.android.test.testPlugin"/>