[Q] Probably easy but...accelerometer and random generator - General Questions and Answers

Trying to use a random image generator as an action if accelerometer is utilized....different image each time the phone is shook.
import java.util.Random;
import android.app.Activity;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class ShakeActivity extends Activity implements SensorListener {
// For shake motion detection.
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 800;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// start motion detection
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
}
}
protected void onPause() {
if (sensorMgr != null) {
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
sensorMgr = null;
}
super.onPause();
}
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(int sensor, float[] values) {
Log.d("sensor", "onSensorChanged: " + sensor);
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
x = values[SensorManager.DATA_X];
y = values[SensorManager.DATA_Y];
z = values[SensorManager.DATA_Z];
float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
// Log.d("sensor", "diff: " + diffTime + " - speed: " + speed);
if (speed > SHAKE_THRESHOLD) {
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
}
Thanks in advance for help?

Related

HELP - Image Gallery In gridview to display images from spicifc folder on sdcard

I have done a lot of searching and I have come up with this code to try and display images that are located in a Folder on my SDCard. The folder is located at /.data/ToDo/.nomedia/ (I am trying to hide this images from the Main Android Gallery) The Code seems to run fine, i don't get any errors, but it's just not displaying the images. I was hoping someone could tell me what I am missing. Any Help would be greatly appreciated!!
Here is my GalleryActivity
Code:
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor, cursor;
private int image_column_index, actual_image_column_index;
File sdCardDir = Environment.getExternalStorageDirectory(); //SDCard Location
String imagesDir = ("sdCardDir" + "/.data/ToDo/.nomedia/"); //Path to Images
GridView imagegrid;
private int count;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Media._ID };
imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img, MediaStore.Images.Media.DATA + " like ? ", new String[] {imagesDir}, null);
image_column_index = imagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.sdcard);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,null, null, null);
actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), GalleryFlow.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
int imageID = 0;
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
//i.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID)));
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}

[Q] Building Nyandroid + platlogo into an app

I've been hacking away at a few java files (PlatlogoActivity.java, Nyandroid.java) extracted from AOSP ICS source in Eclipse. There were some errors that I was able to solve (some funky ones about vibration, but I just removed all code related to vibration instead) but now there is one error, that no matter what, I can't solve. In the Nyandroid.java, I keep on getting the error "Cannot cast from TimeAnimator to ValueAnimator" on the line "((ValueAnimator) mAnim).cancel();" no matter how much I try changing that line (for example to "mAnim.cancel();") based on some custom ROM sources that I've looked through, and some stackoverflow questions. The app source is attached to this post, and below you can find the Nyandroid.java if you're willing to help - please do. I want to get into app developing for Android, or atleast understanding some java. I managed to port the Gingerbread platlogo for all Android versions but it's obviously much easier to do because it's just one still image and a toast. But I really want to port the ICS Nyandroid easter egg, for some practice with java.
/*);
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.nyandroid;
import android.animation.AnimatorSet;
import android.animation.PropertyValuesHolder;
import android.animation.ObjectAnimator;
import android.animation.TimeAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import java.util.HashMap;
import java.util.Random;
public class Nyandroid extends Activity {
final static boolean DEBUG = false;
public static class Board extends FrameLayout
{
public static final boolean FIXED_STARS = true;
public static final int NUM_CATS = 20;
static Random sRNG = new Random();
static float lerp(float a, float b, float f) {
return (b-a)*f + a;
}
static float randfrange(float a, float b) {
return lerp(a, b, sRNG.nextFloat());
}
static int randsign() {
return sRNG.nextBoolean() ? 1 : -1;
}
static <E> E pick(E[] array) {
if (array.length == 0) return null;
return array[sRNG.nextInt(array.length)];
}
public class FlyingCat extends ImageView {
public static final float VMAX = 1000.0f;
public static final float VMIN = 100.0f;
public float v, vr;
public float dist;
public float z;
public ComponentName component;
public FlyingCat(Context context, AttributeSet as) {
super(context, as);
setImageResource(R.drawable.nyandroid_anim); // @@@
if (DEBUG) setBackgroundColor(0x80FF0000);
}
public String toString() {
return String.format("<cat (%.1f, %.1f) (%d x %d)>",
getX(), getY(), getWidth(), getHeight());
}
public void reset() {
final float scale = lerp(0.1f,2f,z);
setScaleX(scale); setScaleY(scale);
setX(-scale*getWidth()+1);
setY(randfrange(0, Board.this.getHeight()-scale*getHeight()));
v = lerp(VMIN, VMAX, z);
dist = 0;
// android.util.Log.d("Nyandroid", "reset cat: " + this);
}
public void update(float dt) {
dist += v * dt;
setX(getX() + v * dt);
}
}
TimeAnimator mAnim;
public Board(Context context, AttributeSet as) {
super(context, as);
setLayerType(View.LAYER_TYPE_HARDWARE, null);
setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
setBackgroundColor(0xFF003366);
}
private void reset() {
// android.util.Log.d("Nyandroid", "board reset");
removeAllViews();
final ViewGroup.LayoutParams wrap = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
if (FIXED_STARS) {
for(int i=0; i<20; i++) {
ImageView fixedStar = new ImageView(getContext(), null);
if (DEBUG) fixedStar.setBackgroundColor(0x8000FF80);
fixedStar.setImageResource(R.drawable.star_anim); // @@@
addView(fixedStar, wrap);
final float scale = randfrange(0.1f, 1f);
fixedStar.setScaleX(scale); fixedStar.setScaleY(scale);
fixedStar.setX(randfrange(0, getWidth()));
fixedStar.setY(randfrange(0, getHeight()));
final AnimationDrawable anim = (AnimationDrawable) fixedStar.getDrawable();
postDelayed(new Runnable() {
public void run() {
anim.start();
}}, (int) randfrange(0, 1000));
}
}
for(int i=0; i<NUM_CATS; i++) {
FlyingCat nv = new FlyingCat(getContext(), null);
addView(nv, wrap);
nv.z = ((float)i/NUM_CATS);
nv.z *= nv.z;
nv.reset();
nv.setX(randfrange(0,Board.this.getWidth()));
final AnimationDrawable anim = (AnimationDrawable) nv.getDrawable();
postDelayed(new Runnable() {
public void run() {
anim.start();
}}, (int) randfrange(0, 1000));
}
if (mAnim != null) {
((ValueAnimator) mAnim).cancel();
}
mAnim = new TimeAnimator();
mAnim.setTimeListener(new TimeAnimator.TimeListener() {
public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) {
// setRotation(totalTime * 0.01f); // not as cool as you would think
// android.util.Log.d("Nyandroid", "t=" + totalTime);
for (int i=0; i<getChildCount(); i++) {
View v = getChildAt(i);
if (!(v instanceof FlyingCat)) continue;
FlyingCat nv = (FlyingCat) v;
nv.update(deltaTime / 1000f);
final float catWidth = nv.getWidth() * nv.getScaleX();
final float catHeight = nv.getHeight() * nv.getScaleY();
if ( nv.getX() + catWidth < -2
|| nv.getX() > getWidth() + 2
|| nv.getY() + catHeight < -2
|| nv.getY() > getHeight() + 2)
{
nv.reset();
}
}
}
});
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
super.onSizeChanged(w,h,oldw,oldh);
// android.util.Log.d("Nyandroid", "resized: " + w + "x" + h);
post(new Runnable() { public void run() {
reset();
mAnim.start();
} });
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAnim.cancel();
}
@Override
public boolean isOpaque() {
return true;
}
}
private Board mBoard;
@Override
public void onStart() {
super.onStart();
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
);
}
@Override
public void onResume() {
super.onResume();
mBoard = new Board(this, null);
setContentView(mBoard);
mBoard.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int vis) {
if (0 == (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)) {
Nyandroid.this.finish();
}
}
});
}
@Override
public void onUserInteraction() {
// android.util.Log.d("Nyandroid", "finishing on user interaction");
finish();
}
}
Click to expand...
Click to collapse

[App] [Tutorial] Learn to make a Compass Application

Hello,
I create this post to present you a video tutorial showing you how to create a compass application for Android steps by steps. This tutorial lets beginners to start with sensors on Android and also to discover how to get GPS Location with default Android services.
Tutorial is here :
A demo application is also available on Google Play Store : https://play.google.com/store/apps/details?id=com.ssaurel.tinycompass
Don't hesitate to tell me if you want more details about the source code.
Sylvain
Compass View source code
Hello,
To start with source code, this is CompassView source code :
Code:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import com.ssaurel.tinycompass.R;
/**
* Compass view.
*
* @author Sylvain Saurel - [email protected]
*
*/
public class CompassView extends View {
private static final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int width = 0;
private int height = 0;
private Matrix matrix;
private Bitmap bitmap;
private float bearing;
public CompassView(Context context) {
super(context);
initialize();
}
public CompassView(Context context, AttributeSet attr) {
super(context, attr);
initialize();
}
private void initialize() {
matrix = new Matrix();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass_icon);
}
public void setBearing(float bearing) {
this.bearing = bearing;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
if (bitmap.getWidth() > canvasWidth || bitmap.getHeight() > canvasHeight) {
// resize to fit canvas
bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmapWidth * .85), (int) (bitmapHeight * .85), true);
}
// calculate center position
int bitmapX = bitmap.getWidth() / 2;
int bitmapY = bitmap.getHeight() / 2;
int parentX = width / 2;
int parentY = height / 2;
int centerX = parentX - bitmapX;
int centerY = parentY - bitmapY;
// rotation angle
int rotation = (int) (360 - bearing);
// transformation matrix
matrix.reset();
// rotate on center to put on North
matrix.setRotate(rotation, bitmapX, bitmapY);
// translate bitmap to center
matrix.postTranslate(centerX, centerY);
// draw bitmap
canvas.drawBitmap(bitmap, matrix, paint);
}
}
Don't hesitate if you have comments .
Sylvain
Hello,
A blog article to complete the video tutorial is also available now : http://www.ssaurel.com/blog/learn-how-to-make-a-compass-application-for-android/
Sylvain

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);
}
}

Multiple permissions in android studio

I want to display in sequence the permissions for each item. I have the following code: I have my main activity first and i show you my other code for the permissions which is the same for each item.
package com.example.crediluca;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.crediluca.gps.Permissions;
import com.example.crediluca.extraer.extraePersonas;
import com.example.crediluca.extraer.extraeLlamadas;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
// Permisos para la ubicacion
private Permissions permissions_gps = new Permissions(this);
//Permisos para extraer contactos
private extraePersonas personas_contacts = new extraePersonas(this);
//Permisos para extraer llamadas
private extraeLlamadas llamadas_log = new extraeLlamadas(this);
// private extraePersonas extraigoPersona = new extraePersonas(context:this) ;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ex.fetchContacts();
//ex.getCallDetails();
if (! permissions_gps.checkPermissions())
{
permissions_gps.requestPermissions();
//permissions.notificationResult();
}
if (! personas_contacts.checkPermissions())
{
personas_contacts.requestPermissions();
}
if (! llamadas_log.checkPermissions())
{
llamadas_log.requestPermissions();
}
//Vlidacion de los permisos de ubicacion
}
}
//--------------------------------------------------------------ANOTHER FILE which is basically the same permissions for my other items------------------------------------------------------------------------------------//
public class extraePersonas extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 79;
private Context context;
//public extraePersonas(Context context) {this.context = context; }
public extraePersonas(Activity activity) {this.context = activity; }
//------------------------------
public boolean checkPermissions() {
int variablePersona = ActivityCompat.checkSelfPermission(
(Activity) context, Manifest.permission.READ_CONTACTS);
return (variablePersona == PackageManager.PERMISSION_GRANTED);
}
public void requestPermissions() {
boolean shouldProvideRationale = checkPermissions();
if (shouldProvideRationale) {
Log.i(TAG, "Mostrando los permisos que debe otorgar.");
Snackbar.make(
findViewById(R.id.activity_main),
R.string.permission_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
@override
public void onClick(View view) {
// Peticion de permisos
ActivityCompat.requestPermissions((Activity) context,
new String[] {
Manifest.permission.READ_CONTACTS,
},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
})
.show();
} else {
Log.i(TAG, "Pidiendo permisos");
ActivityCompat.requestPermissions((Activity) context,
new String[] {
Manifest.permission.READ_CONTACTS },
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
//---------------------------------
//-------------------------------------
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
Log.i("@codekul", "Name - " + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = context.getContentResolver().query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
Log.i("@codekul", "Phone number: " + phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor = context.getContentResolver().query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\nEmail:" + email);
Log.i("@codekul", "Email: " + email);
}
emailCursor.close();
}
output.append("\n");
}
}
}
}
So, what's your question?

Categories

Resources