gpt4 book ai didi

android - 相机 Intent 上的 "Unfortunately, camera has stopped"

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:58 24 4
gpt4 key购买 nike

所以我试图让用户拍照,然后我将照片发送到服务器。我对安卓有点菜鸟所以我关注了this有关如何操作的教程。我见过一些与我的相似但不完全相同的问题。该应用程序确实启动了相机应用程序并允许我拍照,当我点击“检查”以接受图像时,也就是说我收到消息“不幸的是,相机已停止”并且应用程序返回到 Activity 我没有清楚地看到缩略图和图像。从相机启动到停止工作,Logcat 什么都没有显示。这是我的代码:

Activity

package com.example.ignacio.androidchat;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class TaskCompletionForm extends AppCompatActivity{

private static final String TAG = "TaskCompletionForm";
private static int REQUEST_IMAGE_CAPTURE = 1;
ImageView formImageView;
private String currImagePath;

private final boolean submitTime = false;
private final boolean submitGPS = false;
private final boolean requestImage = true;
private final boolean requestQRRead = false;
private final boolean requestRFID = false;

private LinearLayout formContainer;


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

formContainer = (LinearLayout) findViewById(R.id.ll_formContainer);

final Button b_submit = (Button) findViewById(R.id.b_submit);
b_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitForm();
}
});

final Button b_takePicture = (Button) findViewById(R.id.b_takePicture);
b_takePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchPhotographIntent();
}
});

formImageView = (ImageView) findViewById(R.id.formImageView);

}

private void submitForm() {
final int childCount = formContainer.getChildCount() - 1;
JSONObject jsonObject = new JSONObject();
try {
// add text fields
int textFieldCount = 0;
ArrayList<String> entries = new ArrayList<>();
for (int i = 0; i < childCount; i++) {
View v = formContainer.getChildAt(i);
if (v instanceof EditText) {
entries.add(((EditText) v).getText().toString());
textFieldCount++;
}
}
jsonObject.put("fieldCount", textFieldCount);
jsonObject.put("fields", new JSONArray(entries));

// add image
if (requestImage && !currImagePath.equals(""))
{
Bitmap bitmap = BitmapFactory.decodeFile(currImagePath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
jsonObject.put("image", encodedImage);
}
} catch (JSONException e) {
e.printStackTrace();
}

WebSocket.getInstance().submitCompletionForm(jsonObject);
}

private void dispatchPhotographIntent()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
File photoFile = null;
try{
photoFile = createImageFile();
} catch (IOException e)
{
e.printStackTrace();
// handle exeption
}

// continue only if the file was successfully created
if (photoFile != null)
{
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.ignacio.androidchat.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}

private File createImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
if (!image.exists())
{
image.getParentFile().mkdirs();
image.createNewFile();
}
currImagePath = image.getAbsolutePath();
return image;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
formImageView.setImageBitmap(imageBitmap);
}
}
}

list

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ignacio.androidchat">

<uses-permission android:name="android.permission.INTERNET" />

<!-- To auto-complete the email text field in the login form with the user's emails
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />-->

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA"
android:required = "true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HomeScreen"
android:launchMode="singleTask"/>
<activity android:name=".TaskDescription" />
<activity android:name=".TaskCompletionForm"
android:configChanges="keyboardHidden|orientation"/>

<service android:name=".WebSocketIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>

<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.ignacio.androidchat.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>

</manifest>

文件路径.xml


<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"
path="Android/data/com.example.ignacio.androidchat/files/Pictures/" />
</paths>

最佳答案

我假设旧三星 Android 设备(在我的例子中是 api 17)上的相机应用程序需要 "file:///....." 格式的 uri。问题是文件 uri 格式导致 Android Nougat(api 24 及更高版本)抛出 FileUriExposedException

我让这个工作:

Uri imageUri;
// N is for Nougat Api 24 Android 7
if (Build.VERSION_CODES.N <= android.os.Build.VERSION.SDK_INT) {
// FileProvider required for Android 7. Sending a file URI throws exception.
imageUri = FileProvider.getUriForFile(getContext(),"com.<your name here>.fileprovider",imageFile);
} else {
// For older devices:
// Samsung Galaxy Tab 7" 2 (Samsung GT-P3113 Android 4.2.2, API 17)
// Samsung S3
imageUri = Uri.fromFile(imageFile);
}

理想情况是只在 Nougat 或更高版本中使用 FileProvider
您可能想要降低 Build.VERSION_CODES 的 api 版本。 YMMV,取决于您对文件 uri 暴露的容忍度。

参见:Android Documentation有关 Android Nougat 中的 FileUriExposedException 的注释。

关于android - 相机 Intent 上的 "Unfortunately, camera has stopped",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42058962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com