2016-07-21 73 views
1

有人可以解釋什麼是相機請求代碼?相機請求代碼在Android中的含義是什麼

我們爲什麼要使用它?

我正在嘗試在Android的做法,我看到的代碼。

這是我做的練習的代碼;

public class imageActivity extends AppCompatActivity { 

    Button image; 
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView; 

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

     imageView = (ImageView)this.findViewById(R.id.imageView1); 
     image = (Button) findViewById(R.id.capture); 

     image.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivityForResult(cameraIntent, CAMERA_REQUEST); 
      } 
     }); 


    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
      Bitmap photo = (Bitmap) data.getExtras().get("data"); 
      imageView.setImageBitmap(photo); 
     } 
    } 
} 
+1

通過這個的答案 - https://developer.android.com/training/basics/intents/result .html –

+0

請爲您的問題添加更多的細節。你在問什麼CAMERA_REQUEST的價值? –

+0

@JosephRosson是 – kinyas

回答

4

你可以在一個單一的活動,以startActivityForResult()它允許不同Intent下做不同的動作幾個電話。使用請求代碼來確定您要返回的是哪個Intent

例如:

可以啓動兩項活動的結果:

private static final int CAMERA_REQUEST = 1888; 
private static final int GALLERY_REQUEST = 1889; 
startActivityForResult(cameraIntent, CAMERA_REQUEST); 
startActivityForResult(cameraIntent, GALLERY_REQUEST); 

並在onActivityForResult()

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
     //Do stuff with the camara data result 
    } 
    else if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) { 
     //Do stuff with the gallery data result 
    } 
} 

請注意,private static final int s爲完全任意。

+1

謝謝。我像在我的問題中回答的其他人一樣拒絕你的回答。 – kinyas

+0

不客氣!您可以將其中的一個設置爲避免接收更多帖子的答案。 :d –

1

只是在接收響應時檢測/確認REQUEST,我們使用CAMERA_REQUEST。

1

它用來接收相機意圖結果

if (requestCode == CAMERA_REQUEST) { 
    if (resultCode == RESULT_OK) { 
     // Image captured and saved to fileUri specified in the Intent 

    } else if (resultCode == RESULT_CANCELED) { 
     // User cancelled the image capture 
    } else { 
     // Image capture failed, advise user 
    } 
} 

See Official Documentation

1

這是什麼意思:

當你開始對結果的活動,例如要求相機把你的照片,然後將其返回到您的電話活動,傳遞給它一個唯一的整數值,像100001或任何你有不在該類中使用。

因此,簡而言之,CAMERA_REQUEST可能是你在你的類像這樣定義的任何值:請求從相機中的照片時

private static final int CAMERA_REQUEST = 10001; 

現在,因爲你通過它,你會用它來檢查requestCode,因爲如果它是攝像機本身,它將不得不匹配它。

我希望這可以幫助你理解。

1

onActivityResult()可以處理更多的一個回覆,就像您啓動意圖從圖庫中選取圖像一樣,其結果也會在onActivityResult()中收到。

所以要檢測我們得到的結果,我們添加一個標識符,這就是爲什麼我們使用CAMERA_REQUEST。希望你能理解。

相關問題