拍照后返回previoius活动android

时间:2016-03-29 04:42:44

标签: android android-layout android-fragments

在这里,我尝试启动相机并拍摄照片然后将其设置为ImageView,但是在点击图片后我将返回上一个活动。这是我的代码:

public void launchCamera(View view){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent,1);
}

protected void onActivityResult(int reqCode,int resCode,Intent data){
    if(reqCode == 1 && resCode == RESULT_OK){
        Bundle extras = data.getExtras();
        Bitmap photo = (Bitmap) extras.get("data");
        ImageView relativeLayout = (ImageView)findViewById(R.id.imageTaken);
        if(photo==null){
         relativeLayout.setBackgroundColor(Color.CYAN);
        }
        else {
            relativeLayout.setImageBitmap(photo);
        }
    }
}

4 个答案:

答案 0 :(得分:0)

您需要在清单文件中声明权限。

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

您的代码看起来不错,请注意您将获得缩略图图像。

请按照此处提及的说明http://developer.android.com/training/camera/photobasics.html进行操作。一切顺利

答案 1 :(得分:0)

如果你正在使用片段,它将返回到父Activity.Otherwise下面的链接帮助你。

http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html

答案 2 :(得分:0)

试试这个。不同的是super.onActivityResult(requestCode,resultCode,data);这在片段

中使用onActivityResult时是必需的
public void launchCamera(View view){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent,1);
}



      @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == Activity.RESULT_OK) {
                Bitmap bitmap1 = null;
                if (requestCode == 1) {
                    bitmap1 = (Bitmap) data.getExtras().get("data");
                    ImageView relativeLayout = (ImageView)findViewById(R.id.imageTaken);
            if(photo==null){
             relativeLayout.setBackgroundColor(Color.CYAN);
            }
            else {
                relativeLayout.setImageBitmap(photo);
            }


    }

希望它有所帮助。

答案 3 :(得分:-1)

------------------ layout_photoactivity.xml -----------

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


     <ImageView
         android:id="@+id/imageView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/tv_click_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Select Photo"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

----------- ---------- PhotoActivity.class

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class PhotoActivity extends Activity {

    ImageView imageView1;
    TextView tv_click_photo;
     public static final String SHAre_PREFERENCES = "Prefs";

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

        imageView1 = (ImageView)findViewById(R.id.imageView1);
        tv_click_photo = (TextView)findViewById(R.id.tv_click_photo);

        tv_click_photo.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Intent i = new Intent(getApplicationContext(), Camera_Activity.class);
                    startActivityForResult(i, 1);

                }
            });

    }


     protected void onActivityResult(int requestCode, int resultCode, Intent data)
     {
     switch(requestCode) {

     case 1:
         if(resultCode == RESULT_OK){
                String result=data.getStringExtra("result");
                System.out.println("result:"+result);
              SharedPreferences data_preferences = getSharedPreferences(SHAre_PREFERENCES, MODE_PRIVATE);   
                String Image_Path= data_preferences.getString("Image_Path", "Notavailble");
                String imgstr = data_preferences.getString("data", "Notavailble");

                File sel = new File(Image_Path);
                 String file = sel.getAbsolutePath().substring(sel.getAbsolutePath().lastIndexOf("/")+1);

                 Bitmap bitmap = BitmapFactory.decodeFile(sel.getAbsolutePath());
                 imageView1.setImageBitmap(bitmap);



            }
            if (resultCode == RESULT_CANCELED) {
                //Write your code if there's no result
            }
            break;

     }
     }
}

------------------------------ activity_camera.xml -------------- -

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

   <SurfaceView 
       android:id="@+id/preview"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent" 
       />
<RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="100dip"
    android:layout_alignParentBottom="true"
    android:gravity="center_vertical"
     >

    <Button 
        android:id="@+id/btn_cancel"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:text="CANCEL"
        android:onClick="onCancelClick"
        android:textColor="#000000"
        android:padding="5dp"
        android:layout_marginLeft="10dp"
        android:background="#EDEDED"
        android:textSize="12dp"
     />
    <Button 
         android:id="@+id/btn_capture"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:text="CAPTURE"
        android:onClick="onSnapClick"
        android:textColor="#000000"
        android:padding="5dp"
        android:layout_marginRight="10dp"
        android:background="#EDEDED"
        android:textSize="12dp"
     />

</RelativeLayout>
</RelativeLayout>

----------------------- Camera_Activity.class ----------

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;



import java.util.Random;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

public class Camera_Activity extends Activity implements SurfaceHolder.Callback, Camera.ShutterCallback, Camera.PictureCallback{

    Camera mCamera;
    SurfaceView mPreview;
    String path, dirpath;
    //static int i = 0;
    String Image_Path="",StrBase64="";
    Button btn_cancel,btn_capture;

    public static final String SHAre_PREFERENCES = "Prefs";
    int flag=0;



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        btn_cancel=(Button)findViewById(R.id.btn_cancel);
        btn_capture=(Button)findViewById(R.id.btn_capture);


        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
            // Activity was brought to front and not created, 
            // Thus finishing this will get us to the last viewed activity 
            finish(); 
            return; 
        } 

        mPreview = (SurfaceView)findViewById(R.id.preview);
        mPreview.getHolder().addCallback(this);
        mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mCamera = Camera.open();
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mCamera.release();
        Log.d("CAMERA", "Destroy");
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();


    }


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mCamera.stopPreview();
    }

public void onCancelClick(View v)
{
    if(flag == 0)
    {
        finish();
    }
    else
    {
        Intent returnIntent = new Intent(Camera_Activity.this,PhotoActivity.class);

        if (getParent() == null) {
            setResult(Activity.RESULT_OK, returnIntent);
        } else {
            getParent().setResult(Activity.RESULT_OK, returnIntent);
        }
        finish();

    }

}

public void onSnapClick(View v)
{
    if(flag == 0)
    {
        btn_capture.setClickable(false);
        mCamera.takePicture(this, null, null, this);

    }
    else
    {
         mCamera.startPreview();
         btn_capture.setText("CAPTURE");
            btn_cancel.setText("CANCEL");
        flag =0;
    }


}


    public void onPictureTaken(byte[] data, Camera camera) {
        // TODO Auto-generated method stub
        camera.startPreview();
        Random j = new Random();


        int ii =  j.nextInt(1000);
         File sd = Environment.getExternalStorageDirectory();
         System.out.println("sd:"+sd);
        Image_Path = sd.getAbsolutePath().toString()+"/Pic/pic"+ ii + ".jpg";
        System.out.println("Image_Path--------------:"+Image_Path);
        path = "pic" + ii + ".jpg";
        try {
              SharedPreferences data_preferences = getSharedPreferences(SHAre_PREFERENCES, MODE_PRIVATE);   
            Editor editor = data_preferences.edit();
            editor.putString("Image_Path",Image_Path);
            String str;

                str = new String(data, "UTF-8");

            editor.putString("data",str);           

                editor.commit();

        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }   
        if(android.os.Environment.MEDIA_MOUNTED != null)//true if sd card is mounted (xternal)
        {
            //Here we chose external storage
            File dir = new File(sd.getAbsolutePath().toString()+"/Pic");
            if(!dir.exists())
            {
            if (dir.mkdirs()) {  
                Toast toast = Toast.makeText(this,  
                "Directory successfully created!",  
                       Toast.LENGTH_SHORT);   
            toast.show();  
           }
            else
           {  

                Toast toast = Toast.makeText(this,  
                "Directory creation failed!",  
                       Toast.LENGTH_SHORT);  
                  toast.show();  
           }  
            }
            File file = new File(dir.getPath().toString(), path);
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file);
                fos.write(data);
                fos.flush();
                fos.close();
                Toast.makeText(Camera_Activity.this, "Image saved", Toast.LENGTH_LONG).show();

            } catch (FileNotFoundException e) {
                // handle exception
            } catch (IOException e) {
                // handle exception
            }

        }
        else
        {
            //Here we chose internal storage
        try{
            FileOutputStream out = openFileOutput(path, Activity.MODE_PRIVATE);
            out.write(data);
            out.flush();
            out.close();

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        }

        btn_capture.setText("RETAKE");
        btn_cancel.setText("USE");
         btn_capture.setClickable(true);
        mCamera.stopPreview();
        flag =1;


    }


    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub
        Camera.Parameters params = mCamera.getParameters();
        List<Camera.Size> sizes = params.getSupportedPreviewSizes();
        Camera.Size selected = sizes.get(0);
        //params.setPreviewSize(selected.width, selected.height);
        //mCamera.setParameters(params);

    //  mCamera.setDisplayOrientation(90);


        params.set("orientation", "landscape");
        mCamera.setParameters(params);

        mCamera.startPreview();
    }


    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        try{
            mCamera.setPreviewDisplay(mPreview.getHolder());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.i("PREVIEW", "surfaceDestroyed");
    }


    public void onShutter() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
    }


}

AndroidManifest.xml中的添加权限是

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

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