当我尝试拍照时我遇到了问题,但仅限于小米redmi 3S。 我已经尝试过几款机型的APP:三星,华为,HTC,BQ,并且运行良好。 拍照的代码是:
/**
* @param context
*/
private void selectImage(final Activity context) {
final CharSequence[] items = {context.getResources().getString(R.string.sRealizarFoto),
context.getResources().getString(R.string.sSeleccionarGaleria),
context.getResources().getString(R.string.sCancelar)};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.sAddFoto));
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(context.getResources().getString(R.string.sRealizarFoto))) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, context.getResources().getInteger(R.integer.REQUEST_CAMERA));
} else if (items[item].equals(context.getResources().getString(R.string.sSeleccionarGaleria))) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, context.getResources().getString(R.string.sSelecionarArchivo)),
context.getResources().getInteger(R.integer.SELECT_FILE));
} else if (items[item].equals(context.getResources().getString(R.string.sCancelar))) {
dialog.dismiss();
}
}
});
builder.show();
}
/**
* @param requestCode
* @param resultCode
* @param data
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Bitmap thumbnail;
FileOutputStream fo;
if (resultCode == -1) {
boolean fotoNueva = false;
if (requestCode == 137) {
thumbnail = (Bitmap) data.getExtras().get("data");
assert thumbnail != null;
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File directorio = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/" + getString(R.string.findango));
if (!directorio.exists()) {
File wallpaperDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/" + getString(R.string.findango));
wallpaperDirectory.mkdirs();
}
destination = new File(Environment.getExternalStoragePublicDirectory((Environment.DIRECTORY_DCIM) + "/" + getString(R.string.findango)),
idEvento + getActivity().getResources().getString(R.string.sFormatoEvento)+ getActivity().getResources().getString(R.string.punto)+formato);
try {
if (destination.exists())
destination.delete();
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
Bitmap thumb = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(destination.getPath(), options), 96, 96, false);
if (fotoNueva) {
ImageView imageview = (ImageView) getActivity().findViewById(R.id.ivFoto);
imageview.setImageBitmap(thumb);
}
} else if (requestCode == getActivity().getResources().getInteger(R.integer.SELECT_FILE)) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getActivity().managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
BitmapFactory.Options options = new BitmapFactory.Options();
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
Bitmap thumb = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(selectedImagePath, options), 96, 96, false);
thumbnail = BitmapFactory.decodeFile(selectedImagePath, options);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
BordesRedondos bordesRedondos = new BordesRedondos(100, 0);
Log.e(TAG, "fotoNueva " + fotoNueva);
if (fotoNueva) {
ImageView imageview = (ImageView) getActivity().findViewById(R.id.ivFoto);
imageview.setImageBitmap(bordesRedondos.transform(thumb));
}
destination = new File(selectedImagePath);
}
try {
Utilidades utilidades = new Utilidades();
if (utilidades.isExternalStorageAvailable())
upload();
else {
Log.e(TAG, "Error al cargar la imagen");
utilidades.mensajeAlertDialog(getActivity().getApplicationContext(), getActivity().getResources().getString(R.string.sNoImagenDownload));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
*/
private void upload() {
// Image location URL
Log.e(TAG, "path " + destination.getPath());
try {
InputStream is = new FileInputStream(destination);
Bitmap bitmap = BitmapFactory.decodeStream(is);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
BitmapFactory.Options options = new BitmapFactory.Options();
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
//Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(selectedImagePath, options), 96, 96, false);
UploadImage uploadImage = new UploadImage(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(destination.getPath(), options), 96, 96, false));
uploadImage.execute();
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(getActivity().getResources().getString(R.string.sMessage),
getActivity().getResources().getString(R.string.sRutaImagenes));
}
/**
*
*/
public class UploadImage extends AsyncTask<Void, Void, Void> {
private final Bitmap bitmaps;
ProgressDialog pDialog;
public UploadImage(Bitmap bitmaps) {
this.bitmaps = bitmaps;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
if (bitmaps == null)
return null;
Bitmap bitmap = bitmaps;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); // convertir Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convertirr ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
getActivity().getResources().getString(R.string.sUrl_saveToFile));
MultiPartEntity reqEntity = new MultiPartEntity();
reqEntity.addPart(getActivity().getResources().getString(R.string.sImagenes), eventoConsultaPOJO.getI_idEvento() + getActivity().getResources().getString(R.string.sFormatoEvento)+getActivity().getResources().getString(R.string.punto)+formato, in);
Log.e(TAG, reqEntity.toString());
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null) {
InputStream is = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line).append("\n");
}
}
Log.i(TAG, "response " + (response != null ? response.getStatusLine().toString() : null));
} catch (IOException e) {
e.printStackTrace();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.uploaded), Toast.LENGTH_LONG).show();
/* Probar a eliminar el fragment en vez de iniciar la actividad
if(fotoNueva){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("idSesion", idSesion);
editor.putInt("idEvento", idEvento);
Intent intent = new Intent(getActivity(),EventoSeleccionado.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
getActivity().finish();*/
int inserta = sharedPreferences.getInt(getString(R.string.inserta),0);
if(inserta==1)
{
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction frTransaction = fragmentManager.beginTransaction();
frTransaction.addToBackStack(getString(R.string.fragment_evento_consulta));
editor = sharedPreferences.edit();
editor.putInt(getString(R.string.sIdUsuario), idSesion);
editor.putString(getString(R.string.modo), getString(R.string.consultar));
editor.putInt(getString(R.string.sIdSesion), idSesion);
editor.putString(getString(R.string.fromFragment),getString(R.string.fragment_evento_consulta));
editor.putInt(getString(R.string.seleccion),0);
editor.putInt(getString(R.string.tab),0);
editor.apply();
frTransaction.commit();
}
Intent intent = new Intent(getActivity(),MenuPrincipal.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
我不确定它什么时候粉碎,因为我没有手机,我收到了关于此的报告。
答案 0 :(得分:0)
managedQuery()
和getContentResolver().query()
在Redmi 3S中返回null,data.getData().getPath()
为我工作
String selectedImagePath = "";
if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi") && Build.MODEL.equalsIgnoreCase("Redmi 3S")) {
selectedImagePath = data.getData().getPath();
} else {
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getActivity().managedQuery(data.getData(), projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}
答案 1 :(得分:0)
问题在于移动设备具有API 23且APP尚未准备好在运行时请求权限。
希望它有所帮助。