简体   繁体   中英

Camera Issue in Android

I am trying to open camera intent in my app.But I just need to make sure that the image doesn't get saved in either the SD Card or in the Internal Storage.Also the image should get displayed in the app when the picture is clicked.

public class FBCheckInActivity extends Activity{

private CallbackManager callbackManager;
private LoginManager loginManager;
private File mFileTemp;
public static final int REQUEST_CODE_TAKE_PICTURE = 2;
public String path;
Bitmap sharingPhoto;
String caption="";
ImageView chooseImage;
EditText captionText;
Button postFacebook;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.facebook_sharing);
    printHashKey();
    sharingPhoto= BitmapFactory.decodeResource(this.getResources(), R.drawable.no_image);
    FacebookSdk.sdkInitialize(getApplicationContext());
    fbSharing(sharingPhoto);

}

private void fbSharing(Bitmap sharingPhoto) {
    chooseImage=(ImageView) findViewById(R.id.share_image);
    chooseImage.setImageBitmap(sharingPhoto);
    captionText=(EditText) findViewById(R.id.caption_text);
    postFacebook=(Button) findViewById(R.id.buttonPost);
    postFacebook.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loginFaceBook();
        }


    });
    chooseImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openCamera();
        }
    });
    captionText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            caption = captionText.getText().toString();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

@Override
protected void onResume() {
    super.onResume();
}

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if(requestCode==REQUEST_CODE_TAKE_PICTURE){
        Log.d("zambo","after selecting pic");
        path = mFileTemp.getPath();
        Log.d("zambo", path);
        sharingPhoto = BitmapFactory.decodeFile(path);
        chooseImage.setImageBitmap(sharingPhoto);
        fbSharing(sharingPhoto);
    }
    else {
        Log.d("zambo","callback manager for facebook sharing");
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}
public void printHashKey(){
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.urbanwand",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
}

public void  loginFaceBook(){
    callbackManager = CallbackManager.Factory.create();
    List<String> permissionNeeds = Arrays.asList("publish_actions");
    loginManager = LoginManager.getInstance();

    loginManager.logInWithPublishPermissions(FBCheckInActivity.this, permissionNeeds);
    loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();
            graphApi(accessToken);
        }

        @Override
        public void onCancel() {
            Toast.makeText(FBCheckInActivity.this, "cancel", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(FacebookException error) {
            Toast.makeText(FBCheckInActivity.this, "error", Toast.LENGTH_SHORT).show();

        }
    });
}
public void openCamera(){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        Uri mImageCaptureUri = null;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mFileTemp = new File(Environment
                    .getExternalStorageDirectory(), "IMG_"
                    + ".jpg");
            mImageCaptureUri = Uri.fromFile(mFileTemp);
        } else {
                    /*
                     * The solution is taken from here:
                     * http://stackoverflow.com/questions
                     * /10042695/how-to-get-camera-result-as-a-uri-in-data-folder
                     */
            mFileTemp = new File(getFilesDir(), "IMG_"
                    + ".jpg");
            mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                mImageCaptureUri);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
        //Log.d("User_Photo", "cannot take picture", e);
    }
}
public void graphApi(AccessToken accessToken){
    GraphRequest request = GraphRequest.newUploadPhotoRequest(accessToken, "me/photos", sharingPhoto, caption, null, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            Log.d("zambo","On Completed Callback");
            AlertDialog.Builder completeDialog = new AlertDialog.Builder(FBCheckInActivity.this);
            completeDialog.setMessage("Thank you for sharing your happiness!!");
            completeDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(new Intent(FBCheckInActivity.this, DinerHotSellers.class));
                    overridePendingTransition(0, 0);
                }
            });
            completeDialog.create();
            completeDialog.show();
        }
    });
    request.executeAsync();
}

This is what i have implemnted till now. But it doesn't give me the image back in the activity if it is stored in SD Card. Also the image is getting saved. Is is possible not to save the image in the storage media?

Thanks

A simple demo:

maim.xml

<button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="TakePhoto" button=""> 
<imageview android:id="@+id/imageView1" android:layout_gravity="center_horizontal" android:layout_height="wrap_content" android:layout_width="wrap_content"></imageview></button>

MainActivity.java(not all)

    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    private Button takePhotoBn;
    private ImageView showImage;
    private Uri imageUri; 
    private String filename; 

       @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        takePhotoBn = (Button) findViewById(R.id.button1);
        showImage = (ImageView) findViewById(R.id.imageView1);

        takePhotoBn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                SimpleDateFormat format = new SimpleDateFormat(yyyyMMddHHmmss);
                Date date = new Date(System.currentTimeMillis());
                filename = format.format(date);

                //File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);

                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);  
                File outputImage = new File(path,filename+.jpg);
                try {
                    if(outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch(IOException e) {
                    e.printStackTrace();
                }

                imageUri = Uri.fromFile(outputImage);
                Intent intent = new Intent(android.media.action.IMAGE_CAPTURE); 
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
                startActivityForResult(intent,TAKE_PHOTO); 
            }
        });

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) { 
        Toast.makeText(MainActivity.this, ActivityResult resultCode error, Toast.LENGTH_SHORT).show();
        return; 
    }
    switch(requestCode) {
    case TAKE_PHOTO:
        Intent intent = new Intent(com.android.camera.action.CROP); //cut
        intent.setDataAndType(imageUri, image/*);
        intent.putExtra(scale, true);
        intent.putExtra(aspectX, 1);
        intent.putExtra(aspectY, 1);
        intent.putExtra(outputX, 340);
        intent.putExtra(outputY, 340);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        Toast.makeText(MainActivity.this, " ", Toast.LENGTH_SHORT).show();
        //flush
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(imageUri);     
        this.sendBroadcast(intentBc);    
        startActivityForResult(intent, CROP_PHOTO); 
        break;
    case CROP_PHOTO:
        try {    
            Bitmap bitmap = BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(imageUri));
            Toast.makeText(MainActivity.this, imageUri.toString(), Toast.LENGTH_SHORT).show();
            showImage.setImageBitmap(bitmap); //show image
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        break;
    default:
        break;
    }
}

you need add permission

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

I have faced similar issue.Finally i got solution. below url may be help you. http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html

Your code may not work for Api 23. First check your WRITE_EXTERNAL_STORAGE then write. Hope it will be helpful to you...

//Check Permission
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
       Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
   ActivityCompat.requestPermissions(this,
           new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
           REQUEST_WRITE_STORAGE);
}



//Upload permission receive listener For Api 23
private static final int REQUEST_WRITE_STORAGE = 112;
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
   super.onRequestPermissionsResult(requestCode, permissions, grantResults);
   switch (requestCode)
   {
       case REQUEST_WRITE_STORAGE: {
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
           {
               choseImage();
               //reload my activity with permission granted or use the features what required the permission
           }
           else
           {
               Toast.makeText(this, "Do not allowed to write to your storage. Please consider granting it this permission", Toast.LENGTH_LONG).show();
           }
       }
   }

}

Permissions:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM