我使用Ucrop从相机中裁剪图像,但活动会跳过。这是我的MainActivity.java文件。我想我错过了一些东西。我的代码有点长,请看一下。提前谢谢。
package com.example.sathwik.uploadtrail1;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.yalantis.ucrop.UCrop;
public class MainActivity extends AppCompatActivity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Changing action bar background color
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
captureImage();
}
});
/**
Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
checking device has camera hardware or not
*/
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);// set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/** Perform UCrop */
public void performUcrop(){
UCrop.of(fileUri, fileUri).start(this);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState (Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
@Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
performUcrop();
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
//launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(), "Sorry! Failed to record video", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
//Logout function
private void logout(){
//Creating an alert dialog to confirm logout
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(Config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menuLogout) {
logout();
}
return super.onOptionsItemSelected(item);
}
}
我在gradle文件中添加了Ucrop库。我的gradle app模块有这个
compile 'com.github.yalantis:ucrop:2.2.1-native'
Android监视器显示此日志
07-02 00:42:22.953 1534-2050/system_process I/ActivityManager: START u0 {cmp=com.example.sathwik.uploadtrail1/com.yalantis.ucrop.UCropActivity (has extras)} from uid 10058 on display 0
07-02 00:42:22.954 1534-2050/system_process V/WindowManager: addAppToken: AppWindowToken{2e96b812 token=Token{39e8cb9d ActivityRecord{22ae1a74 u0 com.example.sathwik.uploadtrail1/com.yalantis.ucrop.UCropActivity t29}}} to stack=1 task=29 at 2
07-02 00:42:22.959 1534-1955/system_process I/ActivityManager: START u0 {cmp=com.example.sathwik.uploadtrail1/.UploadActivity (has extras)} from uid 10058 on display 0
07-02 00:42:22.962 1534-1955/system_process V/WindowManager: addAppToken: AppWindowToken{278b8499 token=Token{39cc69e0 ActivityRecord{322e0be3 u0 com.example.sathwik.uploadtrail1/.UploadActivity t29}}} to stack=1 task=29 at 3
07-02 00:42:23.578 14053-14053/com.example.sathwik.uploadtrail1 I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
07-02 00:42:23.945 1534-1836/system_process V/WindowManager: Adding window Window{14ab833f u0 com.example.sathwik.uploadtrail1/com.example.sathwik.uploadtrail1.UploadActivity} at 6 of 11 (after Window{14c5edfe u0 com.android.camera/com.android.camera.Camera})
07-02 00:42:24.332 1534-1563/system_process I/ActivityManager: Displayed com.example.sathwik.uploadtrail1/.UploadActivity: +1s293ms
07-02 00:42:24.333 1534-1558/system_process I/ActivityManager: Killing 2721:com.google.android.gms.unstable/u0a7 (adj 15): empty for 3423s
07-02 00:42:24.333 1534-1558/system_process W/libprocessgroup: failed to open /acct/uid_10007/pid_2721/cgroup.procs: No such file or directory
07-02 00:42:25.366 2376-14273/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up.
07-02 00:42:25.374 1534-1836/system_process I/ActivityManager: Killing 9541:com.android.calendar/u0a18 (adj 15): empty for 2545s
07-02 00:42:25.374 1534-1836/system_process W/libprocessgroup: failed to open /acct/uid_10018/pid_9541/cgroup.procs: No such file or directory
答案 0 :(得分:0)
UCrop工作正常,但你的启动方式错误,如果为源和目标指定相同的参数,则会立即调用onActivityResult。显然没有结果,修复: 1.指定不同的来源和目的地 UCrop.of(fileUri,dstUri).start(this); 2.添加代码以处理来自uCrop的响应。在我的教程中 https://youtu.be/glwM0cAUV4A,onActivityResult中的代码并不完美,但它可以正常工作。