2017-01-27 7 views
0

В настоящее время я создаю приложения, которые позволяют пользователю снимать фотографию и показывать ее в ImageView. Он работает как шарм на Android 5.1.1 Sony M2 Dual. Но на Kitkat 4.4.2 Samsung Galaxy Tab 3 и KitKat 4.4.4 Xiaomi Redmi 2, сила камеры закрывается после захвата изображения.Android Force Force закрывается после захвата на KitKat

Я не знаю, будет ли это полезно или нет, но я понял, что камера, вероятно, закроется, потому что после захвата на этих двух устройствах KitKat пользователю будет предложено принять захваченное изображение или нет, то если он будет возвращен к моей текущей Деятельности.

Beacuse на моем Sony с 5.1.1, пользователю не будет предложено отобразить снимок, он будет возвращен к моей текущей деятельности.

Здесь я включил соответствующий код.

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_job_order_line_form); 

    bAddPhoto = (TextView) findViewById(R.id.bAddPhoto); 
    bSaveJOLine = (TextView) findViewById(R.id.bSaveJOLine); 

    editDescription = (EditText) findViewById(R.id.editDescription); 
    editQty = (EditText) findViewById(R.id.editQty); 
    editPrice = (EditText) findViewById(R.id.editPrice); 
    ivImage = (ImageView) findViewById(R.id.imageTaken); 

    Intent intent = getIntent(); 
    jobId = intent.getIntExtra("jobId", 0); 
    docNo = intent.getStringExtra("docNo"); 

    bAddPhoto.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
      if (intentCamera.resolveActivity(getPackageManager()) != null) { 
       // Create the File where the photo should go 
       File photoFile = null; 
       try { 
        photoFile = createImageFile(); 
       } catch (IOException ex) { 
        // Error occurred while creating the File 
        Toast.makeText(OJobOrderLineFormActivity.this, "Create file failed!", 
          Toast.LENGTH_SHORT).show(); 
       } 
       // Continue only if the File was successfully created 
       if (photoFile != null) { 
        Uri photoURI = FileProvider.getUriForFile(OJobOrderLineFormActivity.this, 
          "com.opentoko.opentokolaundry.fileprovider", 
          photoFile); 
        System.out.println(photoURI); 
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); 
        startActivityForResult(intentCamera, 360); 
       } 
      } 
     } 
    }); 

    bSaveJOLine.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Snackbar.make(v, "Item has been saved!", Snackbar.LENGTH_LONG) 
        .setAction("OK", null).show(); 
     } 
    }); 

} 

Создать временную функцию файла:

private File createImageFile() throws IOException { 
    // Create an image file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()); 
    String imageFileName = docNo + "_" + timeStamp + "_"; 
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); 
    File image = File.createTempFile(
      imageFileName, /* prefix */ 
      ".jpg",   /* suffix */ 
      storageDir  /* directory */ 
    ); 
    System.out.println(storageDir); 
    System.out.println(image); 

    // Save a file: path for use with ACTION_VIEW intents 
    currentPhotoPath = image.getAbsolutePath(); 
    System.out.println(currentPhotoPath); 

    return image; 
} 

onActivityResult:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    switch (requestCode) { 
     case 360: 
      if(resultCode == RESULT_OK) { 
       int targetW = ivImage.getWidth(); 
       int targetH = ivImage.getHeight(); 

       // Get the dimensions of the bitmap 
       BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
       bmOptions.inJustDecodeBounds = true; 
       BitmapFactory.decodeFile(currentPhotoPath, bmOptions); 
       int photoW = bmOptions.outWidth; 
       int photoH = bmOptions.outHeight; 

       // Determine how much to scale down the image 
       int scaleFactor = Math.min(photoW/targetW, photoH/targetH); 

       // Decode the image file into a Bitmap sized to fill the View 
       bmOptions.inJustDecodeBounds = false; 
       bmOptions.inSampleSize = scaleFactor; 
       bmOptions.inPurgeable = true; 

       Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions); 
       ivImage.setImageBitmap(bitmap); 
      } 
    } 
} 

Я не могу понял, что причина этого, потому что в LogCat есть, кажется, нет ошибки вообще, мой все еще работает как обычно. Вот мой LogCat после ввода текущей деятельности для выполнения съемки:

D/TextLayoutCache: Enable myanmar Zawgyi converter 
D/TextLayoutCache: Enable myanmar Zawgyi converter 
D/TextLayoutCache: Enable myanmar Zawgyi converter 
D/TextLayoutCache: Enable myanmar Zawgyi converter 
I/System.out: /storage/emulated/0/Android/data/com.opentoko.opentokolaundry/files/Pictures 
I/System.out: /storage/emulated/0/Android/data/com.opentoko.opentokolaundry/files/Pictures/A-00003_20170127_1758_-1345208956.jpg 
I/System.out: /storage/emulated/0/Android/data/com.opentoko.opentokolaundry/files/Pictures/A-00003_20170127_1758_-1345208956.jpg 
I/System.out: content://com.opentoko.opentokolaundry.fileprovider/my_images/A-00003_20170127_1758_-1345208956.jpg 
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection 

Это LogCat уже в этом точный момент, когда он начать начать открыть камеру. После захвата ничего не добавлено в logcat.

Это часть моей Android-Manifest.xml:

<uses-feature android:name="android.hardware.camera" android:required="true" /> 

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" /> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <provider 
     android:name="android.support.v4.content.FileProvider" 
     android:authorities="com.opentoko.opentokolaundry.fileprovider" 
     android:exported="false" 
     android:grantUriPermissions="true"> 
     <meta-data 
      android:name="android.support.FILE_PROVIDER_PATHS" 
      android:resource="@xml/file_paths"> 
     </meta-data> 
    </provider> 

ли кто-нибудь здесь имел или имеет те же проблемы со мной? Любое решение? Любая помощь будет оценена.

ответ

0

Я нашел решение для намерения силы камеры близко к KitKat путем проб и ошибок. Кажется, мне не нужен FileProvider.

меняет storageDir в моем createImageFile() это:

File storageDir = getExternalFilesDir("Pictures"); 

И photoURI к этому:

Uri photoURI = Uri.fromFile(photoFile); 

Теперь я имею право полноэкранного изображения для отображения на KitKat тоже.

И я удаляю провайдера из своего манифеста. Теперь у меня есть файл с захваченным изображением на Android/data/my.package.name/files/Pictures/folder.

Смежные вопросы