我很难用我的代码打开相机,我会很感激帮助...基本上应用程序会显示,当我点击文本时,应用程序会立即关闭...我觉得我没有链接两个正确。
以下是来自activity_main.xml的代码:
<TextView
android:id="@+id/textView4"
android:clickable="true"
android:onClick="onClick"
android:text="@string/openCamera" />
这是我的Java:
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView4);
if (!hasCamera()) {
txt.setEnabled(false);
}
txt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
});
}
private boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
Logcat提到以下内容:
FATAL EXCEPTION: main
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.sec.android.app.camera/.Camera launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } } from ProcessRecord{29106f2 12844:com.example.xxxxxxxxxx} (pid=12844, uid=10188) with revoked permission android.permission.CAMERA
答案 0 :(得分:0)
可能您错过了在清单中添加相机权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
答案 1 :(得分:0)
你去..
1.如果您还在活动中使用onClick侦听器,请从xml文件中删除onClick侦听器。
<TextView
android:id="@+id/textView4"
android:clickable="true"
android:text="@string/openCamera" />
2.在AndroidManifest.xml下添加以下权限
<uses-feature
android:name="android.hardware.camera.any"
android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
3.在您的活动中添加以下点击监听器。
textView4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(cameraIntent);
}
});
5.如果要显示捕获的图像,则需要在xml文件中添加imageview。要显示图片,请在活动中使用以下代码。
textView4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
});
6.在onCreate之后添加以下方法。
@覆盖
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.imageView); //sets imageview as the bitmap
imageview.setImageBitmap(image);
}
}