If I start a service in the foreground inside the onClick of a button everything works fine. But if I start a service after selecting an image, so inside the onActivityResult method, then the service stops after few seconds even though it’s able to read correctly the selected image.
What’s weird is that I don’t get any exception.
Should I grant maybe Manifest.permission.READ_EXTERNAL_STORAGE but I think it’s necessary since I am already able to read the images.
Code:
public void selectImages()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_IMAGES_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == SELECT_IMAGES_REQUEST_CODE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
if(data.getData()!=null){
Uri mImageUri=data.getData();
//TODO
imagesUriArrayList.add(mImageUri);
startMyService();
} else {
if (data.getClipData() != null) {
Log.e("++data", "" + data.getClipData().getItemCount());// Get count of image here.
Log.e("++count", "" + data.getClipData().getItemCount());
if (data.getClipData().getItemCount() > 30) {
Snackbar snackbar = Snackbar
.make(findViewById(R.id.btn), "You can not select more than 30 images", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImages();
}
});
snackbar.setActionTextColor(Color.BLUE);
snackbar.show();
} else {
getListOfImages();
//TODO
startMyService();
}
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
private Bitmap getBitmapFromUri(Uri imageUri)
{
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q)
return MediaStore.Images.Media.getBitmap(notificationService.getContentResolver(), imageUri);
else {
ImageDecoder.Source source = ImageDecoder.createSource(notificationService.getContentResolver(), imageUri);
Bitmap bitmap = ImageDecoder.decodeBitmap(source);
return bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Deborah Ann Woll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.