I built an android application on the android studio to get the feedback of customers, and at the beginning of each activity, I put a voice over.. When the customer finishes the task, the application returns to the first screen (activity 1).
I want to clear the cache of the application when it arrives at the last activity to avoid cache problems (lack of sound..etc)
Thanks a lot
to delete cache of your own application then simply delete your cache directory
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception e) { e.printStackTrace();}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
and it won't clear your shared preference.
Thank you....
I've created a simple shell script which basically just starts an ".jar" file.
this script contains the following
now=$(date +"%s")
sudo java -jar /home/pi/Desktop/test.jar > /home/pi/Desktop/output_$now.txt
I added the script to the crontask with
#reboot sudo bash /home/pi/Desktop/testmygps.sh
My application is going to be a "GPS controller" which is used for dropping baits for foxes (immunization against rabies).
My application consists of 3 threads, one for updating the connected LCD Display, one for updating the GPS position and speed and one for dropping the baits.
I use serial communication for the GPS Modul (and then extract the needed data) and the pi4j library (v1.1) to communicate with the GPIOs.
When I start the jar from the terminal everything works as expected (so far I just calculate the distances between the drops and save every drop coordinate, and at the LCD shows the current speed and the calculated delay between the drops).
But when I reboot my pi with 'sudo reboot' my jar starts, then a few 'speed updates' are made and then somehow the connection to the connection to the GPS module gets lost and only the LCD continues to work.
Anyone an idea what could be the cause of my problem?
PS.
This is the GPSController class of my project
package baitcontrol.v2;
import java.util.Date;
import java.util.logging.Logger;
import com.pi4j.wiringpi.Serial;
import exceptions.NMEAparseException;
import utils.Parser;
import utils.Utils;
public class GPSController implements Runnable {
private static final Logger LOGGER =
Logger.getLogger(GPSController.class.getName());
private int serialPort;
private static boolean continueLoop = true;
private static GPSController instance;
private GPGGAEvent lastGPGGAUpdateEvent;
private GPVTGEvent lastGPVTGUpdateEvent;
private GPSController() {
LOGGER.info("GPSController init");
this.serialPort = Serial.serialOpen("/dev/serial0", 9600);
LOGGER.info("GPSController initialised");
if (this.serialPort == -1) {
LOGGER.severe("Serial Port Failed");
System.out.println("Serial Port Failed");
}
}
public static GPSController getInstance() {
if (instance == null) {
instance = new GPSController();
}
return instance;
}
#Override
public void run() {
LOGGER.info("GPSController started");
String nmea = "";
while (continueLoop) {
if (Serial.serialDataAvail(serialPort) > 0) {
byte[] rawData = Serial.serialGetAvailableBytes(serialPort);
for (byte dataByte : rawData) {
char character = (char) dataByte;
if (character == '\n') {
LOGGER.fine("new nmealine " +nmea);
if(nmea.contains("GPGGA")){
LOGGER.fine("new GPGGA line");
try {
lastGPGGAUpdateEvent = Parser.parseGPGGAToGPSEvent(nmea);
} catch (NMEAparseException e) {
LOGGER.warning(e.getMessage());
System.out.println(e.getMessage());
Utils.addToTxt("error_" + Utils.dateToString(Main.startTime), e.getMessage());
}
}
if(nmea.contains("GPVTG")){
LOGGER.fine("new GPGGA line");
try {
lastGPVTGUpdateEvent = Parser.parseGPVTGToGPSEvent(nmea);
} catch (NMEAparseException e) {
LOGGER.warning(e.getMessage());
System.out.println(e.getMessage());
Utils.addToTxt("error_" + Utils.dateToString(Main.startTime), e.getMessage());
}
}
nmea = "";
}else{
nmea+=Character.toString(character);
}
}
} else {
LOGGER.finest("data empty");
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
LOGGER.finest(e.getMessage());
System.out.println(e.getMessage());
Utils.addToTxt("error_" + Utils.dateToString(Main.startTime), e.getMessage());
}
}
}
public GPGGAEvent getLastGPGGAUpdateEvent() {
return lastGPGGAUpdateEvent;
}
public GPVTGEvent getLastGPVTGUpdateEvent() {
return lastGPVTGUpdateEvent;
}
public boolean positionHasAlreadyBeenUpdated(){
return lastGPGGAUpdateEvent!=null;
}
public boolean speedHasAlreadyBeenUpdated(){
return lastGPVTGUpdateEvent!=null;
}
}
I'm writing a game using Libgdx and I discovered that on Android, when the home button is pressed and I go back into it, my game will increase the amount of memory allocated to it by about 1.5 - 2 MB each time. I've tried to track down why that occurs but I have not been able to find it. Anyway, I decided to close down my program instead of letting it remain in memory on android by using
System.exit(0);
By doing this, the memory gets cleared and I do not have to worry about that increase. I know it is not ideal but I really can not track down the issue.
Problem is that now my save file does not finish writing everything before the program exits.
In my Save class:
public class Save
{
//GameData class holds all of my values that need to be saved.
public static GameData data = new GameData();
public static void saveData() thorws IOException
{
FileHandle file = Gdx.files.local("saveData.sav");
OutputStream out = null;
try
{
file.writeBytes(serialize(data), false;)
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch(Exception ex)
{
}
}
}
}
private static byte[] serialize(Object obj) throws IOException
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
}
In my Main class:
public class MainGame extends ApplicationAdapter
{
public void create()
{
resume();
}
public void render()
{
//.....
}
public void resize()
{
//......
}
public void pause()
{
//set things that need to be saved
//save
try
{
Save.saveData();
}
catch(Exception e)
{
e.printStackTrace();
}
//now I set my arraylists and pretty much everything else to null
//that can be set to null. I was hoping this would fix the memory
//increasing issue. It helped but didn't fix it completely.
//call dispose
dispose();
}
public void resume()
{
//loads various things and determines if the game is to load from
//save due to home being pressed or just load normally.
}
public void dispose()
{
//dispose of a few things
//exit
System.exit(0);
}
}
How can I make sure that the program will only exit after all data has finished being output?
I've tried a few things on my own which didn't work so I'm hoping someone might be able to help.
I have encountered this error:
java.lang.UnsupportedOperationException: Desktop API is not supported on the current platform
I would open a file from my java application. I use this method:
Desktop.getDesktop().open(new File(report.html"));
How can i solve this problem?
Basically, the problem is that Java Desktop integration doesn't work well on Linux.
It was designed to work good with Windows; something works on other systems, but nobody really cared to add proper support for those. Even if you install the required 'gnome libraries', the results will be poor.
I've faced the very same problem a while ago, and came up with the class below.
The goal is achieved by using system-specific commands:
KDE: kde-open
GNOME: gnome-open
Any X-server system: xdg-open
MAC: open
Windows: explorer
If none of those works, it tries the implementation provided by Java Desktop.
Because this one usually fails, it's tried as the last resort.
DesktopApi class
This class provides static methods open, browse and edit.
It is tested to work on Linux (Kde and Gnome), Windows and Mac.
If you use it, please give me credit.
package net.mightypork.rpack.utils;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
public class DesktopApi {
public static boolean browse(URI uri) {
if (openSystemSpecific(uri.toString())) return true;
if (browseDESKTOP(uri)) return true;
return false;
}
public static boolean open(File file) {
if (openSystemSpecific(file.getPath())) return true;
if (openDESKTOP(file)) return true;
return false;
}
public static boolean edit(File file) {
// you can try something like
// runCommand("gimp", "%s", file.getPath())
// based on user preferences.
if (openSystemSpecific(file.getPath())) return true;
if (editDESKTOP(file)) return true;
return false;
}
private static boolean openSystemSpecific(String what) {
EnumOS os = getOs();
if (os.isLinux()) {
if (runCommand("kde-open", "%s", what)) return true;
if (runCommand("gnome-open", "%s", what)) return true;
if (runCommand("xdg-open", "%s", what)) return true;
}
if (os.isMac()) {
if (runCommand("open", "%s", what)) return true;
}
if (os.isWindows()) {
if (runCommand("explorer", "%s", what)) return true;
}
return false;
}
private static boolean browseDESKTOP(URI uri) {
logOut("Trying to use Desktop.getDesktop().browse() with " + uri.toString());
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
logErr("BROWSE is not supported.");
return false;
}
Desktop.getDesktop().browse(uri);
return true;
} catch (Throwable t) {
logErr("Error using desktop browse.", t);
return false;
}
}
private static boolean openDESKTOP(File file) {
logOut("Trying to use Desktop.getDesktop().open() with " + file.toString());
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
logErr("OPEN is not supported.");
return false;
}
Desktop.getDesktop().open(file);
return true;
} catch (Throwable t) {
logErr("Error using desktop open.", t);
return false;
}
}
private static boolean editDESKTOP(File file) {
logOut("Trying to use Desktop.getDesktop().edit() with " + file);
try {
if (!Desktop.isDesktopSupported()) {
logErr("Platform is not supported.");
return false;
}
if (!Desktop.getDesktop().isSupported(Desktop.Action.EDIT)) {
logErr("EDIT is not supported.");
return false;
}
Desktop.getDesktop().edit(file);
return true;
} catch (Throwable t) {
logErr("Error using desktop edit.", t);
return false;
}
}
private static boolean runCommand(String command, String args, String file) {
logOut("Trying to exec:\n cmd = " + command + "\n args = " + args + "\n %s = " + file);
String[] parts = prepareCommand(command, args, file);
try {
Process p = Runtime.getRuntime().exec(parts);
if (p == null) return false;
try {
int retval = p.exitValue();
if (retval == 0) {
logErr("Process ended immediately.");
return false;
} else {
logErr("Process crashed.");
return false;
}
} catch (IllegalThreadStateException itse) {
logErr("Process is running.");
return true;
}
} catch (IOException e) {
logErr("Error running command.", e);
return false;
}
}
private static String[] prepareCommand(String command, String args, String file) {
List<String> parts = new ArrayList<String>();
parts.add(command);
if (args != null) {
for (String s : args.split(" ")) {
s = String.format(s, file); // put in the filename thing
parts.add(s.trim());
}
}
return parts.toArray(new String[parts.size()]);
}
private static void logErr(String msg, Throwable t) {
System.err.println(msg);
t.printStackTrace();
}
private static void logErr(String msg) {
System.err.println(msg);
}
private static void logOut(String msg) {
System.out.println(msg);
}
public static enum EnumOS {
linux, macos, solaris, unknown, windows;
public boolean isLinux() {
return this == linux || this == solaris;
}
public boolean isMac() {
return this == macos;
}
public boolean isWindows() {
return this == windows;
}
}
public static EnumOS getOs() {
String s = System.getProperty("os.name").toLowerCase();
if (s.contains("win")) {
return EnumOS.windows;
}
if (s.contains("mac")) {
return EnumOS.macos;
}
if (s.contains("solaris")) {
return EnumOS.solaris;
}
if (s.contains("sunos")) {
return EnumOS.solaris;
}
if (s.contains("linux")) {
return EnumOS.linux;
}
if (s.contains("unix")) {
return EnumOS.linux;
} else {
return EnumOS.unknown;
}
}
}
I am using Ubuntu 12.04 LTS 64-bit with Oracle jdk1.6.0_45 and was having the same problem.
I’m running gnome-classic as the desktop instead of Unity. This is what worked for me:
sudo apt-get install libgnome2-0
After installing this package I restarted my Java Swing app and Desktop.getDesktop().open(new File("myfile")); worked just fine.
The Desktop class is not supported on all systems.
From the Java Swing tutorial How to Integrate with the Desktop Class:
Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false. After determining that the Desktop API is supported, that is, the isDesktopSupported() returns true, the application can retrieve a Desktop instance using the static method getDesktop().
In any case, it would be best to provide an alternative way to open a file if there is no support for Desktop.
Support varies between implementations on the various JDKs. I encountered the "UnsupportedOperationException" using OpenJDK 1.7.0. Switching to the Oracle JDK 1.7 worked.
Where practical, you may be able to switch JDKs or suggest that your users switch JDKs to enable a certain feature.
I have a following code as below:
new Thread(new Test1Runnable()).start(); // Line (a)
public class Test1Runnable implements Runnable {
public void run() {
Test2Runnable task1 = new Test2Runnable();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.submit(task1);
while(true) {
if(task1.isDone()) {
break;
}
// Thread.sleep(2000); // Line (b)
}
if(!task1.hasError()) { // Line (c)
executor.submit(new Test3Runnable());
}
} catch(Exception ex) {
if(executor != null) {
executor.shutdown();
}
}
}
}
public class Test2Runnable implements Runnable {
private Exception error;
private boolean done;
public void run() {
reset();
doRun();
done = true;
}
protected void doRun() {
try{
// ...
// ....
} catch(Exception ex) {
}
}
private void reset() {
error = null;
done = false;
}
public boolean isDone() {
return done;
}
public boolean hasError() {
return getError() != null || getNonSuccess() > 0;
}
public Exception getError() {
return error;
}
}
I have an issue when I run Test1Runnable at line (a) and comment Line (b) then the thread hang and not run to Line (c). If I uncomment line (b) or I add breakpoint at line (c) and activate remote debug the thread continue to run to the end as normal. Could anyone can give me some advice about this? Why the Thread not continue running? All threads run without any exception.
Looks like you have a race conditioin here, so result of the execution depends on timings, debug enabled, etc. The code posted is more or less fine, the error is likely to be in Test2Runnable class. I suppose there are some flags (isDone, hasError) that have visibility issues. Try to declare them volatile.
Please add Test2Runnable code here and I'll be able to give more precise answer.