1
我從來沒有嘗試過在我的一個項目中拍照,所以我很抱歉可能會問一個愚蠢的問題。基本上,我使用下面的代碼嘗試拍攝一張照片,然後將其保存在臨時文件中。我沒有收到任何錯誤,但沒有發生任何事情。我發現在代碼的最後部分拋出IOException。如果你知道這可能是什麼,我會非常感謝你的幫助。謝謝! 使用權限: 在我的應用程序中使用安卓相機的困惑
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
代碼:
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final String TAG = "MainActivity";
String mCurrentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePicButton = (Button)findViewById(R.id.takePicButton);
takePicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.i(TAG, "Searchable, Catch error ocurred");
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
後異常消息... – MilanNz
不登錄異常本身不要捕捉異常。將Log.i(TAG,「Searchable,Catch error ocurred」)替換爲Log.e(TAG,「Searchable,Catch error ocurred」,ex)'。這樣,您將獲得異常的Java堆棧跟蹤並可以瞭解錯誤。 – CommonsWare
@MilanNz錯誤是:E/MainActivity:java.io.IOException:打開失敗:EACCES(權限被拒絕) – Jake