[Q] Audio Level Meter - General Questions and Answers

Hello
I'm new to programming and I'm trying to make a java application that will "hear" (not record necessarily) the sound and display how loud is.I'm thinking of converting the sound recordings to numbers,so I can see the difference on the sound levels.I got this code and I added the "getLevel()" method,which returns the amplitude of the current recording,but it's returning -1 everytime.I guess I'm not using it properly. Any ideas how I must call this method?I have to deliver my project in a week,so any help will be much appreciated!
Code:
public class Capture extends JFrame {
protected boolean running;
ByteArrayOutputStream out;
public Capture() {
super("Capture Sound Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container content = getContentPane();
final JButton capture = new JButton("Capture");
final JButton stop = new JButton("Stop");
final JButton play = new JButton("Play");
capture.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(false);
ActionListener captureListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
capture.setEnabled(false);
stop.setEnabled(true);
play.setEnabled(false);
captureAudio();
}
};
capture.addActionListener(captureListener);
content.add(capture, BorderLayout.NORTH);
ActionListener stopListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
capture.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
running = false;
}
};
stop.addActionListener(stopListener);
content.add(stop, BorderLayout.CENTER);
ActionListener playListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
playAudio();
}
};
play.addActionListener(playListener);
content.add(play, BorderLayout.SOUTH);
}
private void captureAudio() {
try {
final AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(
TargetDataLine.class, format);
final TargetDataLine line = (TargetDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int)format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
out = new ByteArrayOutputStream();
running = true;
try {
while (running) {
int count =
line.read(buffer, 0, buffer.length);
if (count > 0) {
out.write(buffer, 0, count);
System.out.println(line.getLevel()); // |-this is what i added-|
}
}
out.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-1);
}
}
};
Thread captureThread = new Thread(runner);
captureThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-2);
}
}
private void playAudio() {
try {
byte audio[] = out.toByteArray();
InputStream input =
new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais =
new AudioInputStream(input, format,
audio.length / format.getFrameSize());
DataLine.Info info = new DataLine.Info(
SourceDataLine.class, format);
final SourceDataLine line = (SourceDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
try {
int count;
while ((count = ais.read(
buffer, 0, buffer.length)) != -1) {
if (count > 0) {
line.write(buffer, 0, count);
}
}
line.drain();
line.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-3);
}
}
};
Thread playThread = new Thread(runner);
playThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-4);
}
}
private AudioFormat getFormat() {
float sampleRate = 8000;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;
return new AudioFormat(sampleRate,
sampleSizeInBits, channels, signed, bigEndian);
}
@SuppressWarnings("deprecation")
public static void main(String args[]) {
JFrame frame = new Capture();
frame.pack();
frame.show();
}
}

Ok,I managed to make it capture audio and print on a xls file the timestamp and the value of the current sample,but there is a problem : even I've put some spaces between the time and the value and it seems that they are in different columns,they are actualy on the same column of the xls,it's just expanded and covers the next column (I can put a print screen if you don't understand).How can I make it print the data of time and amplitude in two different columns?Here's my code of the class which creates the file and saves the data on xls :
Code:
package soundRecording;
import java.io.File;
import java.util.Formatter;
public class Save {
static Formatter y;
public static void createFile() {
Date thedate = new Date();
final String folder = thedate.curDate();
final String fileName = thedate.curTime();
try {
String name = "Time_"+fileName+".csv";
y = new Formatter(name);
File nof = new File(name);
nof.createNewFile();
System.out.println("A new file was created.");
}
catch(Exception e) {
System.out.println("There was an error.");
}
}
public void addValues(byte audio) {
Date d = new Date();
y.format("%s " + " %s%n",d.curTime(), audio);
}
public void closeFile() {
y.close();
}
}

Related

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: Why are my images coming in so blurry?

I have a Slideshow for the Home Page of my app looks sorta like the Houzz apps Home Page, were it displays a new image daily. But their is one issue I am having is that all of my images are coming in so blurry. I've checked the Resolution and it shouldn't be that blurry for no reason at all. I've tried changing setScaleType such as switching it too CENTER, CENTER_CROP, and Etc... None of those seemed to work. I have tried everything too my knowledge and now I am stuck, Below are some of my relevant source code in order too successfully help me out on this issue.
This is the Home.java this is linked/runs functions of homebck.xml:
Code:
public class Home extends Fragment {
private final int FileUpload = 100;
public static final String URL =
private Context context;
private ImageView m_imageInformation;
private ImageView m_imageSave;
private ImageView m_imageWallPaper;
private ViewPager m_viewPager;
private ImageAdapter m_imageAdapter;
private ArrayList<ImageView> m_imageViewList;
private int[] m_galleryImages = new int[]{
R.drawable.ic_share,
R.drawable.ic_share,
R.drawable.ic_share
};
public static String popup_status = "";
public static File path = new File(Environment.getExternalStorageDirectory() + "");
public static Item[] fileList;
public static String chosenFile;
public static Boolean firstLvl = true;
ListAdapter adapter;
public static ArrayList<String> str = new ArrayList<String>();
public String dbPath = "/data/data/com.Celebration/";
private AboutPopup m_aboutPopup;
private InformationPopup m_informationPopup;
public static String ss;
public static List<DBManager.ImageModel> m_images;
public ImageLoader imageLoader;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
// super.onCreateView(inflater, container, savedInstanceState);
context = getActivity();
View rootView = inflater.inflate(R.layout.homebck, container, false);
m_viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
m_imageInformation = (ImageView) rootView.findViewById(R.id.image_information);
m_imageSave = (ImageView) rootView.findViewById(R.id.image_save);
m_imageWallPaper = (ImageView) rootView.findViewById(R.id.image_wallpaper);
initView();
m_imageInformation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Globals.imageNumber = m_viewPager.getCurrentItem();
m_informationPopup.showAtLocation(m_viewPager, 0, 0);
}
});
m_imageSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFileList();
onCreateDialog(100);
}
});
m_imageWallPaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//sendIntent.setAction(Intent.ACTION_CHOOSER);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
sendIntent.putExtra(Intent.EXTRA_EMAIL, "");
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hello, I wanted to invite you to join this app with me! It's a guide about Celebration, FL. Come see ");
sendIntent.setType("text/plain");
//Sipdroid.this.startActivity(sendIntent);*/
context.startActivity(Intent.createChooser(sendIntent, "Tell a friend via..."));
}
});
return rootView;
}
public void initView(){
m_imageViewList = new ArrayList<ImageView>();
m_aboutPopup = new AboutPopup(getActivity());
m_informationPopup = new InformationPopup(getActivity());
Globals.m_dbMan = new DBManager(context);
m_images = Globals.m_dbMan.getImageListData();
m_imageViewList.clear();
if(m_images != null){
for (int i = m_images.size() - 1 ; i >= 0; i--) {
ImageView imageView = new ImageView(context);
setImage(imageView, i);
m_imageViewList.add(imageView);
}
}else{
ImageView imageView = new ImageView(context);
imageLoader = new ImageLoader(context);
imageLoader.DisplayImage(URL, imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
m_imageViewList.add(imageView);
}
m_imageAdapter = new ImageAdapter(m_imageViewList);
m_viewPager.setAdapter(m_imageAdapter);
}
public void setImage(ImageView m_imgView, int currentIndex)
{
File imgFile = new File(m_images.get(currentIndex).imagePath);
//Uri uri = Uri.fromFile(new File(lstImage.get(currentIndex).imagePath));
Bitmap myBitmap = decodeFile(imgFile);
m_imgView.setImageBitmap(myBitmap);
m_imgView.setAdjustViewBounds(true);
m_imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
public static Bitmap decodeFile(File f){
Bitmap b = null;
int IMAGE_MAX_SIZE = 1000;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
int maxwh = Math.max(o.outWidth,o.outHeight);
while(maxwh / scale > IMAGE_MAX_SIZE)
scale *= 2;
}
Log.d("twinklestar.containerrecog", "width: " + o.outWidth + "height: " + o.outHeight + "scale:" + scale);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
/* @Override
public void onClick(View v) {
Log.d("onclick", "ok");
switch (v.getId()){
case R.id.image_information:
{
Toast.makeText(context, "ok", Toast.LENGTH_SHORT).show();
break;
}
case R.id.image_save:
{
// loadFileList();
onCreateDialog(100);
break;
}
case R.id.image_wallpaper:
{
((Activity)context).finish();
break;
}
default:
break;
}
}*/
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
if (fileList == null) {
Log.e("TAG", "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case FileUpload:
builder.setTitle("Select a Folder to save");
builder.setPositiveButton("download", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ImageView image = new ImageView(context);
imageLoader = new ImageLoader(context);
Globals.downloadFlag = true;
Globals.downlaodForSaving = true;
Globals.saveFolder = path.toString();
imageLoader.DisplayImage(URL, image);
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
dialog.dismiss();
onCreateDialog(FileUpload);
Log.d("TAG", path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
//UploadFragment.this.getActivity().removeDialog(DIALOG_LOAD_FILE);
dialog.dismiss();
onCreateDialog(FileUpload);
//UploadFragment.this.getActivity().showDialog(DIALOG_LOAD_FILE);
Log.d("TAG", path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
//Toast.makeText(UploadFragment.this.getActivity(), chosenFile, Toast.LENGTH_SHORT).show();
ss = path.getAbsolutePath() + "/" + chosenFile;
String extension = chosenFile.substring(chosenFile.indexOf(".") + 1);
if (extension.equals("png") || extension.equals("jpg") || extension.equals("bmp")) {
dialog.dismiss();
m_aboutPopup.showAtLocation(m_viewPager, 0, 0);
// onUpload(ss,chosenFile);
} else
Toast.makeText(getActivity(), "This is not image file!", Toast.LENGTH_SHORT).show();
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
Below this a SNIPPET/part of the MainActivity.java *hint URL1,2,3,4... Grabs the URL that is put into String:
Code:
public static String des;
public String myurl = null;
public class AboutPopup implements View.OnClickListener {
public View parent;
public PopupWindow popupWindow;
public ListView m_listHolder;
public EditText m_editDescription;
public Button m_btnUpload;
public DatePicker dp;
public TimePicker tp;
private PendingIntent pendingIntent;
private Spinner spinner;
private ImageView imageView;
private TextView selectImageurl;
private TextView imageDescription;
public AboutPopup(Context paramContext) {
this.parent = ((LayoutInflater) paramContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.settting_popup, null);
//this.parent.findViewBy)
this.popupWindow = new PopupWindow(this.parent, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
this.m_editDescription = (EditText) parent.findViewById(R.id.setting_description);
this.m_btnUpload = (Button) parent.findViewById(R.id.btn_setting_show);
m_btnUpload.setOnClickListener(this);
selectImageurl = (TextView) parent.findViewById(R.id.select_imageurl);
imageDescription = (TextView) parent.findViewById(R.id.image_description);
selectImageurl.setTextSize(convertFromDp(24));
imageDescription.setTextSize(convertFromDp(24));
dp = (DatePicker) parent.findViewById(R.id.datePicker);
tp = (TimePicker) parent.findViewById(R.id.timePicker);
dp.setCalendarViewShown(false);
imageView = (ImageView)parent.findViewById(R.id.setting_image);
spinner = (Spinner) parent.findViewById(R.id.setting_spinner);
String[] platforms = paramContext.getResources(). getStringArray(R.array.dev_platforms);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(paramContext, R.layout.spinner_item, platforms);
spinner.setAdapter(adapter);
// If you want to continue on that TimeDateActivity
// If you want to go to new activity that code you can also write here
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
myurl = URL;
break;
case 1:
myurl = URL1;
break;
case 2:
myurl = URL3;
break;
case 3:
myurl = URL4;
break;
case 4:
break;
}
if(myurl != null){
imageLoader = new ImageLoader(MainActivity.this);
imageLoader.DisplayImage(myurl, imageView);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void showAtLocation(View pView, int left, int top) {
this.popupWindow.setOutsideTouchable(true);
this.popupWindow.setTouchable(true);
this.popupWindow.update();
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setAnimationStyle(R.style.PopupAnimation);
popupWindow.setWidth((int) (pView.getWidth() * 0.95));
popupWindow.setHeight((int) (pView.getHeight()));
popupWindow.showAtLocation(pView, Gravity.CENTER_VERTICAL, 0, 0);
// this.popupWindow.showAtLocation(pView, Gravity.CENTER, left, top);
}
public void hide() {
this.popupWindow.dismiss();
}
public boolean isVisible() {
return this.popupWindow.isShowing();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_setting_show: {
imageLoader = new ImageLoader(MainActivity.this);
Globals.downloadFlag = true;
imageLoader.DisplayImage(myurl, imageView);
ss = path.getAbsolutePath() + "/" + ImageLoader.fname;
des = this.m_editDescription.getText().toString();
Globals.alarmFileName[Globals.alarmNumber] = ImageLoader.fname;
Globals.alarmDescription[Globals.alarmNumber] = des;
Globals.alarmNumber = Globals.alarmNumber + 1;
String strDateTime = dp.getYear() + "-" + (dp.getMonth() + 1) + "-" + dp.getDayOfMonth();
Intent Intent = new Intent(MainActivity.this, AlarmReceiver.class);
Intent.putExtra("id",Globals.alarmNumber-1);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, Intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),tp.getCurrentHour(), tp.getCurrentMinute());
Calendar current = Calendar.getInstance();
if(current.get(Calendar.YEAR) > cal.get(Calendar.YEAR) && current.get(Calendar.MONTH) > cal.get(Calendar.MONTH) && current.get(Calendar.DATE) > cal.get(Calendar.DATE)){
Toast.makeText(MainActivity.this, "Please select other time", Toast.LENGTH_SHORT).show();
return;
}
// schedule for every 30 seconds
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
if (des == null) {
Toast.makeText(MainActivity.this, "Input description in..", Toast.LENGTH_SHORT).show();
return;
} else {
popupWindow.dismiss();
}
}
break;
}
}
}
homebck.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/homefragment"
android:background="@color/white">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1">
<ImageView
android:id="@+id/image_information"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_information"
android:layout_weight="1" />
<ImageView
android:id="@+id/image_save"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_save"
android:layout_weight="1"
/>
<ImageView
android:id="@+id/image_wallpaper"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_share"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>

Unable to display images in webView while epub Rendering using epublib.

Here is the code of my epub parser class.
public class EPubParser extends AppCompatActivity {
String path = null;
Book book = null;
String linez = null;
TextView textView;
private int pxScreenWidth;
int textSize = 12;
Drawable imageAsDrawable;
List<String> spineElements;
List<SpineReference> spineList;
@SuppressLint("SetJavaScriptEnabled")
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.layout_epub_render);
getSupportActionBar().setTitle("EPub Reader");
WebView webView = (WebView) findViewById(R.id.web_view);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
//to get Path
Intent intent = this.getIntent();
if (intent.getAction() != null) {
path = intent.getData().getPath();
} else {
path = intent.getExtras().getString("PATH");
}
try {
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
EpubReader epubReader = new EpubReader();
book = epubReader.readEpub(fileInputStream);
} catch (Exception e) {
Log.e("While loading book ", e.toString());
}
//loading the contents
Spine spine = book.getSpine();
spineList = spine.getSpineReferences();
int count = spineList.size();
//gathering all data from spine
StringBuilder string = new StringBuilder();
for (int i = 0; i < count; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = null;
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {
e.printStackTrace();
}
//do with stream
} catch (IOException e) {
e.printStackTrace();
}
// linez = linez.replace("../", "");
webView.loadDataWithBaseURL(null, linez, "text/html", "UTF-8", null);
webView.getSettings().setBuiltInZoomControls(true);
}
}
}
Please help.

Editing the stock MTC Manager

Hey guys, I have a xtrons px5 mtcd head unit and I am trying to figure out without flashing to a custom ROM, how to edit what apps launch at wake, or do not turn off with the unit when it goes to sleep.
I believe it is the MTCManager that is doing these actions, and I have found two interesting parts of the decomplied code.
The first file is android/microntek/a.java
HTML:
package android.microntek;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.microntek.service.R;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import java.util.ArrayList;
public class a {
static String cp;
private static boolean cq = false;
static Context cr;
private static int cs = -1;
static Toast ct;
private static final String[] cu = new String[]{"android.microntek.", "com.murtas.", "com.microntek.", "com.goodocom.gocsdk", "android.rockchip.update.service", "com.android.systemui", "com.hct.obd.OBDActivity", "com.unisound", "com.dpadnavi.assist", "com.intel.thermal", "cn.manstep.phonemirror", "com.hiworld.", "com.carboy.launch", "com.android.bluetooth", "net.easyconn", "com.android.launcher", "com.google.android", "com.vayosoft.carsystem"};
static Object cv = new Object();
static a cw;
private static final String[] cx = new String[]{"android.microntek.", "com.murtas.", "com.microntek.", "com.goodocom.gocsdk", "android.rockchip.update.service", "com.android.systemui", "com.hct.obdservice.OBDService", "com.unisound", "com.intel.thermal", "com.dpadnavi.assist", "cn.manstep.phonemirror", "com.android.bluetooth", "com.hiworld.", "net.easyconn", "android.cn.ecar.cds.process.CoreService", "com.google.android", "com.vayosoft.carsystem"};
private a(Context context) {
cr = context;
}
private int ex(Context context) {
int i = 0;
Iterable<e> arrayList = new ArrayList();
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
for (RunningAppProcessInfo runningAppProcessInfo : activityManager.getRunningAppProcesses()) {
int i2 = runningAppProcessInfo.pid;
int i3 = runningAppProcessInfo.uid;
String str = runningAppProcessInfo.processName;
int i4 = activityManager.getProcessMemoryInfo(new int[]{i2})[0].dalvikPrivateDirty;
e eVar = new e();
eVar.fy(i2);
eVar.fz(i3);
eVar.ga(i4);
eVar.gb(str);
eVar.dk = runningAppProcessInfo.pkgList;
arrayList.add(eVar);
String[] strArr = runningAppProcessInfo.pkgList;
}
for (e eVar2 : arrayList) {
int i5;
if (eVar2.gc() < 10000) {
i5 = i;
} else {
String gd = eVar2.gd();
if (gd.indexOf(".") == -1) {
i5 = i;
} else if (fe(gd) || ff(context, gd) || fg(context, gd)) {
i5 = i;
} else if (cs != 0 || fd(gd)) {
try {
activityManager.killBackgroundProcesses(gd);
i5 = i + 1;
} catch (Exception e) {
System.out.println(" deny the permission");
i5 = i;
}
} else {
ez(gd);
i5 = i + 1;
}
}
i = i5;
}
return i;
}
private void ey(Context context) {
Iterable<RunningServiceInfo> runningServices = ((ActivityManager) context.getSystemService("activity")).getRunningServices(100);
System.out.println(runningServices.size());
Iterable<b> arrayList = new ArrayList();
for (RunningServiceInfo runningServiceInfo : runningServices) {
int i = runningServiceInfo.pid;
int i2 = runningServiceInfo.uid;
String str = runningServiceInfo.process;
long j = runningServiceInfo.activeSince;
int i3 = runningServiceInfo.clientCount;
ComponentName componentName = runningServiceInfo.service;
String shortClassName = componentName.getShortClassName();
String packageName = componentName.getPackageName();
PackageManager packageManager = context.getPackageManager();
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
b bVar = new b();
bVar.fh(applicationInfo.loadIcon(packageManager));
bVar.fi(applicationInfo.loadLabel(packageManager).toString());
bVar.fj(shortClassName);
bVar.fk(packageName);
Intent intent = new Intent();
intent.setComponent(componentName);
bVar.fl(intent);
bVar.fm(i);
bVar.fn(i2);
bVar.fo(str);
arrayList.add(bVar);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
for (b bVar2 : arrayList) {
if (bVar2.fp() >= 10000) {
String fq = bVar2.fq();
if (!(fd(fq) || ff(context, fq) || fg(context, fq))) {
if (cs != 0 || fe(fq)) {
try {
context.stopService(bVar2.fr());
} catch (SecurityException e2) {
System.out.println(" deny the permission");
}
} else {
ez(fq);
}
}
}
}
}
private long fa(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
MemoryInfo memoryInfo = new MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
return memoryInfo.availMem;
}
public static a fc(Context context) {
a aVar;
synchronized (cv) {
if (cw == null) {
cw = new a(context);
}
cs = -1;
aVar = cw;
}
return aVar;
}
private boolean fd(String str) {
for (String startsWith : cx) {
if (str.startsWith(startsWith)) {
return true;
}
}
return cp != null && str.equals(cp);
}
private boolean fe(String str) {
for (String startsWith : cu) {
if (str.startsWith(startsWith)) {
return true;
}
}
return cp != null && str.equals(cp);
}
private boolean ff(Context context, String str) {
if (context == null || TextUtils.isEmpty(str)) {
return false;
}
for (InputMethodInfo packageName : ((InputMethodManager) context.getSystemService("input_method")).getInputMethodList()) {
if (str.equalsIgnoreCase(packageName.getPackageName())) {
return true;
}
}
return false;
}
private boolean fg(Context context, String str) {
try {
for (ResolveInfo resolveInfo : context.getPackageManager().queryIntentServices(new Intent("android.service.wallpaper.WallpaperService"), 128)) {
if (str.equalsIgnoreCase(resolveInfo.serviceInfo.packageName)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void ew(int i, String str) {
cs = i;
cq = true;
cp = str;
long fa = fa(cr);
ey(cr);
int ex = ex(cr);
long fa2 = fa(cr);
if (i == 1) {
fa = Math.abs(fa2 - fa);
CharSequence string = cr.getString(R.string.clear_message, new Object[]{Integer.valueOf(ex), Formatter.formatFileSize(cr, fa)});
if (ct == null) {
ct = Toast.makeText(cr, string, 0);
} else {
ct.cancel();
ct = Toast.makeText(cr, string, 1);
}
ct.show();
}
cq = false;
}
public void ez(String str) {
if (str != null && str.length() != 0) {
try {
((ActivityManager) cr.getSystemService("activity")).forceStopPackage(str);
} catch (SecurityException e) {
System.out.println(" deny the permission");
}
}
}
public boolean fb() {
return cq;
}
}
it appears as though it is listing which apps either stay awake on sleep, or launch at boot. Can anybody confirm this?
And in this file, it looks like it might be controlling the apps in the apploop, maybe...
file is android/microntek/c.java
HTML:
package android.microntek;
import android.microntek.service.R;
public class c {
public static final String[] dg = new String[]{"com.microntek.avin", "com.microntek.dvr", "com.microntek.dvd", "com.microntek.tv", "com.microntek.media", "com.microntek.music", "com.microntek.radio", "com.microntek.ipod", "com.microntek.btMusic", "com.microntek.bluetooth", "com.microntek.civxusb", "com.microntek.tv", "com.microntek.dvr"};
public static final String[] dh = new String[]{"com.microntek.avin", "com.microntek.dvr", "com.microntek.dvd", "com.microntek.tv", "com.microntek.media", "com.microntek.music", "com.microntek.radio", "com.microntek.ipod", "com.microntek.btMusic", "com.microntek.dvr"};
public static final String[] di = new String[]{"com.microntek.radio", "com.microntek.dvd", "com.microntek.music", "com.microntek.media", "com.microntek.ipod", "com.microntek.avin"};
public static final int[] dj = new int[]{R.string.music_style0, R.string.music_style1, R.string.music_style2, R.string.music_style3, R.string.music_style4, R.string.music_style5, R.string.music_style6};
}
Let me know what you guys think.
You are absolutely correct. Check out the thread on the Malaysk ROM for the PX5. A member, Nico84, is working with the same files. You guys may want to join forces on this.
Johan
Thanks for that, does that work on the Stock firmware, or only on Malaysk's Custom ROM?
Not sure, but I believe it will work on stock. Needs to be rooted I suppose. Contact Nico84 for details, I am not an experienced Android developer.
I did, thanks for the lead on that, exactly what I was looking for. It looks like it should work on stock firmware so ill probably give it a try
So I took Nico84's MTCManager and tried to decompile and add spotify and accuweather to it, and recompile it. But then the actualy MTCManager did not work, so not sure what I did wrong.
semaj4712 said:
So I took Nico84's MTCManager and tried to decompile and add spotify and accuweather to it, and recompile it. But then the actualy MTCManager did not work, so not sure what I did wrong.
Click to expand...
Click to collapse
You have to compile it with original signature, not testkeys. You can use "tickle my android"
Bummer, tickle my android does not seem to work on mac which is all I have, is there any other way to compile with original signature with apktools? Or would it be possible to make me a version that allows spotify and accuweather to remain open, that would be great.
Ok so I found the documentation on signatures for the APKtool, but it still didnt work. Just to be clear I started this command
Code:
apktool d MTCManager.apk
then I made the changes to the smali.d file, and then recompiled with this command
Code:
apktool b MTCManager/ -c
Is there something I am doing wrong? (The location of files is not exact, bare in mind I am doing this on a mac via terminal so I simply drag and drop the file which returns the path it needs.)
On second try I was able to get this to work. The above commands worked perfectly, my guess is I messed something up the first time around.
For PX3:
when the unit comes back from sleep it sends Intent com.cayboy.action.ACC_ON
when it goes to sleep it sends com.cayboy.action.ACC_OFF

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