2015-10-21 108 views
0

我正在開發一個應用程序,該應用程序允許用戶從圖庫中選擇圖片,然後開始一個活動以進行裁剪。安卓完成有時重新啓動應用程序

我想將裁剪後的圖像發送回調用活動。

這兩個活動都擴展AppCompatActivity。

調用活動:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
     if (requestCode == SELECT_PICTURE) {  

      // start image crop activity 
      String dataString = data.getDataString();  
      Intent intent=new Intent(this, CropPhotoActivity.class); 
      intent.putExtra("SELECTED_PICTURE_FOR_CROP", dataString); 
      startActivityForResult(intent, CROP_PICTURE);  
     } 
     else if(requestCode == CROP_PICTURE) { 
      // get cropped bitmap 
      Bitmap bitmap = (Bitmap) data.getParcelableExtra("CROPPED_IMAGE"); 
      profilePhoto.setImageBitmap(bitmap); 
     } 
    } 
} 

在裁剪圖像的活動,我有一個按鈕,在點擊要返回到調用活動:

Button okButton = (Button)findViewById(R.id.ok_button); 
okButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     Intent returnIntent = new Intent(); 
     returnIntent.putExtra("CROPPED_IMAGE", cropped_bitmap); 
     setResult(RESULT_OK, returnIntent); 
     finish(); // sometimes restarts app 
    } 
}); 

有時位圖被正確返回,而有時它不會和應用程序重新啓動沒有錯誤。這是爲什麼發生? putExtra與位圖大小或其他任何事情有關嗎?

回答

0

你可以嘗試替換

AppcompatActivity.this.finish() 

(其中AppcompatActivity是你的類名)

爲:

finish(); // sometimes restarts app 

或者,創建在調用活動的方法:

public static void cropComplete(Activity activity) 
{ 
    activity.startActivity(activity, AnotherActivity.class); 
    activity.finish(); 
} 
0

Theres的數據長度限制作爲額外的意圖傳遞。儘量不要傳遞dataString的值;相反,您應該將圖像保存爲臨時文件,在意圖中傳遞路徑,然後從調用活動中加載圖像(或者您可以將dataString保存在靜態助手類中)。

在作物活性(從Save bitmap to location保存位圖碼):

// Save bitmap 
String filename = "tempImage.png"; 
File sd = Environment.getExternalStorageDirectory(); 
File dest = new File(sd, filename); 
FileOutputStream out = null; 
try { 
    out = new FileOutputStream(dest); 
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance 
// PNG is a lossless format, the compression factor (100) is ignored 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (out != null)out.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

// Get image file path 
String path = dest.getAbsolutePath(); 

// Set result with image path 
Intent returnIntent = new Intent(); 
returnIntent.putExtra("CROPPED_IMAGE_PATH", path); 
setResult(RESULT_OK, returnIntent); 
finish(); 

在呼叫者活性:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (resultCode == RESULT_OK) { 
    if(requestCode == CROP_PICTURE) { 
     // Get image file path 
     String imagePath = data.getStringExtra("CROPPED_IMAGE_PATH"); 

     // Load image 
     Bitmap bitmap = BitmapFactory.decodeFile(imagePath); 
    } 
} 
相關問題