Phonegap setting wallpaper from www assets? Android - android

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?

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"/>

Related

React Native: Crop image on Android

The following function works on iOS, but doesn't work on Android. I want to achieve the same result on both platforms.
Based on this official documentation, the reason is missing ImageStore in react-native package for Android.
import {
ImageEditor,
ImageStore
} from 'react-native';
What would be an alternative way to crop images (as square) in react-native for Android?
cropImage(base64ImageData) {
return new Promise((resolve, reject)=>{
ImageStore.addImageFromBase64(
base64ImageData,
(photoURI)=>{
ImageEditor.cropImage(
photoURI,
{offset:{x:0,y:(1920-1080)/2},size:{width:1080, height:1080}},
(croppedURI)=>{
ImageStore.getBase64ForTag(
croppedURI,
(base64CroppedData)=>{
ImageStore.removeImageForTag(croppedURI);
resolve(base64CroppedData);
},
(err)=>{
reject(err);
}
);
ImageStore.removeImageForTag(photoURI);
},
(err)=>{
reject(err);
}
);
},
(err)=>{
reject(err);
}
);
});
}
Update:
There is a project https://github.com/seancunningham/react-native-image-store-ext (last commit Oct 28, 2016), but it only implements:
Boolean removeImageForTag(String file_uri)
The rest is missing:
static addImageFromBase64(base64ImageData, success, failure)
My preliminary solution:
private static final String IMAGE_STORAGE_URL_SCHEME = "rct-image-store";
#ReactMethod
public void addImageFromBase64(String base64_image_data, Callback successCallback, Callback failureCallback){
String imageStorageDir = this.reactContext.getApplicationContext().getFilesDir()+"/"+IMAGE_STORAGE_URL_SCHEME+"/";
byte[] buffer = new byte[BUFFER_SIZE];
String file_uri = imageStorageDir+"1";
try {
File f = new File(imageStorageDir);
if(!f.exists()) {
f.mkdir();
}
FileOutputStream fos = new FileOutputStream(file_uri, false);
byte[] decodedImage = Base64.decode(base64_image_data, Base64.DEFAULT);
fos.write(decodedImage);
fos.close();
successCallback.invoke("file://"+file_uri);
} catch (IOException ioe) {
failureCallback.invoke("Failed to add image from base64String"+ioe.getMessage());
} catch (Exception e) {
failureCallback.invoke("Failed to add image from base64String"+e.getMessage());
}
}
static getBase64ForTag(uri, success, failure)
Implemented in this file ImageStorageManager.java
static hasImageForTag(uri, callback)
The issue must be the sum of the offset + size be more then the height accepted, try it:
{offset:{x:0,y:(1920-1080)/2},size:{width:1080, height:1080 - (1920-1080)/2)}},
See if it works, if it does, just try to resize your size.height and see what works for you! :)

NanoHTTPD server on desktop

I'm trying to serve a small file on my desktop using NanoHTTPD. The server starts fine but due to some unknown reason, it is unable to serve files. The same program works fine in Android. Can anyone give me some pointers? It's being more than an hour but I've got no clue. Here is my desktop version of NanoHTTPD server:
package com.desktopserver;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.util.Map;
import com.desktopserver.NanoHTTPD.Response.Status;
public class MainClass {
static int PORT = 8080;
static WebServer MyServer;
static FileInputStream fis;
static BufferedInputStream bis;
public static void main(String[] args) {
MyServer = new WebServer();
try {
MyServer.start();
System.out.println("Webserver Started # PORT:8080");
} catch (IOException e) {
e.printStackTrace();
}
}
public static class WebServer extends NanoHTTPD {
String MIME_TYPE;
public WebServer() {
super(PORT);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
try {
File file=new File("/home/evinish/Music/Meant_to_live.mp3");
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
MIME_TYPE= URLConnection.guessContentTypeFromName(file.getName());
System.out.println("\nMIME TYPE: "+MIME_TYPE);
System.out.println("\nFILE NAME: "+file.getName());
} catch (IOException ioe) {
System.out.println("File IO Exception");
}
return new NanoHTTPD.Response(Status.OK, MIME_TYPE, bis);
}
}
}
I do get this output, but that's it:
Webserver Started # PORT:8080
What am I missing here? Thanks a lot for your help.
Because you don't use "ServerRunner" class. ServerRunner hold you server to until any key press.
But in real application this don't work you want some change in NanoHTTPd file
line no 196 to
myThread.setDaemon(false);

Android saving logs on every run for crash report [duplicate]

This question already has answers here:
How do I obtain crash-data from my Android application?
(30 answers)
Closed 5 months ago.
I'm currently developing an android app. I noticed a very rare error which leeds to a crash of my app. Unfortunately, I had my smartphone never connected to my pc when it occured. So, is there a way to automatically save all logs (and especially the thrown runtimeexceptions) to a file when my app starts, so that I can copy this file to my pc and analyse the error? The file should be overwritten on every start of my app, so that it contains only the logs of the last run... How can I achieve that?
regards
You can find help by following this link Writing crash reports into device sd card
You don't need to add external library.
import com.wordpress.doandroid.Training.R;
import android.app.Activity;
import android.os.Bundle;
public class CaptureExceptionActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets the default uncaught exception handler. This handler is invoked
// in case any Thread dies due to an unhandled exception.
Thread.setDefaultUncaughtExceptionHandler(new CustomizedExceptionHandler(
"/mnt/sdcard/"));
String nullString = null;
System.out.println(nullString.toString());
setContentView(R.layout.main);
}
}
And the Handler implementation
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Environment;
import android.util.Log;
public class CustomizedExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
private String localPath;
public CustomizedExceptionHandler(String localPath) {
this.localPath = localPath;
//Getting the the default exception handler
//that's executed when uncaught exception terminates a thread
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void uncaughtException(Thread t, Throwable e) {
//Write a printable representation of this Throwable
//The StringWriter gives the lock used to synchronize access to this writer.
final Writer stringBuffSync = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringBuffSync);
e.printStackTrace(printWriter);
String stacktrace = stringBuffSync.toString();
printWriter.close();
if (localPath != null) {
writeToFile(stacktrace);
}
//Used only to prevent from any code getting executed.
// Not needed in this example
defaultUEH.uncaughtException(t, e);
}
private void writeToFile(String currentStacktrace) {
try {
//Gets the Android external storage directory & Create new folder Crash_Reports
File dir = new File(Environment.getExternalStorageDirectory(),
"Crash_Reports");
if (!dir.exists()) {
dir.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
String filename = dateFormat.format(date) + ".STACKTRACE";
// Write the file into the folder
File reportFile = new File(dir, filename);
FileWriter fileWriter = new FileWriter(reportFile);
fileWriter.append(currentStacktrace);
fileWriter.flush();
fileWriter.close();
} catch (Exception e) {
Log.e("ExceptionHandler", e.getMessage());
}
}
}
Don't forget to add this permission in the manifest WRITE_EXTERNAL_STORAGE

Jar not found error in Android

In the following code below i have importted the jsch jar by clicking on Project properties and by adding the "add external jar button" also have added into the ant global path from the following link Add external jar but when i run the program i still get the "java.lang.NoClassDefFoundError: com.jcraft.jsch.JSch"
package android_jsch.com;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import com.jcraft.jsch.*;
import android.os.Bundle;
import android.widget.EditText;
public class Android_jschActivity extends Activity {
EditText ip,username,password;
#Override
public void onCreate(Bundle savedInstanceState) {
List<String> commands = new ArrayList<String>();
commands.add("touch /tmp/test1.txt");
commands.add("touch /tmp/test2.txt");
commands.add("touch /tmp/test3.txt");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rd);
try {
JSch jsch = new JSch();
session.connect();
Channel channel=session.openChannel("shell");//only shell
channel.setOutputStream(System.out);
PrintStream shellStream = new PrintStream(channel.getOutputStream()); // printStream for convenience
channel.connect();
for(String command: commands) {
shellStream.println(command);
shellStream.flush();
}
Thread.sleep(5000);
channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.err.println("ERROR: Connecting via shell to "+ip.getText().toString());
e.printStackTrace();
}
}
private static void setUpHostKey(Session session) {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
}
}
You should specify that the jar must be exported when building apk: in "Java Build Path" > "Order and Export" tab, fill the checkbox corresponding to your jar.

Implementation of WebDAV client on android

I am using jakarta/slide project for implementing webDAV client on my android device.
I got the all necessary jar files into external library,
my code:
package com.android.webdav;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.commons.httpclient.HttpException;
import org.apache.util.HttpURL;
import org.apache.webdav.lib.WebdavResource;
import android.app.Activity;
import android.os.Bundle;
public class Webdav extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpURL hrl = new HttpURL("serverUrl");
hrl.setUserInfo("username", "password");
WebdavResource wdr = new WebdavResource(hrl);
File fn = new File("remote-file");
wdr.getMethod(fn);
File LocFile = new File("mnt/sdcard/test/");
wdr.putMethod(LocFile);
wdr.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
but I am getting error,
java.lang.NoClassDefFoundError: org.apache.webdav.lib.WebdavResource
above class already added in jar.
Required help.
Thanks
Sardine + http://code.google.com/p/httpclientandroidlib/ does not work, because httpclientandroidlib has renamed all package names. See android sardine + httpclientandroidlib -> new package names
Sardine + http://code.google.com/p/httpclientandroidlib/
http://sardine.googlecode.com/
You can use https://github.com/yeonsh/Sardine-Android.

Categories

Resources