Android Camera App photo duplicates images - java

I am making a camera app that takes an image when the camera is first initiated, I have got it working, however the only problem I am getting is that when a picture is taken, it stores the first image in the folder. EG. I install the app, the camera takes a photo, then the next time the camera takes another photo, it is the same as the first one. I have tried to make the data = null after, however this is still not working.
Any suggestions?
package com.example.charlie;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PService2 extends Service {
//private myPreview mPreview;
Camera mCamera;
byte[] data;
private void PictureCallback()
{
}
private final class TakePhotoReceiver extends BroadcastReceiver {
public final Camera mCamera;
private TakePhotoReceiver(Camera mCamera) {
this.mCamera = mCamera;
}
#Override
public void onReceive(Context context, Intent intent) {
try {// TODO Auto-generated method stub
Log.v("test", "Got here");
mCamera.takePicture(null, null, mPicture);
//releaseCamera();
} finally {
releaseCamera();
}
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data2,Camera camera) {
Log.v("test", "image taken");
data = data2;
createExternalStoragePublicPicture(data);
data = null;
data2 = null;
//releaseCamera();
}
};
}
}
*/
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
String mCurrentPhotoPath;
void createExternalStoragePublicPicture(byte[] data) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + ".jpg";
File image = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(image, imageFileName);
try {
image.mkdirs();
OutputStream os = new FileOutputStream(file);
os.write(data);
os.close();
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
}
data = null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Service Started");
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
try {
//releaseCamera();
final Camera mCamera = Camera.open(0);
//myPreview mPreview = new myPreview(this, mCamera);
//FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
// preview.addView(mPreview);
this.registerReceiver(new TakePhotoReceiver(mCamera),
new IntentFilter(Intent.ACTION_SCREEN_ON));
//releaseCamera();
//mCamera.stopPreview();
//mCamera.stopPreview();
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return START_STICKY;
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
private FrameLayout findViewById(int cameraPreview) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
System.out.println("Service Stopped");
super.onDestroy();
mCamera.release();
//unregisterReceiver(this.TakePhotoReceiver);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
public class PictureService extends Service
{
private static final String TAG = PictureService.class.getSimpleName();
private TakePhotoReceiver mReceiver;
#Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, "onCreate");
mReceiver = new TakePhotoReceiver(0);
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.d(TAG, "onDestroy");
unregisterReceiver(mReceiver);
}
private final class TakePhotoReceiver extends BroadcastReceiver
implements Camera.PictureCallback
{
public final int mCameraId;
private TakePhotoReceiver(int cameraId)
{
mCameraId = cameraId;
}
#Override
public void onReceive(Context context, Intent intent)
{
try{
Camera camera = Camera.open(mCameraId);
try{
Log.d(TAG, "onReceive: Taking picture");
camera.takePicture(null, null, this);
}
finally{
camera.release();
camera = null;
}
}
catch(Exception e){
Log.w(TAG, "onReceive: error with camera " + mCameraId, e);
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d(TAG, "onPictureTaken");
File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
savePictureTo(picturesDir, data);
}
}
private void savePictureTo(File directory, byte[] data)
{
String fileName = new SimpleDateFormat("'JPEG_'yyyyMMdd_HHmmss'.jpg'")
.format(System.currentTimeMillis());
File file = new File(directory, fileName);
try{
directory.mkdirs();
OutputStream os = new FileOutputStream(file);
os.write(data);
os.close();
MediaScannerConnection.scanFile(this, new String[ ] { file.toString() },
null, new MediaScannerConnection.OnScanCompletedListener()
{
#Override
public void onScanCompleted(String path, Uri uri)
{
Log.d(TAG, "savePictureTo: scanned path=" + path + ", uri=" + uri);
}
});
}
catch(IOException e){
Log.w(TAG, "savePictureTo: error writing " + file, e);
}
}
}

Related

android version 10 its work but android version 12 camera and gallery not working when download playstore

Android version 12 camera and gallery not working solution
I am working on a camera application with camera API. I am able to save the image to the picture directory and set it to the image view till android version 11 but on android 12, the image is getting saved to the picture directory but not getting set to the image view I am getting an error
My Code is
Profile.java
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.cocosw.bottomsheet.BottomSheet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xxx.xx.view.MainFragment;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Profile extends AppCompatActivity implements View.OnClickListener {
private ActivityProfileBinding binding;
private String TAG = Profile.class.getSimpleName();
private Context mContext;
private ArrayList<ImageDTO> imageDatalist = new ArrayList<>();
private SharedPrefrence prefrence;
private LoginDTO loginDTO;
private HashMap<String, String> parms = new HashMap<>();
String dob = "";
String[] arrOfStr;
BottomSheet.Builder builder;
Uri picUri;
int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;
String imageName;
String pathOfImage;
Bitmap bm;
int flag = 1;
ImageCompression imageCompression;
byte[] resultByteArray;
File file;
Bitmap bitmap = null;
private HashMap<String, File> paramsFile = new HashMap<>();
HashMap<String, String> values = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
mContext = Profile.this;
prefrence = SharedPrefrence.getInstance(mContext);
loginDTO = prefrence.getLoginResponse(Consts.LOGIN_DTO);
parms.put(Consts.USER_ID, loginDTO.getUser_id());
values.put(Consts.USER_ID, loginDTO.getUser_id());
setUiaction();
}
public void setUiaction() {
binding.collapsingToolbar.setExpandedTitleColor(Color.TRANSPARENT);
binding.collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
binding.collapsingToolbar.setTitle("Profile");
binding.rlBio.setOnClickListener(this);
binding.ivCamera.setOnClickListener(this);
binding.rlGallaryClick.setOnClickListener(this);
binding.back.setOnClickListener(this);
binding.ivEditSelf.setOnClickListener(this);
binding.ivEditAbout.setOnClickListener(this);
binding.ivEditAppearance.setOnClickListener(this);
binding.ivEditImportant.setOnClickListener(this);
binding.ivEditCritical.setOnClickListener(this);
binding.ivEditLifestyle.setOnClickListener(this);
binding.ivEditFamily.setOnClickListener(this);
builder = new BottomSheet.Builder(Profile.this).sheet(R.menu.menu_cards);
builder.title(getResources().getString(R.string.select_img));
builder.listener(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case R.id.camera_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
ProjectUtils.pauseProgressDialog();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
picUri = FileProvider.getUriForFile(Profile.this.getApplicationContext(), Profile.this.getApplicationContext().getPackageName() + ".fileprovider", file);
} else {
picUri = Uri.fromFile(file); // create
}
prefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case R.id.gallery_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
picUri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_pic)), PICK_FROM_GALLERY);
}
}
break;
case R.id.cancel_cards:
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
});
break;
}
}
});
}
private File getOutputMediaFile(int type) {
String root = Environment.getExternalStorageDirectory().toString();
File mediaStorageDir = new File(root, Consts.APP_NAME);
/**Create the storage directory if it does not exist*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
Consts.APP_NAME + timeStamp + ".png");
imageName = Consts.APP_NAME + timeStamp + ".png";
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CROP_CAMERA_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
//bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
// bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
Log.e("image", imagePath);
changeImage();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == CROP_GALLERY_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
bm = MediaStore.Images.Media.getBitmap(Profile.this.getContentResolver(), picUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
changeImage();
Log.e("image", imagePath);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == PICK_FROM_CAMERA && resultCode == RESULT_OK) {
if (picUri != null) {
picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
} else {
picUri = Uri.parse(prefrence
.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
}
}
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
try {
Uri tempUri = data.getData();
Log.e("front tempUri", "" + tempUri);
if (tempUri != null) {
startCropping(tempUri, CROP_GALLERY_IMAGE);
} else {
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public void startCropping(Uri uri, int requestCode) {
Intent intent = new Intent(Profile.this, MainFragment.class);
intent.putExtra("imageUri", uri.toString());
intent.putExtra("requestCode", requestCode);
startActivityForResult(intent, requestCode);
}
#Override
protected void onResume() {
super.onResume();
if (NetworkManager.isConnectToInternet(mContext)) {
getImages();
} else {
ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_concation));
}
}
public void getImages() {
new HttpsRequest(Consts.GET_GALLARY_API, parms, mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
getMyProfile();
if (flag) {
try {
imageDatalist = new ArrayList<>();
Type getpetDTO = new TypeToken<List<ImageDTO>>() {
}.getType();
imageDatalist = (ArrayList<ImageDTO>) new Gson().fromJson(response.getJSONArray("data").toString(), getpetDTO);
if (imageDatalist.size() > 0) {
} else {
imageDatalist = new ArrayList<>();
}
} catch (JSONException e) {
e.printStackTrace();
imageDatalist = new ArrayList<>();
}
} else {
imageDatalist = new ArrayList<>();
}
}
});
}
#Override
public void onBackPressed() {
//super.onBackPressed();
finish();
overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
}
public void getMyProfile() {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MY_PROFILE_API, getparmProfile(), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
try {
loginDTO = new Gson().fromJson(response.getJSONObject("data").toString(), LoginDTO.class);
prefrence.setLoginResponse(loginDTO, Consts.LOGIN_DTO);
showData();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public HashMap<String, String> getparmProfile() {
HashMap<String, String> parms = new HashMap<>();
parms.put(Consts.USER_ID, loginDTO.getUser_id());
Log.e(TAG + " My Profile", parms.toString());
return parms;
}
public void changeImage() {
new HttpsRequest(Consts.SET_PROFILE_IMAGE_API, values,paramsFile, mContext).imagePost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
getMyProfile();
} else {
}
}
});
}
}
MainFragment.java
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.xxx.xx.R;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;
import com.isseiaoki.simplecropview.util.Utils;
import java.io.File;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class MainFragment extends FragmentActivity {
private static final int REQUEST_PICK_IMAGE = 10011;
private static final int REQUEST_SAF_PICK_IMAGE = 10012;
private static final String PROGRESS_DIALOG = "ProgressDialog";
Uri myUri;
int requestCode;
private CropImageView mCropView;
private LinearLayout mRootLayout;
public MainFragment() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
myUri = Uri.parse(getIntent().getExtras().getString("imageUri"));
requestCode = getIntent().getExtras().getInt("requestCode");
bindViews();
FontUtils.setFont(mRootLayout);
mCropView.startLoad(myUri, mLoadCallback);
mCropView.setCropMode(CropImageView.CropMode.FREE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = result.getData().toString();
mCropView.startLoad(result.getData(), mLoadCallback);
} else if (requestCode == REQUEST_SAF_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = Utils.ensureUriPermission(this, result).toString();
mCropView.startLoad(Utils.ensureUriPermission(this, result), mLoadCallback);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
MainFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
private void bindViews() {
mCropView = (CropImageView) findViewById(R.id.cropImageView);
findViewById(R.id.buttonDone).setOnClickListener(btnListener);
findViewById(R.id.buttonFitImage).setOnClickListener(btnListener);
findViewById(R.id.button1_1).setOnClickListener(btnListener);
findViewById(R.id.button3_4).setOnClickListener(btnListener);
findViewById(R.id.button4_3).setOnClickListener(btnListener);
findViewById(R.id.button9_16).setOnClickListener(btnListener);
findViewById(R.id.button16_9).setOnClickListener(btnListener);
findViewById(R.id.buttonFree).setOnClickListener(btnListener);
findViewById(R.id.buttonPickImage).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateLeft).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateRight).setOnClickListener(btnListener);
findViewById(R.id.buttonCustom).setOnClickListener(btnListener);
findViewById(R.id.buttonCircle).setOnClickListener(btnListener);
findViewById(R.id.buttonShowCircleButCropAsSquare).setOnClickListener(btnListener);
mRootLayout = (LinearLayout) findViewById(R.id.layout_root);
}
#NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
public void pickImage() {
if (Build.VERSION.SDK_INT >= 33) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_SAF_PICK_IMAGE);
}
}
#NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void cropImage() {
showProgress();
Log.e("cropImage", "called");
mCropView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
}
#OnShowRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
public void showRationaleForPick(PermissionRequest request) {
showRationaleDialog(R.string.permission_pick_rationale, request);
}
#OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void showRationaleForCrop(PermissionRequest request) {
showRationaleDialog(R.string.permission_crop_rationale, request);
}
public void showProgress() {
ProgressDialogFragment f = ProgressDialogFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.add(f, PROGRESS_DIALOG)
.commitAllowingStateLoss();
}
public void dismissProgress() {
// if (!isAdded()) return;
FragmentManager manager = getSupportFragmentManager();
if (manager == null) return;
ProgressDialogFragment f = (ProgressDialogFragment) manager.findFragmentByTag(PROGRESS_DIALOG);
if (f != null) {
getSupportFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public Uri createSaveUri() {
return Uri.fromFile(new File(this.getCacheDir(), "cropped"));
}
private void showRationaleDialog(#StringRes int messageResId, final PermissionRequest request) {
new AlertDialog.Builder(this)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.proceed();
}
})
.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.cancel();
}
})
.setCancelable(false)
.setMessage(messageResId)
.show();
}
// Handle button event /////////////////////////////////////////////////////////////////////////
private final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDone:
MainFragmentPermissionsDispatcher.cropImageWithCheck(MainFragment.this);
break;
case R.id.buttonFitImage:
mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
break;
case R.id.button1_1:
mCropView.setCropMode(CropImageView.CropMode.SQUARE);
break;
case R.id.button3_4:
mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
break;
case R.id.button4_3:
mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
break;
case R.id.button9_16:
mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
break;
case R.id.button16_9:
mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
break;
case R.id.buttonCustom:
mCropView.setCustomRatio(7, 5);
break;
case R.id.buttonFree:
mCropView.setCropMode(CropImageView.CropMode.FREE);
break;
case R.id.buttonCircle:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
break;
case R.id.buttonShowCircleButCropAsSquare:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE_SQUARE);
break;
case R.id.buttonRotateLeft:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
break;
case R.id.buttonRotateRight:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
break;
case R.id.buttonPickImage:
MainFragmentPermissionsDispatcher.pickImageWithCheck(MainFragment.this);
break;
}
}
};
// Callbacks ///////////////////////////////////////////////////////////////////////////////////
private final LoadCallback mLoadCallback = new LoadCallback() {
#Override
public void onSuccess() {
dismissProgress();
Log.e("", "success");
}
#Override
public void onError() {
dismissProgress();
Log.e("", "error");
}
};
private final CropCallback mCropCallback = new CropCallback() {
#Override
public void onSuccess(Bitmap cropped) {
}
#Override
public void onError() {
}
};
private final SaveCallback mSaveCallback = new SaveCallback() {
#Override
public void onSuccess(Uri outputUri) {
dismissProgress();
//addPicture.startResultActivity(outputUri);
Intent i = getIntent();
i.putExtra("resultUri", outputUri.toString());
setResult(requestCode, i);
finish();
}
#Override
public void onError() {
dismissProgress();
}
};
}
ProjectUtils.java
public static boolean hasPermissionInManifest(Context context, int requestCode, String permissionName) {
if (Build.VERSION.SDK_INT >= 29) {
Log.w(TAG, "hasPermissions: API version >= 29, returning true by default");
// DANGER ZONE!!! Changing this will break the library.
return true;
}
if (context == null) {
throw new IllegalArgumentException("Can't check permissions for null context");
}
if (ContextCompat.checkSelfPermission(context,
permissionName)
!= PackageManager.PERMISSION_GRANTED) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity) context,
new String[]{permissionName},
requestCode);
} else {
return true;
}
return false;
}
AndroidManifest.java
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"
tools:ignore="ScopedStorage" />
<!--Permission for the Android 11 and above-->
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android:requestLegacyExternalStorage="true"
've also added requestLegacyExternalStorage="true" to the application tag in the manifest to get it to work for the APIs below Android 12. Stuck with this issue since yesterday, Please help.
Android version 12 camera and gallery not working solution

Socket Python-Server and Java - Client in android studio where java is not able to connect to the python server

I have successfully built a python server which even works but when java from android studio tries to connect to it fails with whole bunch of errors. I have understood that it fails while creating a new socket object but why that I don't know.
This is Java client, see at the end of the code particularly for the issue where I have created new Socket object:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.TextView;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import org.w3c.dom.Text;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.net.*;
import java.io.*;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnRecognize;
private SpeechRecognizer speechRecognizer;
static EditText ET_ShowRecognized;
String locality;
private Intent intent;
private String ET_ShowRecognizedText;
private String ProcessingText;
//private FusedLocationProviderClient fusedLocationProviderClient;
//Geocoder geocoder;
Python py;
PyObject pyobj;
PyObject obj;
String currentDate;
String currentTime;
static TextToSpeech tts;
Uri imageURI;
ContentValues contentValues;
Intent cameraIntent;
static final int REQUEST_IMAGE_CAPTURE = 1;
Image mediaImage;
FirebaseVisionImage firebaseVisionImage;
static Bitmap imageBitmap;
FirebaseVisionTextDetector textDetector;
String imgText;
Intent CameraIntent;
static Thread sent;
static Thread receive;
static Socket socket;
InputStreamReader in;
BufferedReader bf;
String ServerOutput;
PrintWriter writer;
String ServerInput;
#SuppressLint({"SetTextI18n", "ClickableViewAccessibility", "MissingPermission"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, ACCESS_FINE_LOCATION, CAMERA}, PackageManager.PERMISSION_GRANTED);
ET_ShowRecognized = findViewById(R.id.ET_ShowRecognized);
btnRecognize = findViewById(R.id.btnRecognize);
/*fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if(location != null){
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
locality = address.get(0).getLocality();
} catch (IOException e) {
;
}
}
}
});
if(!Python.isStarted()){
Python.start(new AndroidPlatform(this));
}
py = Python.getInstance();
pyobj = py.getModule("WolframAlpha");
obj = pyobj.callAttr("main", locality);*/
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
}
tts.speak("Hi you successfully ran me.", TextToSpeech.QUEUE_FLUSH, null, null);
tts.speak("Seems good to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
});
//currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
//currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
//textToSpeech.speak("Hi! I am your personal assistant. Today date is something something ", TextToSpeech.QUEUE_FLUSH, null, null);
//Speak("Today's weather forecast for the current location is " + obj.toString());
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> mathches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (mathches != null) {
ET_ShowRecognized.setText(mathches.get(0));
process();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
btnRecognize.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
break;
case MotionEvent.ACTION_DOWN:
ET_ShowRecognized.setText(null);
ET_ShowRecognized.setText("Listening...");
speechRecognizer.startListening(intent);
break;
default:
break;
}
return false;
}
});
}
public void process() {
ProcessingText = ET_ShowRecognized.getText().toString().toLowerCase();
if(ProcessingText.contains("hello")) {
tts.speak("Hi! I hope all is well.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("hi")){
tts.speak("Hello! Nice to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("your name")){
tts.speak("My name is assistant.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("recognise text")){
tts.speak("Opening Camera.", TextToSpeech.QUEUE_FLUSH, null, null);
dispatchTakePictureIntent();
}
else if(ProcessingText.contains("bye")){
finish();
System.exit(0);
}
else if(ProcessingText.contains("current temperature")){
/*try {
socket = new Socket("192.168.43.203",12345);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable(){
#Override
public void run() {
try {
bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
ServerOutput = bf.readLine().toString();
MainActivity.tts.speak(ServerOutput, TextToSpeech.QUEUE_FLUSH, null, null);
MainActivity.ET_ShowRecognized.setText(ServerOutput);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
recieve_data();
}else {
tts.speak(ProcessingText, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
private void dispatchTakePictureIntent() {
CameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(CameraIntent, REQUEST_IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
// display error state to the user
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
//imageView.setImageBitmap(imageBitmap);
detectTextFromImage();
}
}
private void detectTextFromImage() {
firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
textDetector = FirebaseVision.getInstance().getVisionTextDetector();
textDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
//speakTextFromImage(firebaseVisionText);
getImgText(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#SuppressLint("SetTextI18n")
#Override
public void onFailure(#NonNull Exception e) {
tts.speak("Something went wrong. Please try again later or try with another image.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("Something went wrong. Please try again later or try with another image.");
}
});
}
#SuppressLint("SetTextI18n")
private void getImgText(FirebaseVisionText firebaseVisionText){
List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
if(blockList.size() == 0) {
tts.speak("I think this image contains no text.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("I think this image contains no text.");
}else{
for(FirebaseVisionText.Block block : firebaseVisionText.getBlocks()){
imgText = block.getText().toString();
tts.speak("The text in the image is as follows : " + imgText, TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("The text in the image is as follows : " + imgText);
}
}
}
public void recieve_data(){
ServerInput = "Java client is successfully connected with the server ";
BackgroundTask bt = new BackgroundTask();
bt.execute(ServerInput);
}
class BackgroundTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... voids) {
try{
String message = voids[0];
socket = new Socket("myIP", 24224);
writer = new PrintWriter(socket.getOutputStream());
writer.write(message);
writer.flush();
writer.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}
This is my python server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
try:
port = 24224
s.bind(("", port))
print("socket binded to %s" %(port))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
while True:
conn, addr = s.accept()
print('Got connection from', addr)
message = conn.recv(1024)
print("Client : " + message)
conn.close()
Now the run view in the android studio:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.maitreyastudio.ai, PID: 17690
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maitreyastudio.ai/com.maitreyastudio.ai.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1318)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:340)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:616)
at java.net.Socket.connect(Socket.java:548)
at java.net.Socket.<init>(Socket.java:440)
at java.net.Socket.<init>(Socket.java:223)
at com.maitreyastudio.ai.MainActivity.onCreate(MainActivity.java:127)
at android.app.Activity.performCreate(Activity.java:6712)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
Looking at the stack trace I see that you are trying to connect on the ui thread which
is causing the crash. You need to move the connection logic in to its own thread
Here is a link to the documentation that will help you
https://developer.android.com/guide/components/processes-and-threads#Threads
try this for main activity
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.TextView;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import org.w3c.dom.Text;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.net.*;
import java.io.*;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnRecognize;
private SpeechRecognizer speechRecognizer;
static EditText ET_ShowRecognized;
String locality;
private Intent intent;
private String ET_ShowRecognizedText;
private String ProcessingText;
//private FusedLocationProviderClient fusedLocationProviderClient;
//Geocoder geocoder;
Python py;
PyObject pyobj;
PyObject obj;
String currentDate;
String currentTime;
static TextToSpeech tts;
Uri imageURI;
ContentValues contentValues;
Intent cameraIntent;
static final int REQUEST_IMAGE_CAPTURE = 1;
Image mediaImage;
FirebaseVisionImage firebaseVisionImage;
static Bitmap imageBitmap;
FirebaseVisionTextDetector textDetector;
String imgText;
Intent CameraIntent;
static Thread sent;
static Thread receive;
static Socket socket;
InputStreamReader in;
BufferedReader bf;
String ServerOutput;
PrintWriter writer;
String ServerInput;
#SuppressLint({"SetTextI18n", "ClickableViewAccessibility", "MissingPermission"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, ACCESS_FINE_LOCATION, CAMERA}, PackageManager.PERMISSION_GRANTED);
ET_ShowRecognized = findViewById(R.id.ET_ShowRecognized);
btnRecognize = findViewById(R.id.btnRecognize);
/*fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if(location != null){
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
locality = address.get(0).getLocality();
} catch (IOException e) {
;
}
}
}
});
if(!Python.isStarted()){
Python.start(new AndroidPlatform(this));
}
py = Python.getInstance();
pyobj = py.getModule("WolframAlpha");
obj = pyobj.callAttr("main", locality);*/
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
}
tts.speak("Hi you successfully ran me.", TextToSpeech.QUEUE_FLUSH, null, null);
tts.speak("Seems good to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
});
//currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
//currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
//textToSpeech.speak("Hi! I am your personal assistant. Today date is something something ", TextToSpeech.QUEUE_FLUSH, null, null);
//Speak("Today's weather forecast for the current location is " + obj.toString());
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> mathches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (mathches != null) {
ET_ShowRecognized.setText(mathches.get(0));
process();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
btnRecognize.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
speechRecognizer.stopListening();
break;
case MotionEvent.ACTION_DOWN:
ET_ShowRecognized.setText(null);
ET_ShowRecognized.setText("Listening...");
speechRecognizer.startListening(intent);
break;
default:
break;
}
return false;
}
});
}
public void process() {
ProcessingText = ET_ShowRecognized.getText().toString().toLowerCase();
if(ProcessingText.contains("hello")) {
tts.speak("Hi! I hope all is well.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("hi")){
tts.speak("Hello! Nice to meet you.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("your name")){
tts.speak("My name is assistant.", TextToSpeech.QUEUE_FLUSH, null, null);
}
else if(ProcessingText.contains("recognise text")){
tts.speak("Opening Camera.", TextToSpeech.QUEUE_FLUSH, null, null);
dispatchTakePictureIntent();
}
else if(ProcessingText.contains("bye")){
finish();
System.exit(0);
}
else if(ProcessingText.contains("current temperature")){
sendTemp();
recieve_data();
}else {
tts.speak(ProcessingText, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
private void dispatchTakePictureIntent() {
CameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(CameraIntent, REQUEST_IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
// display error state to the user
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
//imageView.setImageBitmap(imageBitmap);
detectTextFromImage();
}
}
private void detectTextFromImage() {
firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
textDetector = FirebaseVision.getInstance().getVisionTextDetector();
textDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
//speakTextFromImage(firebaseVisionText);
getImgText(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#SuppressLint("SetTextI18n")
#Override
public void onFailure(#NonNull Exception e) {
tts.speak("Something went wrong. Please try again later or try with another image.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("Something went wrong. Please try again later or try with another image.");
}
});
}
#SuppressLint("SetTextI18n")
private void getImgText(FirebaseVisionText firebaseVisionText){
List<FirebaseVisionText.Block> blockList = firebaseVisionText.getBlocks();
if(blockList.size() == 0) {
tts.speak("I think this image contains no text.", TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("I think this image contains no text.");
}else{
for(FirebaseVisionText.Block block : firebaseVisionText.getBlocks()){
imgText = block.getText().toString();
tts.speak("The text in the image is as follows : " + imgText, TextToSpeech.QUEUE_FLUSH, null, null);
ET_ShowRecognized.setText("The text in the image is as follows : " + imgText);
}
}
}
public void recieve_data(){
ServerInput = "Java client is successfully connected with the server ";
BackgroundTask bt = new BackgroundTask();
bt.execute(ServerInput);
}
public void sendTemp(){
new TempBackgroundTask().execute();
}
class TempBackgroundTask extends AsyncTask<Void, String, Void>{
#Override
protected Void doInBackground(String... voids) {
try {
socket = new Socket("myIP",12345);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable(){
#Override
public void run() {
try {
bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
ServerOutput = bf.readLine().toString();
publishProgress(ServerOutput);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
#Override
protected void onProgressUpdate(String... text) {
MainActivity.tts.speak(text[0], TextToSpeech.QUEUE_FLUSH, null, null);
MainActivity.ET_ShowRecognized.setText(text[0]);
}
}
class BackgroundTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... voids) {
try{
String message = voids[0];
socket = new Socket("192.168.43.203", 24224);
writer = new PrintWriter(socket.getOutputStream());
writer.write(message);
writer.flush();
writer.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
}

Unable to fetch file from google drive

I am working on a project where user can upload a document to my server. This file can be selected either from local storage or a cloud storage ,say google drive. When i click on the file from file chooser all i am receiving is an account info and doc info as a uri, When i tried to fetch doc from this URI it is showing FileNotFound . I have gone through Drive API also but It is a bit confusing to me. Following are the points i came accross while trying Google Drive API:
1. How to select file from local storage.
2. How do I get FileId form the selected file.
I tried with the following code snippet:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("**/");
startActivityForResult(intent, 1000);
and In onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i("URI", "Uri: " + uri.toString());
try {
readTextFromUri(uri);
getMimeType(this,uri);
} catch (IOException e) {
e.printStackTrace();
}
// showImage(uri);
}
}
}
private String readTextFromUri(Uri uri) throws IOException {
// FileInputStream fileInputStream=new FileInputStream(uri.)
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
// fileInputStream.close();
// parcelFileDescriptor.close();
return stringBuilder.toString();
}
Conclusion:
Can anyone please send me a link how to upload a document(I should even check the extension of the document) from both local storage and Google drive in a File chooser.
package com.example.ayyappaboddupalli.gdrive;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResourceClient;
import com.google.android.gms.drive.OpenFileActivityOptions;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.api.services.drive.model.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Google drive";
private static final String SIGN_IN = "Sign In";
private static final String DOWNLOAD_FILE = "Download file";
private static final int REQUEST_CODE_SIGN_IN = 0;
private static final int REQUEST_CODE_OPEN_ITEM = 1;
private static final int REQUEST_WRITE_STORAGE = 112;
private GoogleSignInAccount signInAccount;
private Set<Scope> requiredScopes;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private OpenFileActivityOptions openOptions;
private TaskCompletionSource<DriveId> mOpenItemTaskSource;
private java.io.File storageDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main);
initialize();
requestPermission();
signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
// onDriveClientReady();
signIn();
}
Button button=(Button)findViewById(R.id.Submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDriveClientReady();
}
});
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == RESULT_OK) {
Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
showMessage("Sign in successfully.");
// binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
showMessage("Sign in failed.");
}
} else {
showMessage("Sign in failed.");
}
break;
case REQUEST_CODE_OPEN_ITEM:
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
mOpenItemTaskSource.setResult(driveId);
} else {
mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
}
break;
}
}
private void initialize() {
requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
openOptions = new OpenFileActivityOptions.Builder()
.setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "application/pdf"))
.setActivityTitle("Select file")
.build();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
private void signIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
private void onDriveClientReady() {
mOpenItemTaskSource = new TaskCompletionSource<>();
mDriveClient.newOpenFileActivityIntentSender(openOptions)
.continueWith(new Continuation<IntentSender, Void>() {
#Override
public Void then(#NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(
task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
return null;
}
});
Task<DriveId> tasks = mOpenItemTaskSource.getTask();
tasks.addOnSuccessListener(this,
new OnSuccessListener<DriveId>() {
#Override
public void onSuccess(DriveId driveId) {
retrieveContents(driveId.asDriveFile());
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("File not selected.");
}
});
}
private void retrieveContents(final DriveFile file) {
// [START open_file]
final Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY);
// [END open_file]
// [START read_contents]
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
Log.v(TAG, "File name : " + contents.toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
InputStream input = contents.getInputStream();
try {
java.io.File file = new java.io.File(getExternalFilesDir(null), "umesh.pdf");
Log.v(TAG, storageDir + "");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
showMessage("Download file successfully.");
return mDriveResourceClient.discardContents(contents);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("Unable to download file.");
}
});
// [END read_contents]
}
private void requestPermission() {
String dirPath = getFilesDir().getAbsolutePath() + java.io.File.separator + "PDF";
storageDir = new java.io.File(dirPath);
if (!storageDir.exists())
storageDir.mkdirs();}}
//in gradle
implementation 'com.google.android.gms:play-services:11.8.0'
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-drive:v3-rev110-1.23.0'

why when i trying to upload image with size 1.5mb it's said error while uploading, but actually the image is successfully upload?

why when i trying to upload image with size 1.5 mb it's said error while uploading, but actually the image is successfully upload? and if i trying to upload with size 100 kb it's said Image Uploaded Successfully
WC_Activity.java
package com.emergency.e_place;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAGS = "DEBUG";
String Latitude;
String Longitude;
private final String TAG = this.getClass().getName();
ImageView ivCamera, ivGallery, ivUpload, ivImage;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST = 13323;
final int GALLERY_REQUEST = 22131;
String selectedPhoto;
EditText etIpAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAGS, "onLocationChanged: " + Longitude);
etIpAddress = (EditText)findViewById(R.id.etIpAddress);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ivImage = (ImageView)findViewById(R.id.ivImage);
ivCamera = (ImageView)findViewById(R.id.ivCamera);
ivGallery = (ImageView)findViewById(R.id.ivGallery);
ivUpload = (ImageView)findViewById(R.id.ivUpload);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(galleryPhoto.openGalleryIntent(), GALLERY_REQUEST);
}
});
ivUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedPhoto == null || selectedPhoto.equals("")){
Toast.makeText(getApplicationContext(), "No Image Selected.", Toast.LENGTH_SHORT).show();
return;
}
try {
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
String encodedImage = ImageBase64.encode(bitmap);
Log.d(TAG, encodedImage);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("image", encodedImage);
PostResponseAsyncTask task = new PostResponseAsyncTask(WC_Activity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if(s.contains("uploaded_success")){
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully.",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error while uploading.",
Toast.LENGTH_SHORT).show();
}
}
});
String ip = etIpAddress.getText().toString();
task.execute("http://" +ip + "/AndroidUpload/upload.php");
task.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error.",
Toast.LENGTH_SHORT).show();
}
});
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while encoding photos", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST){
String photoPath = cameraPhoto.getPhotoPath();
selectedPhoto = photoPath;
Bitmap bitmap = null;
try {
bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(getRotatedBitmap(bitmap, 90));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
}
else if(requestCode == GALLERY_REQUEST){
Uri uri = data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath = galleryPhoto.getPath();
selectedPhoto = photoPath;
try {
Bitmap bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
private Bitmap getRotatedBitmap(Bitmap source, float angle){
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap bitmap1 = Bitmap.createBitmap(source,
0, 0, source.getWidth(), source.getHeight(), matrix, true);
return bitmap1;
}
}

Inverting audio in Java

I am new to Java and I want to know how to invert audio (fixed voice inversion) coming from the input through a loopback to the output after a delay. How and where would I do this, and would I be able to set a frequency of the inversion somehow. Thanks.
package net.bitplane.android.microphone;
import java.nio.ByteBuffer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
public class MicrophoneService extends Service implements OnSharedPreferenceChangeListener {
private static final String APP_TAG = "Microphone";
private static final int mSampleRate = 44100;
private static final int mFormat = AudioFormat.ENCODING_PCM_16BIT;
private AudioTrack mAudioOutput;
private AudioRecord mAudioInput;
private int mInBufferSize;
private int mOutBufferSize;
SharedPreferences mSharedPreferences;
private static boolean mActive = false;
private NotificationManager mNotificationManager;
private MicrophoneReceiver mBroadcastReceiver;
private class MicrophoneReceiver extends BroadcastReceiver {
// Turn the mic off when things get loud
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
SharedPreferences prefs = context.getSharedPreferences(APP_TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefs.edit();
e.putBoolean("active", false);
e.commit();
}
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.d(APP_TAG, "Creating mic service");
// notification service
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBroadcastReceiver = new MicrophoneReceiver();
// create input and output streams
mInBufferSize = AudioRecord.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat);
mOutBufferSize = AudioTrack.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat);
mAudioInput = new AudioRecord(MediaRecorder.AudioSource.MIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat, mInBufferSize);
mAudioOutput = new AudioTrack(AudioManager.STREAM_MUSIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat, mOutBufferSize, AudioTrack.MODE_STREAM);
// listen for preference changes
mSharedPreferences = getSharedPreferences(APP_TAG, MODE_PRIVATE);
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
mActive = mSharedPreferences.getBoolean("active", false);
if (mActive)
record();
}
#Override
public void onDestroy() {
Log.d(APP_TAG, "Stopping mic service");
// close the service
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putBoolean("active", false);
e.commit();
// disable the listener
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
mAudioInput.release();
mAudioOutput.release();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(APP_TAG, "Service sent intent");
// if this is a stop request, cancel the recording
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals("net.bitplane.android.microphone.STOP")) {
Log.d(APP_TAG, "Cancelling recording via notification click");
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putBoolean("active", false);
e.commit();
}
}
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// intercept the preference change.
if (!key.equals("active"))
return;
boolean bActive = sharedPreferences.getBoolean("active", false);
Log.d(APP_TAG, "Mic state changing (from " + mActive + " to " + bActive + ")");
if (bActive != mActive) {
mActive = bActive;
if (mActive)
record();
if (!mActive)
mNotificationManager.cancel(0);
}
}
public void record() {
Thread t = new Thread() {
public void run() {
Context context = getApplicationContext();
CharSequence titleText = getString(R.string.mic_active);
CharSequence statusText = getString(R.string.cancel_mic);
long when = System.currentTimeMillis();
Intent cancelIntent = new Intent();
cancelIntent.setAction("net.bitplane.android.microphone.STOP");
cancelIntent.setData(Uri.parse("null://null"));
cancelIntent.setFlags(cancelIntent.getFlags() | Notification.FLAG_AUTO_CANCEL);
PendingIntent pendingCancelIntent = PendingIntent.getService(context, 0, cancelIntent, 0);
Notification notification = new Notification(R.drawable.status, titleText, when);
notification.setLatestEventInfo(context, titleText, statusText, pendingCancelIntent);
mNotificationManager.notify(0, notification);
// allow the
registerReceiver(mBroadcastReceiver, new IntentFilter(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY));
Log.d(APP_TAG, "Entered record loop");
recordLoop();
Log.d(APP_TAG, "Record loop finished");
}
private void recordLoop() {
if ( mAudioOutput.getState() != AudioTrack.STATE_INITIALIZED || mAudioInput.getState() != AudioTrack.STATE_INITIALIZED) {
Log.d(APP_TAG, "Can't start. Race condition?");
}
else {
try {
try { mAudioOutput.play(); } catch (Exception e) { Log.e(APP_TAG, "Failed to start playback"); return; }
try { mAudioInput.startRecording(); } catch (Exception e) { Log.e(APP_TAG, "Failed to start recording"); mAudioOutput.stop(); return; }
try {
ByteBuffer bytes = ByteBuffer.allocateDirect(mInBufferSize);
int o = 0;
byte b[] = new byte[mInBufferSize];
while(mActive) {
o = mAudioInput.read(bytes, mInBufferSize);
bytes.get(b);
bytes.rewind();
mAudioOutput.write(b, 0, o);
}
Log.d(APP_TAG, "Finished recording");
}
catch (Exception e) {
Log.d(APP_TAG, "Error while recording, aborting.");
}
try { mAudioOutput.stop(); } catch (Exception e) { Log.e(APP_TAG, "Can't stop playback"); mAudioInput.stop(); return; }
try { mAudioInput.stop(); } catch (Exception e) { Log.e(APP_TAG, "Can't stop recording"); return; }
}
catch (Exception e) {
Log.d(APP_TAG, "Error somewhere in record loop.");
}
}
// cancel notification and receiver
mNotificationManager.cancel(0);
try {
unregisterReceiver(mBroadcastReceiver);
} catch (IllegalArgumentException e) { Log.e(APP_TAG, "Receiver wasn't registered: " + e.toString()); }
}
};
t.start();
}
}

Categories