One smali code but 2 different in Java source - Android General

hi everyone
i'm very noob in android because i'm a Java EE developer.
ok i have one apk file that i want to change the source code in to JAVA.
i decompiled the apk file in two ways:
first, i used apktool ,dex2jar, jd-ui and then i got this java code :
Code:
package com.sunglab.bigbanghd;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.*;
//import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
public class MainActivity
extends Activity
implements SensorEventListener
{
public static final int Amazon = 1;
public static final int Google = 0;
public static boolean IsthatPlaying = true;
public static final int Samsung = 3;
public static final int Tstore = 2;
public static MediaPlayer mPlayer;
public static int store = WallpaperSettings.store;
public int MusicNumber = 0;
Handler handler;
Intent intent;
GL2JNIView.Renderer mRenderer;
private GL2JNIView mView;
Sensor m_ot_sensor;
SensorManager m_sensor_manager;
ImageButton menu_Button;
public void abc(int paramInt)
{
switch (paramInt)
{
}
do
{
do
{
do
{
do
{
do
{
return;
Log.e("else", "Playing 0");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034112);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 1");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034113);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 2");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034114);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 3");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034115);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 4");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034116);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
}
public void onAccuracyChanged(Sensor paramSensor, int paramInt)
{
Log.e("Sensor working", "Good ratated2s");
}
public void onBackPressed()
{
Log.e("omg", "Back key");
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setIcon(2130837507);
if ((store == 2) || (store == 3)) {
localBuilder.setTitle("이 앱을 종료 하시겠습니까?");
}
for (;;)
{
localBuilder.setCancelable(false);
if ((store != 2) && (store != 3)) {
localBuilder.setPositiveButton("More Apps", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
switch (MainActivity.store)
{
}
for (;;)
{
MainActivity.this.startActivity(MainActivity.this.intent);
return;
MainActivity.this.intent = new Intent("android.intent.action.VIEW", Uri.parse("xxxx"));
continue;
MainActivity.this.intent = new Intent("android.intent.action.VIEW", Uri.parse("xxx"));
}
}
});
}
localBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.cancel();
}
});
localBuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
MainActivity.this.finish();
}
});
localBuilder.show();
return;
localBuilder.setTitle("Do you need More SungLab Apps ?");
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
Log.e("gg", "onCreate");
this.m_sensor_manager = ((SensorManager)getSystemService("sensor"));
this.m_ot_sensor = this.m_sensor_manager.getDefaultSensor(3);
this.mView = new GL2JNIView(getApplication());
setContentView(this.mView);
SharedPreferences localSharedPreferences = getSharedPreferences("wallpaperSet", 0);
int i = localSharedPreferences.getInt("THICK", 5);
int j = localSharedPreferences.getInt("TAIL", 7);
int k = localSharedPreferences.getInt("NUMBER", 5999);
int m = localSharedPreferences.getInt("COLORS", 0);
if (Boolean.valueOf(localSharedPreferences.getBoolean("MUSIC", true)).booleanValue()) {}
for (IsthatPlaying = true;; IsthatPlaying = false)
{
GL2JNIView.Renderer.number = k + 1;
GL2JNIView.Renderer.tail = 0.99F - (0.2F - 0.02F * j);
GL2JNIView.Renderer.thick = 1.0F + 0.4F * i;
GL2JNIView.Renderer.colors = m;
addContentView(((LayoutInflater)getSystemService("layout_inflater")).inflate(2130903040, null), new ViewGroup.LayoutParams(-1, -1));
getWindow().setFlags(128, 128);
mPlayer = MediaPlayer.create(this, 2131034112);
if (!IsthatPlaying) {
mPlayer.pause();
}
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
this.menu_Button = ((ImageButton)findViewById(2131296256));
this.menu_Button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
MainActivity.this.startActivity(new Intent(MainActivity.this, WallpaperSettings.class));
}
});
return;
}
}
protected void onDestroy()
{
super.onDestroy();
this.mView = null;
if (mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.release();
mPlayer = null;
Log.e("omg", "Destroy");
}
public void onHomePressed()
{
Log.e("omg", "Home key");
}
protected void onPause()
{
super.onPause();
this.mView.onPause();
if (IsthatPlaying) {
mPlayer.pause();
}
this.m_sensor_manager.unregisterListener(this);
Log.e("omg", "onPause");
}
protected void onResume()
{
super.onResume();
this.mView.onResume();
Log.e("omg", "onResume");
if (Boolean.valueOf(getSharedPreferences("wallpaperSet", 0).getBoolean("MUSIC", true)).booleanValue())
{
IsthatPlaying = true;
if (!IsthatPlaying) {
break label82;
}
mPlayer.start();
}
for (;;)
{
this.m_sensor_manager.registerListener(this, this.m_ot_sensor, 2);
return;
IsthatPlaying = false;
break;
label82:
mPlayer.pause();
}
}
public void onSensorChanged(SensorEvent paramSensorEvent)
{
if (paramSensorEvent.sensor.getType() == 3)
{
if ((int)paramSensorEvent.values[2] > 45) {
GL2JNIView.Renderer.DefinallyROTATION = -90;
}
}
else {
return;
}
if ((int)paramSensorEvent.values[2] < -45)
{
GL2JNIView.Renderer.DefinallyROTATION = 90;
return;
}
GL2JNIView.Renderer.DefinallyROTATION = 0;
}
public boolean onTouchEvent(MotionEvent paramMotionEvent)
{
int i = paramMotionEvent.getPointerCount();
int j = 0;
if (j >= i) {
switch (paramMotionEvent.getAction())
{
}
}
for (;;)
{
return true;
GL2JNIView.TouchMoveNumber(paramMotionEvent.getX(j), paramMotionEvent.getY(j), j, paramMotionEvent.getPointerCount());
j++;
break;
GL2JNIView.TouchUpNumber();
continue;
GL2JNIView.TouchDownNumber();
continue;
GL2JNIView.TouchDownNumber();
}
}
}
/* Location: C:\jd-gui-windows-1.4.0\classes_dex2jar.jar!\com\sunglab\bigbanghd\MainActivity.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
and the second way i used backSmali tool and jd-ui , i got this JAVA code:
Code:
/**
* Generated by smali2java 1.0.0.558
* Copyright (C) 2013 Hensence.com
*/
package com.sunglab.bigbanghd;
import android.app.Activity;
import android.hardware.SensorEventListener;
import android.media.MediaPlayer;
import android.os.Handler;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.ImageButton;
import android.util.Log;
import android.content.Context;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.Application;
import android.view.View;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.hardware.SensorEvent;
import android.view.MotionEvent;
public class MainActivity extends Activity implements SensorEventListener {
public static final int Amazon = 0x1;
public static final int Google = 0x0;
public int MusicNumber;
public static final int Samsung = 0x3;
public static final int Tstore = 0x2;
Handler handler;
Intent intent;
public static MediaPlayer mPlayer;
GL2JNIView.Renderer mRenderer;
private GL2JNIView mView;
Sensor m_ot_sensor;
SensorManager m_sensor_manager;
ImageButton menu_Button;
public static int store = WallpaperSettings.store;
public static boolean IsthatPlaying = 0x1;
public void onCreate(Bundle p1) {
super.onCreate(p1);
Log.e("gg", "onCreate");
m_sensor_manager = (SensorManager)getSystemService("sensor");
m_ot_sensor = m_sensor_manager.getDefaultSensor(0x3);
mView = new GL2JNIView(getApplication());
setContentView(mView);
SharedPreferences "preferences" = getSharedPreferences("wallpaperSet", 0x0);
int "thickness" = "preferences".getInt("THICK", 0x5);
int "tails" = "preferences".getInt("TAIL", 0x7);
int "particleNumber" = "preferences".getInt("NUMBER", 0x176f);
int "colors" = "preferences".getInt("COLORS", 0x0);
Boolean "music" = Boolean.valueOf("preferences".getBoolean("MUSIC", true));
if("music".booleanValue()) {
IsthatPlaying = 0x1;
} else {
IsthatPlaying = 0x0;
}
GL2JNIView.Renderer.number = ("particleNumber" + 0x1);
GL2JNIView.Renderer.tail = (0x3f7d70a4 # 0.99f - (0x3e4ccccd # 0.2f - ((float)"tails" * 0x3ca3d70a # 0.02f)));
GL2JNIView.Renderer.thick = (0.0f + ((float)"thickness" * 0x3ecccccd # 0.4f));
GL2JNIView.Renderer.colors = "colors";
LayoutInflater "vi" = (LayoutInflater)getSystemService("layout_inflater");
View "v" = "vi".inflate(0x0, 0x0);
addContentView("v", new ViewGroup.LayoutParams(-0x1, -0x1));
getWindow().setFlags(0x80, 0x80);
mPlayer = MediaPlayer.create(this, 0x0);
if(!IsthatPlaying) {
mPlayer.pause();
}
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
1(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
menu_Button = (ImageButton)findViewById(0x0);
menu_Button.setOnClickListener(new View.OnClickListener(this) {
2(MainActivity p1) {
}
public void onClick(View p1) {
startActivity(new Intent(this$0, WallpaperSettings.class));
}
});
}
public void abc(int p1) {
switch(p1) {
case 0:
{
Log.e("else", "Playing 0");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x0);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
3(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 1:
{
Log.e("else", "Playing 1");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050001);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
4(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 2:
{
Log.e("else", "Playing 2");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050002);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
5(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 3:
{
Log.e("else", "Playing 3");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050003);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
6(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 4:
{
Log.e("else", "Playing 4");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050004);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
7(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
break;
}
}
}
}
protected void onPause() {
super.onPause();
mView.onPause();
if(IsthatPlaying) {
mPlayer.pause();
}
m_sensor_manager.unregisterListener(this);
Log.e("omg", "onPause");
}
protected void onResume() {
super.onResume();
mView.onResume();
Log.e("omg", "onResume");
SharedPreferences "preferences" = getSharedPreferences("wallpaperSet", 0x0);
Boolean "music" = Boolean.valueOf("preferences".getBoolean("MUSIC", true));
if("music".booleanValue()) {
IsthatPlaying = 0x1;
} else {
IsthatPlaying = 0x0;
}
if(IsthatPlaying) {
mPlayer.start();
} else {
mPlayer.pause();
}
m_sensor_manager.registerListener(this, m_ot_sensor, 0x2);
}
public void onSensorChanged(SensorEvent p1) {
if(p1.sensor.getType() == 0x3) {
if((int)p1.values[0x2] > 0x2d) {
GL2JNIView.Renderer.DefinallyROTATION = -0x5a;
return;
}
if((int)p1.values[0x2] < -0x2d) {
GL2JNIView.Renderer.DefinallyROTATION = 0x5a;
return;
}
GL2JNIView.Renderer.DefinallyROTATION = 0x0;
}
}
public void onAccuracyChanged(Sensor p1, int p2) {
Log.e("Sensor working", "Good ratated2s");
}
protected void onDestroy() {
super.onDestroy();
mView = 0x0;
if(mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.release();
mPlayer = 0x0;
Log.e("omg", "Destroy");
}
public void onBackPressed() {
Log.e("omg", "Back key");
AlertDialog.Builder "d" = new AlertDialog.Builder(this);
"d".setIcon(0x7f020003);
if((store == 0x2) || (store == 0x3)) {
"d".setTitle("\uc774 \uc571\uc744 \uc885\ub8cc \ud558\uc2dc\uaca0\uc2b5\ub2c8\uae4c?");
} else {
"d".setTitle("Do you need More SungLab Apps ?");
}
"d".setCancelable(false);
if((store != 0x2) && (store != 0x3)) {
"d".setPositiveButton("More Apps", new DialogInterface.OnClickListener(this) {
8(MainActivity p1) {
}
public void onClick(DialogInterface p1, int p2) {
switch(MainActivity.store) {
case 0:
{
new Intent("android.intent.action.VIEW", Uri.parse("xx"));
intent = localIntent1;
break;
}
case 1:
{
new Intent("android.intent.action.VIEW", Uri.parse("xxxx"));
intent = localIntent2;
break;
}
}
startActivity(intent);
}
});
}
"d".setNeutralButton("Cancel", new DialogInterface.OnClickListener(this) {
9(MainActivity p1) {
}
public void onClick(DialogInterface p1, int p2) {
p1.cancel();
}
});
"d".setNegativeButton("Exit", new DialogInterface.OnClickListener(this) {
10(MainActivity p1) {
}
public void onClick(DialogInterface p1, int p2) {
finish();
}
});
"d".show();
}
public void onHomePressed() {
Log.e("omg", "Home key");
}
public boolean onTouchEvent(MotionEvent p1) {
int "pointerCount" = p1.getPointerCount();
for(int "i" = 0x0; "i" >= "pointerCount"; "i" = "i" + 0x1) {
}
GL2JNIView.TouchMoveNumber(p1.getX("i"), p1.getY("i"), "i", p1.getPointerCount());
switch(p1.getAction()) {
case 1:
{
GL2JNIView.TouchUpNumber();
break;
}
case 0:
{
GL2JNIView.TouchDownNumber();
break;
}
case 5:
{
GL2JNIView.TouchDownNumber();
break;
}
case 2:
case 3:
case 4:
{
return true;
}
}
}
}
now i have a question why both of java codes are not the same?? for example, in the first one, we have some (do while) loops but in the second way we don't have them???
and as you can see, in the first one some lines seem wrong (in abc() method or it has written for( ;; ) ).
And also in the second one, in abc() method, we have switch case but in the first one we don't have it.
i want to edit some lines and codes but it seems the original decompiled code doesn't work.

Related

Save calculator result problem

Here's where the button is pressed:
btnMP.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
memNum = memNum + Double.parseDouble(txtCalc.getText().toString());
operator = 0; }
});
Here's a thingie I hammered together from parts:
// Save MEMORY
public void WriteMemory(OnClickListener onClickListener, double
memNum){
File sdcard = Environment.getExternalStorageDirectory();
File destinationdir = new File(sdcard,"/download/calculator");
destinationdir.mkdir();
File destinationfile = new File(destinationdir,"memory.dat");
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
destinationfile.createNewFile();
fOut = new FileOutputStream(destinationfile);
osw = new OutputStreamWriter(fOut);
osw.write((int) memNum);
osw.flush();
Toast.makeText((Context) onClickListener, "Memory
saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
// Toast.makeText((Context) onClickListener, "Memory not
saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is called by inserting WriteMemory(this,memNum); in the button
routine thusly:
btnMP.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
memNum = memNum + Double.parseDouble(txtCalc.getText().toString());
operator = 0; }
WriteMemory(this,memNum);
});
The file is created but only a 0 is written in it. What's missing?
Brian

Basic android animation code

Here is the code for a basic animation program in Android:
Code:
[SIZE="2"][FONT="Courier New"]import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import javax.xml.parsers.*;
import javax.security.cert.*;
public class MainActivity extends Activity
{
DrawView drawView = null;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setTitle("Animation Example");
drawView = new DrawView(this);
setContentView(drawView);
}
@Override public void onPause()
{
super.onPause();
drawView.pause();
}
@Override public void onResume()
{
super.onResume();
drawView.resume();
}
}
class DrawView extends SurfaceView implements SurfaceHolder.Callback
{
DrawThread thread = null;
int screenWidth = 0;
int screenHeight = 0;
int radius = 40;
int boundaryTop = 0;
int boundaryBottom = 0;
int boundaryLeft = 0;
int boundaryRight = 0;
float ppsX = 0; // horizontal velocity in pixels per second
float ppsY = 0; // vertical "
float x = 0;
float y = 0;
long lastDrawTime = 0;
int minIntervalMs = 15; // limit frame rate
Paint paint = null;
public DrawView(Context context)
{
super(context);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
getHolder().addCallback(this);
setFocusable(true);
}
public void initialize(int screen_width, int screen_height)
{
screenWidth = screen_width;
screenHeight = screen_height;
x = screenWidth / 2.0f;
y = screenHeight / 2.0f;
boundaryTop = radius;
boundaryBottom = screenHeight - radius - 1;
boundaryLeft = radius;
boundaryRight = screenWidth - radius - 1;
ppsX = 250;
ppsY = 100;
}
public void startThread()
{
thread = new DrawThread(getHolder());
thread.setRunning(true);
thread.start();
}
public void stopThread()
{
boolean retry = true;
thread.setRunning(false);
while (retry)
{
try { thread.join(); retry = false; }
catch (InterruptedException e) { }
}
}
public void pause()
{
stopThread();
lastDrawTime = 0;
}
public void resume()
{
}
@Override public void surfaceCreated(SurfaceHolder holder)
{
startThread();
}
@Override public void surfaceDestroyed(SurfaceHolder holder)
{
stopThread();
}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
}
@Override public void onSizeChanged(int width_new, int height_new, int width_old, int height_old)
{
super.onSizeChanged(width_new, height_new, width_old, height_old);
initialize(width_new, height_new);
}
@Override public synchronized boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
break;
}
case MotionEvent.ACTION_UP:
{
break;
}
case MotionEvent.ACTION_MOVE:
{
break;
}
}
return true;
}
public void updateCanvas(Canvas canvas)
{
if (lastDrawTime != 0)
{
long intervalMs = System.currentTimeMillis() - lastDrawTime; // interval in milliseconds
if (intervalMs < minIntervalMs)
{
try { Thread.sleep(minIntervalMs - intervalMs); }
catch (InterruptedException e) { }
intervalMs = minIntervalMs;
}
float intervalS = intervalMs / 1000.0f; // interval in seconds
x = x + intervalS * ppsX;
if (x < boundaryLeft)
{
x = boundaryLeft;
ppsX = -ppsX;
}
else if (x > boundaryRight)
{
x = boundaryRight;
ppsX = -ppsX;
}
y = y + intervalS * ppsY;
if (y < boundaryTop)
{
y = boundaryTop;
ppsY = -ppsY;
}
else if (y > boundaryBottom)
{
y = boundaryBottom;
ppsY = - ppsY;
}
}
canvas.drawColor(Color.WHITE);
canvas.drawCircle(x, y, radius, paint);
lastDrawTime = System.currentTimeMillis();
}
class DrawThread extends Thread
{
private SurfaceHolder holder = null;
private boolean run = false;
public DrawThread(SurfaceHolder holder)
{
this.holder = holder;
}
public void setRunning(boolean run)
{
this.run = run;
}
@Override public void run()
{
Canvas canvas = null;
while (run)
{
canvas = null;
try
{
canvas = holder.lockCanvas(null);
synchronized (holder)
{
updateCanvas(canvas);
}
}
finally
{
if (canvas != null)
{
holder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}
[/FONT][/SIZE]

[Q] Android Getting Sound Levels

Hello there
I'm a newbie in programming and I wanna build a sound recording application.
I have this code which is recording sound and puts a timestamp :
Code:
package com.tsop.tsp_recorder;
import android.R.layout;
import android.app.Activity;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public MainActivity() {
theDate date = new theDate();
String sDate = date.curDate();
String sTime = date.curTime();
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/TSP_Recordings/Date_"+sDate+"_Time_"+sTime+".3gp";
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
package com.tsop.tsp_recorder;
import java.util.Calendar;
public class theDate {
static Calendar c = Calendar.getInstance();
public static String curDate() {
int month = c.get(Calendar.MONTH) + 1;
String sDate = c.get(Calendar.DAY_OF_MONTH) + "-"
+ month
+ "-" + c.get(Calendar.YEAR);
return sDate;
}
public static String curTime() {
String sTime = c.get(Calendar.HOUR_OF_DAY)
+ "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
return sTime;
}
public static long duration() {
long dur = c.getTimeInMillis();
return dur;
}
}
I need to change it and make it messure the sound levels.I'll use the getMaxAmplitude method,but this method returns only the last result,before it was called.I think I should use a loop,but the start method is capturing and encoding continuously.
How can I get the current amplitude,for example in a period of 1 second,on my recording?
Thanks
I've edited my code into this :
Code:
package com.tsop.tsp_recorder;
import android.R.layout;
import android.app.Activity;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
public int currentAmplitude;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
getAmplitude();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public double getAmplitude() {
if (mRecorder != null) {
currentAmplitude = mRecorder.getMaxAmplitude();
return currentAmplitude;
}
else
return 0;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public MainActivity() {
theDate date = new theDate();
String sDate = date.curDate();
String sTime = date.curTime();
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/TSP_Recordings/Date_"+sDate+"_Time_"+sTime+".3gp";
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
TextView tv = new TextView(this);
ll.addView(tv,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
tv.setText(Integer.toString(currentAmplitude));
setContentView(ll);
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
But my result is 0 everytime.Any ideas?

Not working context menu item in fragment

Code:
public class ThreeFragment extends Fragment {
public View ThreeFragmentView = null;
public static TextView internalMemoryInfo;
public static Button IntBtn;
public ThreeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (ThreeFragmentView == null) ThreeFragmentView = inflater.inflate(R.layout.fragment_three, container, false);
internalMemoryInfo = (TextView) ThreeFragmentView.findViewById(R.id.textViewInternalMemoryInfo);
IntBtn = (Button) ThreeFragmentView.findViewById(R.id.InternalBtn);
return ThreeFragmentView;
}
public static void showText(String text) {
internalMemoryInfo.setText(text);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
registerForContextMenu(IntBtn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
switch (v.getId()){
case R.id.InternalBtn:
menu.setHeaderTitle("Internal Memory Menu");
menu.add(0, ClearCacheMet, 0, "Clear Cache");
menu.add(0, Common, 0, "Go to Common Tab");
menu.add(0, ITEM_CANCEL, 0, "Cancel");
break;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ClearCacheMet:
ClearCache(); <-------This not working
break;
case Common:
tabLayout.getTabAt(0).select(); <-------This working
break;
case ITEM_CANCEL:
ins.closeContextMenu(); <-------This working
break;
}
return true;
}
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();
}
public static void ClearCache() {
File cache = ins.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
}
}
}
try{
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
((ActivityManager) ins.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
} else {*/
File externalcache = ins.getExternalCacheDir();
File externalappDir = new File(externalcache.getParent());
if (externalappDir.exists()) {
String[] children = externalappDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(externalappDir, s));
}
}
} else {
Log.d(TAG, "No externalappDir");
}
/*}*/
} catch (Exception e) {
Log.d(TAG, "MainActivity in ClearCache");
}
}
I have fragment(ThreeFragment) with button(InternalBtn) that have a context menu. Context menu registered with registerForContextMenu(IntBtn); Menu item ClearCacheMet not working. I cannot see neither Toast.makeText().show(); nor Log.d(TAG, "ClearCache"); Common and ITEM_CANCEL items working. I cannot understand why? Please help me.
Toast.makeText(getActivity(), "Called !", Toast.LENGTH_SHORT).show(); not called in ClearCache() function. ClearCacheMet and Common were initialized in other fragment.
public class OneFragment extends Fragment {
public View OneFragmentView = null;
public static final int Common = 25;
public static final int ClearCacheMet = 50;

How to crop bitmaps according to size of a custom view

Trying to make a motion detection app. The intention is to make the app take pictures when motion is detected by comparing two images. Up to this part, the app is working fine.
Requirement:
To specify area of detection by a custom view. So that, the pictures will be captured only if a motion is detected inside the defined area by calculating the detection area.
What I have tried:
Created a movable custom view, like a crop view of which the dimensions (`Rect`) are saved in the preference each time when the view is moved.
In the detection thread I tried setting the width and height from the preference like
Code:
private int width = Prefe.DetectionArea.width();
private int height = Prefe.DetectionArea.height();
But it didn't work.
What is not working:
The motion detection from inside the custom view is not working. I believe that the bitmaps must be cropped according to the size of the custom view.
Please help me by explaining how this could be achieved so that the motion detection will happen according to the size of the custom view. I'm new to android and trying to self learn, any help is appreciated.
MotionDetectionActivity.java
Code:
public class MotionDetectionActivity extends SensorsActivity {
private static final String TAG = "MotionDetectionActivity";
private static long mReferenceTime = 0;
private static IMotionDetection detector = null;
public static MediaPlayer song;
public static Vibrator mVibrator;
private static SurfaceView preview = null;
private static SurfaceHolder previewHolder = null;
private static Camera camera = null;
private static boolean inPreview = false;
private static AreaDetectorView mDetector;
private static FrameLayout layoutDetectorArea;
static FrameLayout layoutMain;
static View mView;
private static volatile AtomicBoolean processing = new AtomicBoolean(false);
/**
* {@inheritDoc}
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.main);
mVibrator = (Vibrator)this.getSystemService(VIBRATOR_SERVICE);
layoutMain=(FrameLayout)findViewById(R.id.layoutMain);
preview = (SurfaceView) findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mView=layoutMain;
mDetector= (AreaDetectorView) findViewById(R.id.viewDetector);
layoutDetectorArea=(FrameLayout) findViewById(R.id.layoutDetectArea);
ToggleButton toggle = (ToggleButton) findViewById(R.id.simpleToggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
if (Preferences.USE_RGB) {
detector = new RgbMotionDetection();
} else if (Preferences.USE_LUMA) {
detector = new LumaMotionDetection();
} else {
// Using State based (aggregate map)
detector = new AggregateLumaMotionDetection();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
/**dd:
* Song play # 1
* Camera callback
*
* {@inheritDoc}
*/
@Override
public void onPause() {
super.onPause();
if(song!=null && song.isPlaying())
{
song.stop();}
camera.setPreviewCallback(null);
if (inPreview) camera.stopPreview();
inPreview = false;
camera.release();
camera = null;
}
/**
* {@inheritDoc}
*/
@Override
public void onResume() {
super.onResume();
camera = Camera.open();
}
private PreviewCallback previewCallback = new PreviewCallback() {
/**
* {@inheritDoc}
*/
@Override
public void onPreviewFrame(byte[] data, Camera cam) {
if (data == null) return;
Camera.Size size = cam.getParameters().getPreviewSize();
if (size == null) return;
if (!GlobalData.isPhoneInMotion()) {
DetectionThread thread = new DetectionThread(data, size.width, size.height);
thread.start();
}
}
};
private SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
/**
* {@inheritDoc}
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
camera.setPreviewCallback(previewCallback);
} catch (Throwable t) {
Log.e("Prek", "Exception in setPreviewDisplay()", t);
}
}
/**
* {@inheritDoc}
*/
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(camera != null) {
Camera.Parameters parameters = camera.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
Camera.Size size = getBestPreviewSize(width, height, parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
Log.d(TAG, "Using width=" + size.width + " height=" + size.height);
}
camera.setParameters(parameters);
camera.startPreview();
inPreview = true;
}
//AreaDetectorView.InitDetectionArea();
}
/**
* {@inheritDoc}
*/
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Ignore
}
};
private static Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) result = size;
}
}
}
return result;
}
//***************Detection Class******************//
private final class DetectionThread extends Thread {
private byte[] data;
private int width;
private int height;
public DetectionThread(byte[] data, int width, int height) {
this.data = data;
this.width = width;
this.height = height;
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
if (!processing.compareAndSet(false, true)) return;
// Log.d(TAG, "BEGIN PROCESSING...");
try {
// Previous frame
int[] pre = null;
if (Preferences.SAVE_PREVIOUS) pre = detector.getPrevious();
// Current frame (with changes)
// long bConversion = System.currentTimeMillis();
int[] img = null;
if (Preferences.USE_RGB) {
img = ImageProcessing.decodeYUV420SPtoRGB(data, width, height);
} else {
img = ImageProcessing.decodeYUV420SPtoLuma(data, width, height);
}
// Current frame (without changes)
int[] org = null;
if (Preferences.SAVE_ORIGINAL && img != null) org = img.clone();
if (img != null && detector.detect(img, width, height)) {
// The delay is necessary to avoid taking a picture while in
// the
// middle of taking another. This problem can causes some
// phones
// to reboot.
long now = System.currentTimeMillis();
if (now > (mReferenceTime + Preferences.PICTURE_DELAY)) {
mReferenceTime = now;
//mVibrator.vibrate(10);
Bitmap previous = null;
if (Preferences.SAVE_PREVIOUS && pre != null) {
if (Preferences.USE_RGB) previous = ImageProcessing.rgbToBitmap(pre, width, height);
else previous = ImageProcessing.lumaToGreyscale(pre, width, height);
}
Bitmap original = null;
if (Preferences.SAVE_ORIGINAL && org != null) {
if (Preferences.USE_RGB) original = ImageProcessing.rgbToBitmap(org, width, height);
else original = ImageProcessing.lumaToGreyscale(org, width, height);
}
Bitmap bitmap = null;
if (Preferences.SAVE_CHANGES) {
if (Preferences.USE_RGB) bitmap = ImageProcessing.rgbToBitmap(img, width, height);
else bitmap = ImageProcessing.lumaToGreyscale(img, width, height);
}
Log.i(TAG, "Saving.. previous=" + previous + " original=" + original + " bitmap=" + bitmap);
Looper.prepare();
new SavePhotoTask().execute(previous, original, bitmap);
} else {
Log.i(TAG, "Not taking picture because not enough time has passed since the creation of the Surface");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
processing.set(false);
}
// Log.d(TAG, "END PROCESSING...");
processing.set(false);
}
};
private static final class SavePhotoTask extends AsyncTask<Bitmap, Integer, Integer> {
/**
* {@inheritDoc}
*/
@Override
protected Integer doInBackground(Bitmap... data) {
for (int i = 0; i < data.length; i++) {
Bitmap bitmap = data[i];
String name = String.valueOf(System.currentTimeMillis());
if (bitmap != null) save(name, bitmap);
}
return 1;
}
private void save(String name, Bitmap bitmap) {
File photo = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
if (photo.exists()) photo.delete();
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}
}
}
AreaDetectorView.java
Code:
public class AreaDetectorView extends LinearLayout {
public static int Width;
public static int Height;
private static Paint BoxPaint = null;
private static Paint TextPaint = null;
private static Paint ArrowPaint = null;
private static Path mPath = null;
private static Rect mRect = null;
private static int lastX, lastY = 0;
private static boolean mBoxTouched = false;
private static boolean mArrowTouched = false;
private static Context mContext;
private static int ArrowWidth = 0;
private static Paint BoxPaint2 = null;
public AreaDetectorView(Context context) {
super(context);
mContext = context;
}
//attrs was not there
public AreaDetectorView(Context context, AttributeSet attrs) {
super(context,attrs);
mContext = context;
// TODO Auto-generated constructor stub
if (!this.getRootView().isInEditMode()) {
ArrowWidth =GetDisplayPixel(context, 30);
}
//InitDetectionArea();
InitMemberVariables();
setWillNotDraw(false);
}
public static int GetDisplayPixel(Context paramContext, int paramInt)
{
return (int)(paramInt * paramContext.getResources().getDisplayMetrics().density + 0.5F);
}
public static void InitMemberVariables() {
if (BoxPaint == null) {
BoxPaint = new Paint();
BoxPaint.setAntiAlias(true);
BoxPaint.setStrokeWidth(2.0f);
//BoxPaint.setStyle(Style.STROKE);
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext, R.color.bwff_60));
}
if (ArrowPaint == null) {
ArrowPaint = new Paint();
ArrowPaint.setAntiAlias(true);
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.redDD));
ArrowPaint.setStyle(Style.FILL_AND_STROKE);
}
if (TextPaint == null) {
TextPaint = new Paint();
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.yellowL));
TextPaint.setTextSize(16);
//txtPaint.setTypeface(lcd);
TextPaint.setStyle(Style.FILL_AND_STROKE);
}
if (mPath == null) {
mPath = new Path();
} else {
mPath.reset();
}
if (mRect == null) {
mRect = new Rect();
}
if (BoxPaint2 == null) {
BoxPaint2 = new Paint();
BoxPaint2.setAntiAlias(true);
BoxPaint2.setStrokeWidth(2.0f);
//BoxPaint.setStyle(Style.STROKE);
BoxPaint2.setStyle(Style.STROKE);
BoxPaint2.setColor(ContextCompat.getColor(mContext,R.color.bwff_9e));
}
}
public static void InitDetectionArea() {
try {
int w = Prefe.DetectionArea.width();
int h = Prefe.DetectionArea.height();
int x = Prefe.DetectionArea.left;
int y = Prefe.DetectionArea.top;
// ver 2.6.0
if (Prefe.DetectionArea.left == 1
&& Prefe.DetectionArea.top == 1
&& Prefe.DetectionArea.right == 1
&& Prefe.DetectionArea.bottom == 1) {
w = Prefe.DisplayWidth / 4;
h = Prefe.DisplayHeight / 3;
// ver 2.5.9
w = Width / 4;
h = Height / 3;
Prefe.DetectorWidth = w; //UtilGeneralHelper.GetDisplayPixel(this, 100);
Prefe.DetectorHeight = h; //UtilGeneralHelper.GetDisplayPixel(this, 100);
x = (Prefe.DisplayWidth / 2) - (w / 2);
y = (Prefe.DisplayHeight / 2) - (h / 2);
// ver 2.5.9
x = (Width / 2) - (w / 2);
y = (Height / 2) - (h / 2);
}
//Prefe.DetectionArea = new Rect(x, x, x + Prefe.DetectorWidth, x + Prefe.DetectorHeight);
Prefe.DetectionArea = new Rect(x, y, x + w, y + h);
Prefe.gDetectionBitmapInt = new int[Prefe.DetectionArea.width() * Prefe.DetectionArea.height()];
Prefe.gDetectionBitmapIntPrev = new int[Prefe.DetectionArea.width() * Prefe.DetectionArea.height()];
} catch (Exception e) {
e.printStackTrace();
}
}
public static void SetDetectionArea(int x, int y, int w, int h) {
try {
Prefe.DetectionArea = new Rect(x, y, w, h);
} catch (Exception e) {
e.printStackTrace();
}
}
private void DrawAreaBox(Canvas canvas) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
try {
if (this.getRootView().isInEditMode()) {
super.dispatchDraw(canvas);
return;
}
//canvas.save(Canvas.MATRIX_SAVE_FLAG);
//Prefe.DetectionAreaOrient = UtilGeneralHelper.GetDetectRectByOrientation();
canvas.drawColor(0);
mPath.reset();
canvas.drawRect(Prefe.DetectionArea, BoxPaint);
mPath.moveTo(Prefe.DetectionArea.right - ArrowWidth, Prefe.DetectionArea.bottom);
mPath.lineTo(Prefe.DetectionArea.right, Prefe.DetectionArea.bottom - ArrowWidth);
mPath.lineTo(Prefe.DetectionArea.right, Prefe.DetectionArea.bottom);
mPath.lineTo(Prefe.DetectionArea.right - ArrowWidth, Prefe.DetectionArea.bottom);
mPath.close();
canvas.drawPath(mPath, ArrowPaint);
mPath.reset();
//canvas.drawRect(Prefe.DetectionAreaOrient, BoxPaint2);
//canvas.drawRect(Prefe.DetectionAreaOrientPort, BoxPaint2);
TextPaint.setTextSize(16);
//TextPaint.setLetterSpacing(2);
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff));
TextPaint.getTextBounds(getResources().getString(R.string.str_detectarea), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_detectarea),
Prefe.DetectionArea.left + 4,
Prefe.DetectionArea.top + 4 + mRect.height(),
TextPaint);
int recH = mRect.height();
TextPaint.setStrokeWidth(1.2f);
TextPaint.setTextSize(18);
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.redD_9e));
TextPaint.getTextBounds(getResources().getString(R.string.str_dragandmove), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_dragandmove),
Prefe.DetectionArea.left + 4,
Prefe.DetectionArea.top + 20 + mRect.height()*2,
TextPaint);
TextPaint.getTextBounds(getResources().getString(R.string.str_scalearea), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_scalearea),
Prefe.DetectionArea.left + 4,
Prefe.DetectionArea.top + 36 + mRect.height()*3,
TextPaint);
super.dispatchDraw(canvas);
//canvas.restore();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
invalidate();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean retValue = true;
int X = (int)event.getX();
int Y = (int)event.getY();
//AppMain.txtLoc.setText(String.valueOf(X) + ", " + String.valueOf(Y));
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mBoxTouched = TouchedInBoxArea(X, Y);
//AppMain.txtLoc.setText("BoxTouched: " + String.valueOf(mBoxTouched));
if (!mBoxTouched) break;
lastX = X;
lastY = Y;
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext,R.color.redD_9e));
mArrowTouched = TouchedInArrow(X, Y);
//AppMain.txtLoc.setText("ArrowTouched: " + String.valueOf(mBoxTouched));
if (mArrowTouched) {
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff_9e));
}
break;
case MotionEvent.ACTION_MOVE:
if (!mBoxTouched) break;
int moveX = X - lastX;
int moveY = Y - lastY;
//AppMain.txtLoc.setText("Move X, Y: " + String.valueOf(moveX) + "," + String.valueOf(moveY));
if (!mArrowTouched) {
if (Prefe.DetectionArea.left + moveX < 0) {
break;
}
// if (Prefe.DetectionArea.right + moveX > Prefe.gDisplay.getWidth()) {
// break;
// }
// ver 2.5.9
if (Prefe.DetectionArea.right + moveX > Width) {
break;
}
if (Prefe.DetectionArea.top + moveY < 0) {
break;
}
// if (Prefe.DetectionArea.bottom + moveY > Prefe.gDisplay.getHeight()) {
// break;
// }
// ver 2.5.9
if (Prefe.DetectionArea.bottom + moveY > Height) {
break;
}
}
if (mArrowTouched) {
if ((Prefe.DetectionArea.width() + moveX) < ArrowWidth * 2){
break;
}
if ((Prefe.DetectionArea.height() + moveY) < ArrowWidth * 2) {
break;
}
Prefe.DetectionArea.right += moveX;
Prefe.DetectionArea.bottom += moveY;
//Log.i("DBG", "W,H: " + String.valueOf(Prefe.DetectionArea.width()) + "," + String.valueOf(Prefe.DetectionArea.height()));
} else {
Prefe.DetectionArea.left += moveX;
Prefe.DetectionArea.right += moveX;
Prefe.DetectionArea.top += moveY;
Prefe.DetectionArea.bottom += moveY;
}
lastX = X;
lastY = Y;
//AppMain.txtLoc.setText(String.valueOf(Prefe.DetectionArea.left) + ", " + String.valueOf(Prefe.DetectionArea.top));
break;
case MotionEvent.ACTION_UP:
mBoxTouched = false;
mArrowTouched = false;
//BoxPaint.setStyle(Style.STROKE);
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff_60));
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.redDD));
//AppMain.txtLoc.setText(String.valueOf(Prefe.DetectionArea.left) + ", " + String.valueOf(Prefe.DetectionArea.top));
if (Prefe.DetectionArea.left < 0) {
Prefe.DetectionArea.left = 0;
}
// if (Prefe.DetectionArea.right > Prefe.gDisplay.getWidth()) {
// Prefe.DetectionArea.right = Prefe.gDisplay.getWidth();
// }
// ver 2.5.9
if (Prefe.DetectionArea.right > Width) {
Prefe.DetectionArea.right = Width;
}
if (Prefe.DetectionArea.top < 0) {
Prefe.DetectionArea.top = 0;
}
// if (Prefe.DetectionArea.bottom > Prefe.gDisplay.getHeight()) {
// Prefe.DetectionArea.bottom = Prefe.gDisplay.getHeight();
// }
if (Prefe.DetectionArea.bottom > Height) {
Prefe.DetectionArea.bottom = Height;
}
Prefe.gDetectionBitmapInt = new int[Prefe.DetectionArea.width() * Prefe.DetectionArea.height()];
Prefe.gDetectionBitmapIntPrev = new int[Prefe.DetectionArea.width() * Prefe.DetectionArea.height()];
//Prefe.gDetectionBitmapInt = null;
//Prefe.gDetectionBitmapIntPrev = null;
String area = String.valueOf(Prefe.DetectionArea.left)
+ "," + String.valueOf(Prefe.DetectionArea.top)
+ "," + String.valueOf(Prefe.DetectionArea.right)
+ "," + String.valueOf(Prefe.DetectionArea.bottom);
// UtilGeneralHelper.SavePreferenceSetting(Prefe.gContext, Prefe.PREF_DETECTION_AREA_KEY, area);
//Saving the value
SharedPrefsUtils.setStringPreference(mContext.getApplicationContext(), Prefe.PREF_DETECTION_AREA_KEY, area);
Log.v("TAG", SharedPrefsUtils.getStringPreference(mContext.getApplicationContext(),Prefe.PREF_DETECTION_AREA_KEY));
break;
}
invalidate();
return retValue;
}
private boolean TouchedInBoxArea(int x, int y) {
boolean retValue = false;
try {
if (x > Prefe.DetectionArea.left && x < Prefe.DetectionArea.right) {
if (y > Prefe.DetectionArea.top && y < Prefe.DetectionArea.bottom) {
retValue = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retValue;
}
private boolean TouchedInArrow(int x, int y) {
boolean retValue = false;
try {
if (x > Prefe.DetectionArea.right - ArrowWidth && x < Prefe.DetectionArea.right) {
if (y > Prefe.DetectionArea.bottom - ArrowWidth && y < Prefe.DetectionArea.bottom) {
retValue = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retValue;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
Width = width;
Height = height;
InitDetectionArea();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
for (int i = 0; i < this.getChildCount()-1; i++){
(this.getChildAt(i)).layout(l, t, r, b);
}
if (changed) {
// check width height
if (r != Width || b != Height) {
// size does not match
}
}
}
}
Prefe.java
Code:
public class Prefe extends Application{
...
public static final String PREF_DETECTION_AREA_KEY = "pref_detection_area_key";
}
static{
...
DetectionArea = new Rect(1, 1, 1, 1);
}
}

Categories

Resources