我正在尝试在我的应用中打开相机意图。但我只需要确保图像不会保存在SD卡或内部存储中。此外,图像应显示在单击图片时的应用程序。
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();
}
这是我到目前为止所实现的。但如果它存储在SD卡中,它不能将活动中的图像返回给我。图像也被保存了。有可能不将图像保存在存储介质中吗?
谢谢
答案 0 :(得分:0)
一个简单的演示:
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(不是全部)
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;
}
}
您需要添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.CAMERA"> </uses-permission></uses-permission>
答案 1 :(得分:0)
我遇到过类似的问题。最后我得到了解决方案。 以下网址可能对您有所帮助。 http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html
答案 2 :(得分:0)
您的代码可能不适用于Api 23.首先检查您的WRITE_EXTERNAL_STORAGE然后写。希望它对你有所帮助......
//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();
}
}
}
}
权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />