我正在尝试找到在MainActivity中实现按钮的最佳方法,该按钮启动相机活动并将图像返回到另一个活动。基本上它将图像返回到活动以向图像添加描述...我认为这是一个好主意是在按下相机按钮时启动单个照片视图活动,并从新活动启动相机活动做其他事之前的结果;但我有一个间歇性的问题,有时相机卡在一个循环中。
也许有更好的方法?我应该首先为结果启动相机活动,然后将图像作为意图传递吗?
这就是我现在所拥有的:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}else if ( id == R.id.menu_rules ){
Intent rulesIntent = new Intent(this, RulesActivity.class);
startActivity(rulesIntent);
return true;
}else if ( id == R.id.menu_import_photo ){
//pull in an image from the gallery
return true;
}else if ( id == R.id.menu_item_new_photo ){
startActivity(new Intent(MainActivity.this, SinglePhotoViewActivity.class));
}
return super.onOptionsItemSelected(item);
}
和接收活动..
public class SinglePhotoViewActivity extends Activity {
private static final String LOG_TAG = "Simple Camera App";
private static int TAKE_PICTURE = 1001;
private ImageView imageView;
private Uri imageUri;
private Bitmap bitmap;
private TextView textView;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_photo_view);
if ( bitmap == null )
takePhoto();
}
public void takePhoto(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment
.getExternalStoragePublicDirectory(Environment
//this will continually overwrite the same file
//need to implement a date/ time string
//to save as file name.
.DIRECTORY_PICTURES), "pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 1001:
if(resultCode == Activity.RESULT_OK) {
getContentResolver().notifyChange(imageUri, null);
imageView = (ImageView )findViewById(R.id.ivCameraImageView);
ContentResolver contentResolver = getContentResolver();
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(contentResolver,
imageUri);
imageView.setImageBitmap(bitmap);
} catch(Exception e) {
Toast.makeText(SinglePhotoViewActivity.this, "failed to load",
Toast.LENGTH_LONG).show();
Log.e(LOG_TAG, e.toString());
}
}
}
}
}
答案 0 :(得分:1)
您的情况类似于启动ACTION_IMAGE_CAPTURE
意图时经常发生的情况(请参阅例如 Android startCamera gives me null Intent and ... does it destroy my global variable? )。
原因是系统可能决定销毁调用者活动(在您的情况下为SinglePhotoViewActivity
),并在启动的活动(在您的情况下,系统Camera活动)返回结果后再次重新创建它。
最终修复涉及在调用活动中实现onSaveInstanceState(Bundle)
。但在你的具体情况下,有一条捷径。检查onCreate()
中的意图,如果它来自MainActivity
,则启动相机。否则,就像现在要接收onActivityResult()
一样。