How to detect face in realtime by opencv? - android

Here is the code but camera not showing any square on face(NO error in code)
everything else is working fine, app is opening camera is also opening.
i have search a lot online but i m not able to solve so please help it is very important........
package com.phoenixer.nao.opencv2;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private CameraBridgeViewBase cameraBridgeViewBase;
private CascadeClassifier cascadeClassifier;
private Mat grayscaleImage;
private int absoluteFaceSize;
private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
initializeOpenCVDependencies();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
private void initializeOpenCVDependencies() {
try {
// Copy the resource into a temp file so OpenCV can load it
InputStream is = getResources().openRawResource(R.raw.activity_opencv_camera2);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
File mCascadeFile = new File(cascadeDir, "activity_opencv_camera2.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
// Load the cascade classifier
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
} catch (Exception e) {
Log.e("OpenCVActivity", "Error loading cascade", e);
}
// And we are ready to go
cameraBridgeViewBase.enableView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
cameraBridgeViewBase = new JavaCameraView(this, -1);
setContentView(cameraBridgeViewBase);
cameraBridgeViewBase.setCvCameraViewListener(this);
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
#Override
public void onCameraViewStarted(int width, int height) {
grayscaleImage = new Mat(height, width, CvType.CV_8UC4);
// The faces will be a 20% of the height of the screen
absoluteFaceSize = (int) (height * 0.2);
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(Mat inputFrame) {
// Create a grayscale image
Imgproc.cvtColor(inputFrame, grayscaleImage, Imgproc.COLOR_RGBA2RGB);
MatOfRect faces = new MatOfRect();
// Use the classifier to detect faces
if (cascadeClassifier != null) {
cascadeClassifier.detectMultiScale(grayscaleImage, faces, 1.1, 2, 2,
new Size(absoluteFaceSize, absoluteFaceSize), new Size());
}
// If there are any faces found, draw a rectangle around it
Rect[] facesArray = faces.toArray();
for (int i = 0; i <facesArray.length; i++)
Imgproc.rectangle(inputFrame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0, 255), 6);
return inputFrame;
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_2_0, this,baseLoaderCallback);
}
}

Related

Trying to save WebView to PDF in Android is there a way i can save the captured bitmap to the pdf

Trying to save WebView to PDF in Android is there a way i can save the captured bitmap to pdf
How to save the captured bitmap in pdf not getting with my code
Is there any way to save webview contents to PDF
Shared Code Below
MainActivity.java
package com.example.webviewtopdf;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.drawable.PictureDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
Bitmap bmp;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "You PDF was Saved Successfully", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
myWebView.capturePicture();
}
});
myWebView = (WebView) findViewById(R.id.mywebview);
// myWebView.setPictureListener(new WebView.PictureListener() {
//
// public void onNewPicture(WebView view, Picture picture) {
// if (picture != null) {
// try {
// Bitmap bmp = pictureDrawable2Bitmap(new PictureDrawable(picture));
// FileOutputStream out = new FileOutputStream(filename);
// bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
// out.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// });
myWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
// Picture picture = myWebView.capturePicture();
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream( "/sdcard/" + "page.pdf" );
if ( fos != null ) {
b.compress(Bitmap.CompressFormat.JPEG, 100, fos );
fos.close();
}
}
catch( Exception e ) {
System.out.println("-----error--"+e);
}
}
});
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.yahoo.com");
}
private static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable) {
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth()
, pictureDrawable.getIntrinsicHeight()
, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}
}
You are currently only capturing an image, which is a BitMap and not a PDF.
You should try and find / use 3rd party libs that can convert IMG to PDF. If found a working approach on SO answers:
Image to PDF using IText PDF Library

How to read whatsapp message from notification extras

Hi I'm working on an app in which I have to read images from whatsapp. I can read the first image as a bitmap with this line of code:
Bitmap btm = (Bitmap) sbn.getNotification().extras.get(Notification.EXTRA_PICTURE);
The problem is that if I receive more than one images I get null. How can I resolve this?
this is the NotificationListenerService:
package com.etaure.callany.testwhatsappimage;
import android.accounts.AccountManager;
import android.app.Notification;
import android.content.Intent;
import android.graphics.Bitmap;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
/**
* Created by administrator on 03/11/2015.
*/
public class MyNotificationListner extends NotificationListenerService {
static int i = 0;
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
if (sbn.getPackageName().equals("com.whatsapp")) {
Bitmap btm = (Bitmap) sbn.getNotification().extras.get(Notification.EXTRA_PICTURE);
}
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.w("Test", "NotificationRemoved");
}
}
this is a code that parses for you whatsapp images and shows ( if you want ) on your logcat all base64 string! Enjoy
`
if (extras.containsKey(Notification.EXTRA_PICTURE)) {
bmp = (Bitmap) extras.get(Notification.EXTRA_PICTURE);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byteArrayS = byteArrayOutputStream .toByteArray();
encoded = Base64.encodeToString(byteArrayS, Base64.DEFAULT);
final int LOGCAT_MAX_LENGTH = 3950;
if (BuildConfig.DEBUG) {
while (encoded.length() > LOGCAT_MAX_LENGTH) {
int substringIndex = encoded.lastIndexOf(",", LOGCAT_MAX_LENGTH);
if (substringIndex == -1)
substringIndex = LOGCAT_MAX_LENGTH;
Log.d("encode", encoded.substring(0, substringIndex));
encoded = encoded.substring(substringIndex).trim();
}
Log.d("encode", encoded);
}
}
`

Error: "Fatal signal 11 (SIGSEGV), code 1" when passing Mat object from java to jni function

I am running the video camera using the OpenCV function. I pass the Mat object to the jni function it works for awhile, them the error:
10-10 13:03:17.978: A/libc(28693): Fatal signal 11 (SIGSEGV), code 1, fault addr 0x9 in tid 28791 (Thread-5418)
Java code that runs the camera and calls the jni function:
package com.adhamenaya;
import java.util.ArrayList;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
//import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
public class MainActivity extends Activity implements CvCameraViewListener2,
OnTouchListener {
private static final String TAG = "OCVSample::Activity";
private Mat mRgba;
private Mat mGray;
private CameraBridgeViewBase mOpenCvCameraView;
private ArrayList<Mat> mats = new ArrayList<Mat>();
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
mOpenCvCameraView.setOnTouchListener(MainActivity.this);
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
Native.loadlibs();
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.cam_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
Native.setup(mFaceCascadeFile, mNoseCascadeFile, mLandmarks);
}
#Override
public void onPause() {
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this,
mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mGray = new Mat();
mRgba = new Mat();
}
public void onCameraViewStopped() {
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
Imgproc.cvtColor(mRgba, mGray, Imgproc.COLOR_BGRA2GRAY);
Native.runJni(mFaceCascadeFile, mNoseCascadeFile, mLandmarks,
mRgba.getNativeObjAddr());
return mRgba;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
Jni function:
JNIEXPORT jbyteArray JNICALL Java_com_adhamenaya_Native_runJni(JNIEnv * env,
jobject obj, jstring faceCascadeFile, jstring noseCascadeFile,
jstring landmarks, jlong frame) {
cv::Mat& inFrame = *(cv::Mat*) frame;
if (!gsys.loadFaceCascade(faceCascadeFnameStr)) {
LOG("Could not load face cascade");
gsys.loadFaceCascade(faceCascadeFnameStr);
} else {
LOG("Face cascade: OK");
}
if (!gsys.loadNoseCascade(noseCascadeFnameStr)) {
LOG("Could not load nose cascade");
gsys.loadNoseCascade(noseCascadeFnameStr);
} else {
LOG("Nose cascade: OK");
}
gsys.setFrameRate(30);
gsys.setProgramState(DETECT);
clock_t tin, tout = 0;
cv::flip(inFrame, inFrame, 0);
cv::transpose(inFrame, inFrame);
dlib::shape_predictor pose_model;
dlib::deserialize(landmarksStr) >> pose_model;
gsys.setCurrentFrame(inFrame);
tin = clock();
trigger_hr(gsys, faces, pose_model);
// Process the frame
size_t spm;
float motionStrengthX, motionStrengthY;
float phiYaw = -0xFFFFFFFF, thetaPitch = -0xFFFFFFFF;
if (faces.size()) {
faces[0].getSpm(gsys, spm, motionStrengthX, motionStrengthY);
faces[0].getFacePose(phiYaw, thetaPitch);
}
tout = tout + clock() - tin;
if ((gsys.getFrameCount() % 30) == 29) {
double secs_between_frames = (double) (tout) / (CLOCKS_PER_SEC * 30.0f);
printf("FPS = %2.2f\n", 1.0f / secs_between_frames);
LOG("FPS = %2.2f ", 1.0f / secs_between_frames);
tout = 0;
}
char spmText[100];
//sprintf(spmText,
// "SPM = %zu, P = %2.2f, T = %2.2f, MS-X = %2.2f, MS-Y = %2.2f", spm,
// phiYaw, thetaPitch, motionStrengthX, motionStrengthY);
LOG("SPM = %zu, P = %2.2f, T = %2.2f, MS-X = %2.2f, MS-Y = %2.2f", spm,
phiYaw, thetaPitch, motionStrengthX, motionStrengthY);
std::string str;
str = "SPM=";
jbyteArray arr = env->NewByteArray(str.length());
env->SetByteArrayRegion(arr, 0, str.length(), (jbyte*) str.c_str());
return arr;
}
Kindly help me.
After two days of searching online, I could figure out that the problem is because of the 'Memory leak', and this happens when I am reading the frames from a video and send them the jni function, without releasing frames after finishing working on them, so always I will have the frames in the memory.
What I did is to move the Mat object in the C++ code outside the scope of the function and make it a class scope object, so it will not create a new object each time the function is called.
Also, I called:
inFrame.release();
to free the memory after finishing working on it.

How to download .docx file from url in android? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i am trying to download this file from url in android and also save file in SD card ....
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar=(ProgressBar)findViewById(R.id.progressBar1);
new DownloadFileFromURL().execute("http://hrdevcontentapi.spanunit.com/000132/538/HCDocument/the_hatha_yoga_pradipika.docx");
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.docx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
bar.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
File targetFile = new File("/sdcard/downloadedfile.docx");
Uri targetUri = Uri.fromFile(targetFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/*");
startActivityForResult(intent, 100);
}
}
}
This is the activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.test.MainActivity" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
And this is the activity_main.xml
Don't forget to add the following permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For further details check this link:http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
Try using DownloadManager, it's very easy to use and good at long running download tasks.
import java.io.FileInputStream;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ImageView;
public class Test extends Activity
{
private static final String DL_ID = "downloadId";
private SharedPreferences prefs;
private DownloadManager dm;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageView = new ImageView(this);
setContentView(imageView);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
}
#Override
public void onResume() {
super.onResume();
if(!prefs.contains(DL_ID)) {
Uri resource = Uri.parse("http://asdf.com/big.jpg");
DownloadManager.Request request = new DownloadManager.Request(resource);
request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
request.setAllowedOverRoaming(false);
request.setTitle("Download Sample");
long id = dm.enqueue(request);
prefs.edit().putLong(DL_ID, id).commit();
} else {
queryDownloadStatus();
}
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
queryDownloadStatus();
}
};
private void queryDownloadStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(prefs.getLong(DL_ID, 0));
Cursor c = dm.query(query);
if(c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
Log.d("DM Sample","Status Check: "+status);
switch(status) {
case DownloadManager.STATUS_PAUSED:
case DownloadManager.STATUS_PENDING:
case DownloadManager.STATUS_RUNNING:
break;
case DownloadManager.STATUS_SUCCESSFUL:
try {
ParcelFileDescriptor file = dm.openDownloadedFile(prefs.getLong(DL_ID, 0));
FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(file);
imageView.setImageBitmap(BitmapFactory.decodeStream(fis));
} catch (Exception e) {
e.printStackTrace();
}
break;
case DownloadManager.STATUS_FAILED:
dm.remove(prefs.getLong(DL_ID, 0));
prefs.edit().clear().commit();
break;
}
}
}
}
Ckeck Out This Link

Disable back button in Android(Not working)

package com.my.app ;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import com.my.app .R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageInfo extends Activity {
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView mImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImage = (ImageView) findViewById(R.id.camera_image);
//1
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
if(requestCode == CAMERA_PIC_REQUEST){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File("data/data/com.my.app /photo.jpg");
File myDir=new File("data/data/com.my.app /");
try {
String encodedPhotoImage;
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
deleteLatest() ;
byte[] photoImgBytes=readPhotoFile();
ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
Bitmap bitmapPhoto = BitmapFactory.decodeByteArray(photoImgBytes, 0, photoImgBytes.length);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100,bao1);
byte[] by = bao1.toByteArray();
String by1 = Base64.encodeToString(by, 0);
encodedPhotoImage = URLEncoder.encode(by1);
file.delete();
if (!myDir.exists()) {
myDir.mkdirs();
}
File encryptedFile=new File("data/data/com.my.app /photo.txt");
encryptedFile.createNewFile();
FileWriter writer = new FileWriter(encryptedFile);
writer.append(encodedPhotoImage);
writer.close();
//Base64.encodeToString(ba1, Base64.DEFAULT);
Intent intent=new Intent(ImageInfo.this,Info.class);
startActivity(intent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private byte[] readPhotoFile(){
String url="data/data/com.my.app /photo.jpg";
Log.e("","Image is"+url);
Bitmap bm = BitmapFactory.decodeFile(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
return b;
}
#Override
public void onBackPressed() {
// do nothing.
}
private void deleteLatest() {
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
File [] files = f.listFiles();
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return 1;
} else {
return 0;
}
}
});
files[0].delete();
}
}
This is my java file. I have already disabled the back button using
public void onBackPressed() {
// do nothing.
}
But when back button is pressed in the app, the entire screen becomes black. Please find screen shot . The app hangs and the only way it can be accessed by terminating it through task manager and then restarting it.
try this code for disable back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
Capture Image from Camera and Display in Activity
I can't see a problem with your back button disabling. But there is another problem that may cause a part of this issue you are doing File IO in the UI Thread of your App.
Android has one UI Thread that does all the painting of your UI. If you block this thread through writing large files to the disk or reading bitmaps from the disk the phone UI will freeze and not react on user input until the heavy work is done.
I recommend to read this article on responsiveness to learn more about not blocking the UI Thread.
You can intercept the BackButton inside your own App, ONLY! As I see, you are starting some kind of CameraApp, that should pick a picture for you. You have NO control over the CameraActivity's BackButton. Your screen Has an ImageView, but you never set a Bitmap to it.
The disabling of the BackButton works, as you could NOT go out of your screen and have to "kill" it via a TaskManager. The BackButton has no functionality inside your Activity.

Categories

Resources