拍照与摄像头的Android编程 [英] Taking pictures with camera android programmatically
问题描述
我创建了一个带有按钮的应用程序,并写了onClickListener该按钮。我尝试了好几种样品code例子,没有一次成功。它们都带来了Android摄像头应用程序,不拍照。我想一些code,我可以把我的onClickListener所以当我preSS屏幕上的按钮,一会被拍照。
I have created an app with a button and wrote onClickListener for that button. I have tried several sample code examples and none of them worked. They all bring up the android camera app and don't take photographs. I want some code which I can put in my onClickListener so when I press the button on the screen, a picture will be taken.
我怎样才能让相机拍摄照片时,我美元的一个机器人活动p $ PSS按钮?
How can I make the camera take a picture when I press a button in an android activity?
推荐答案
看看下面的演示code,
look at following demo code,
下面是UI的xml文件,
here is your xml file for UI,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Camera" />
</LinearLayout>
和这里是你的Java类文件,
and here is your java class file,
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
注意: 请在您的清单文件中的以下权限,
Note: specify the following permissions in your manifest file,
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我希望这会有所帮助!
I hope it will be helpful !!
这篇关于拍照与摄像头的Android编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!