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);
}
}
`
Related
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);
}
}
I know this was a common issue, but I have tried different suggestion, and still no solution.
My issue is that the bitmap is being displayed correctly, however SOMETIMES it saves as a black bitmap, while other times it saves correctly.
Can anyone see what I have done and tell me where I can be going wrong?
I have looked at most of the other StackOverflow questions.
The following is my code, which encodes the clip board text into a QR code and attempts to save the qr code generated.
Thank you!
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
//import android.content.ClipboardManager;
public class BarcodeWriter extends AppCompatActivity {
ImageLoader imgLoader;
ImageView qrImg;
String copiedStr;
TextView qrTxt;
ClipboardManager clipboard;
String BASE_QR_URL = "http://chart.apis.google.com/chart?cht=qr&chs=400x400&chld=M&choe=UTF-8&chl=";
String fullUrl = BASE_QR_URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_writer);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
imgLoader = ImageLoader.getInstance(); // Do it on Application start
imgLoader.init(config);
qrImg = (ImageView)findViewById(R.id.qrImg);
qrTxt = (TextView)findViewById(R.id.qrTxt);
clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
/*
* clipboard.getText() is now deprecated. But I am going to use it here
* because the new way of doing the same thing only works on API lvl 11+
* Since I want this application to support API lvl 4+ we have to use
* the old method.
*/
CharSequence clipTxt = clipboard.getText();
//This is the new, non-deprecated way of getting text from the Clipboard.
//CharSequence clipTxt = clipboard.getPrimaryClip().getItemAt(0).getText();
//If the clipboard has text, and it is more than 0 characters.
if((null != clipTxt) && (clipTxt.length() > 0)){
try {
qrTxt.setText(clipTxt);
copiedStr = clipTxt.toString();
fullUrl += URLEncoder.encode(copiedStr, "UTF-8");
//imgLoader.displayImage(fullUrl, qrImg);
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions); // Incoming options will be used
qrImg.setDrawingCacheEnabled(true);
qrImg.measure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
qrImg.layout(0, 0, qrImg.getMeasuredWidth(), qrImg.getMeasuredHeight());
qrImg.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(qrImg.getDrawingCache());
qrImg.setDrawingCacheEnabled(false); // clear drawing cache
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/DCIM/QR codes");
myDir.mkdirs();
String fname = clipTxt+".png";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
Toast.makeText(BarcodeWriter.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
Toast.makeText(this,"QR Code showing "+clipTxt,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Error occurred. Please try again later.",
Toast.LENGTH_SHORT).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{ //If no text display a dialog.
Toast.makeText(this,"No text in clipboard",Toast.LENGTH_SHORT).show();
}
}
}
Your code seems to be fine, the only thing that I saw is that you are getting you Bitmap from and external URL with Universal Image Loader instantly after calling displayImage. So is possible that for some delay in the network sometimes your ImageView still doesn't have the entire image and can make your bitmap saved as black.
Please try moving your all code bellow ImageLoader.getInstance().displayImage inside the onLoadingComplete like this:
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions, new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
ImageLoader.getInstance().displayImage(fullUrl, qrImg, defaultOptions,null);
qrImg.setDrawingCacheEnabled(true);
...
catch (Exception e) {
Toast.makeText(this, "Error occurred. Please try again later.",
Toast.LENGTH_SHORT).show();
}
}
});
Hope this help!!
I tried creating a screenshot app, but somehow I can not get the root content.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
public class Screenshot extends Activity {
public final String TAG = "Screen";
String output;
public String takeScreen(String savepathname) {
Log.e(TAG, "TAKESCREEN 01");
//View content = findViewById(R.id.button1);
//View content = findViewById(R.id.layoutroot);
//View content = getWindow().getDecorView().findViewById(android.R.id.content);
Log.e(TAG, "TAKESCREEN 01.5");
content.setDrawingCacheEnabled(true);
Log.e(TAG, "TAKESCREEN 02");
//View content = findViewById(R.id.layoutroot);
Bitmap bitmap = content.getDrawingCache();
File file = new File( Environment.getExternalStorageDirectory() + savepathname);
Log.e(TAG, "TAKESCREEN 03");
try{
Log.e(TAG, "TAKESCREEN 04");
file.createNewFile();
Log.e(TAG, "TAKESCREEN 05");
FileOutputStream ostream = new FileOutputStream(file);
Log.e(TAG, "TAKESCREEN 06");
bitmap.compress(CompressFormat.PNG, 100, ostream);
Log.e(TAG, "TAKESCREEN 07");
ostream.close();
output = "Successfully saved -> "+savepathname;
}catch (Exception e) {
e.printStackTrace();
output = "Screenshot.java -> "+e;
}
return output;
}
}
If I use findViewbyId, I only get this error: "layoutroot cannot be resolved or is not a field".
While using "getWindow().getDecorView().findViewById(android.R.id.content);" works, but then the app crashes in that part.
Could someone help me with that, please?
Did you implement this part too? If you didn't, place it inside your Screen class. By the way, I strongly believe that going over this activity lifecycle tutorial will help you.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Assuming that button1 and layoutroot are properly described within activity_main.xml
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
i would like to implement a QR Code/Barcode reader within my application. I would like to know what is the most lightweight solution to do this (disregarding intent integrator from zxing).
I used zxing to build into my application. You will need a bit of coding. First include core.jar , its at core/core.jar,in your build path, then go to their client ,its at android/..../com.google.zxing, and get their code(This is not recommended by the devs, because your copy and pasting.) last, Add this code:
package com.wtsang02.activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.HybridBinarizer;
public class QRDecoder extends Activity implements OnClickListener {
private String text;
private Button webbutton;
private Bitmap bmp;
private ImageView ivPicture;
private TextView textv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysales);
webbutton = (Button)findViewById(R.id.webbutton);
ivPicture = (ImageView) findViewById(R.id.ivPicture);
textv= (TextView) findViewById(R.id.mytext);
webbutton.setOnClickListener(this);
}
private void decode() {
if (bmp == null) {
Log.i("tag", "wtf");
}
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
int[] intArray = new int[bmp.getWidth() * bmp.getHeight()];
bmp.getPixels(intArray, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),
bmp.getHeight());
LuminanceSource source = new com.google.zxing.RGBLuminanceSource(
bmp.getWidth(), bmp.getHeight(), intArray);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
try {
Result result = reader.decode(bitmap);
text = result.getText();
byte[] rawBytes = result.getRawBytes();
BarcodeFormat format = result.getBarcodeFormat();
ResultPoint[] points = result.getResultPoints();
textv.setText(text);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
Log.i("done", "done");
if(text!=null)
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG).show();
else{
Toast.makeText(getBaseContext(), "QQ", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivPicture.setImageBitmap(bmp);
decode();
}
}
}
This code will use your phone's default camera, if you need to use their client, you will need to start their CaptureActivity, Your layout should include a TextView to show results, ImageView to show the image you captured, and Button to start the camera. . This is based off of 2.1zxing.
You can use:
zbar (SDK has a good example).
zxing
Hey download a sample of Biggu Barcode Scanner from this link, extract the Demo Project and import it to eclipse. The zip file has Demo Example, which you can use and integrate in your app as per your requirement
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.