0

怎么了:

  1. showCameraApp()叫做。currentPhotoPath设置为/mnt/sdcard/20_08_22_06_33.jpg(使用当前日期)。
  2. 显示用于制作照片的默认 Android 应用程序(Intent以 开头startActivityForResult)。
  3. 用户正在制作和保存图片。
  4. 我们将回到我们的应用程序onActivityResult()并被cameraManager.getPhoto()调用。
  5. currentPhotoPathcameraManager.getPhoto()null

问题(随意回答其中任何一个,不一定全部):

  1. 为什么尽管之前设置过currentPhotoPathnull
  2. 也许我不必存储currentPhotoPath在私有变量中,也许我可以通过Intent? 我试过了intent.putExtra("some", "thing"),但后来Intent datanull
  3. 也许通常有一种更简单的方法可以Bitmap从用户制作的照片中获取(不保存到冗余文件)?

我的盲目猜测是,也许它与多线程有关,所以我添加volatilecurrentPhotoPath,但它没有帮助。

MainActivity班级:

public class MainActivity extends Activity implements OnClickListener 
{
    private CameraManager cameraManager;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        cameraManager = new CameraManager(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == CameraManager.REQUEST_CODE && resultCode == RESULT_OK)
        {
            Bitmap bitmap = cameraManager.getPhoto(); // HERE bitmap is null!
        }
    }   
}

CameraManager班级:

public class CameraManager
{
    public final static int REQUEST_CODE = 666;

    private /*volatile*/ String currentPhotoPath; // THIS VARIABLE BEHAVES STRANGE
    private final Activity activity;

    public CameraManager(Activity activity)
    {
        this.activity = activity;
    }

    public void showCameraApp()
    {
        final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        currentPhotoPath = createNewPhotoPath(); // HERE currentPhotoPath is set
        final File file = new File(currentPhotoPath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    private String createNewPhotoPath()
    {
        final String date = new SimpleDateFormat("dd_MM_HH_mm_ss", Locale.UK).format(new Date());
        return Environment.getExternalStorageDirectory() + "/" + date + ".jpg";
    }

    public Bitmap getPhoto()
    {
        return BitmapFactory.decodeFile(currentPhotoPath); // HERE currentPhotoPath is null!
    }
}
4

2 回答 2

2

MainActivity我猜,当你回来时会创建一个新的实例。CameraManager因此,您还分配了一个没有设置字段的新实例。

查看文档中的保存活动状态

于 2013-08-21T10:54:04.247 回答
0

尝试从意图中获取数据,如下所示:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setImageBitmap(photo);
    }  
} 
于 2013-08-20T21:12:33.867 回答