gpt4 book ai didi

java - Android 11,可以启动意图共享文件但文件未附加

转载 作者:行者123 更新时间:2023-12-05 06:05:37 27 4
gpt4 key购买 nike

在修改路径 XML 和我的 list 提供程序设置后,我终于能够让我的应用在尝试发送电子邮件意图中的附件时停止崩溃。

但是,虽然应用程序中的一切看起来都很正常,但当 Gmail 或驱动器打开时,文件并未附加。

截图:

enter image description here

enter image description here

我的代码如下

主 Activity .java

package com.loopbreakr.filesend;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
public String reciever;
public String subject;
public String body;
public final String stringPath = "/storage/emulated/0/Android/data/com.loopbreakr.firstpdf/files/PDF_files/Abdile&Name 2021-01-29&15:59:55.pdf";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reciever = "mkercode@gmail.com";
subject = "my subject";
body = "blank email";
File file = new File(stringPath);
Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prepareEmail(file);
}
});
}

private void prepareEmail(File report) {
ArrayList<Uri> uris = new ArrayList<>();
uris.add(FileProvider.getUriForFile(getApplicationContext(), "com.loopbreakr.filesend", report));


Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, reciever);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Send email via:").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
}
}

AndroidManifest.xml

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

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Filesend">

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.loopbreakr.filesend"
android:exported="false"
android:grantUriPermissions="true">

<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<meta-data
android:name="com.google.android.actions"
android:resource="@xml/file_paths" />

<activity android:name=".MainActivity">


<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

文件路径.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>

由于程序可以找到我的文件,我认为这不再是权限错误。该文件也在外部存储上。有没有可能我在意图中遗漏了什么?非常感谢!

已编辑

请注意,我最初手动设置权限以使我的问题更具可读性,但是在向我的代码添加运行时存储读取权限并简化文件名以及将意图更改为仅发送一个文件后,我得到了无法附加文件 toast 消息

主要 Activity .java:

package com.loopbreakr.filesend;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
public String reciever;
public String subject;
public String body;
public final String stringPath = "/storage/emulated/0/Android/data/samplefile.pdf";
private int STORAGE_PERMISSION_CODE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reciever = "mkercode@gmail.com";
subject = "my subject";
body = "blank email";
File file = new File(stringPath);
Button button = findViewById(R.id.button);

if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "You have already granted this permission!",
Toast.LENGTH_SHORT).show();
} else {
requestStoragePermission();
}


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prepareEmail(file);
}
});
}

private void prepareEmail(File report) {
Uri uri = FileProvider.getUriForFile(getApplicationContext(), "com.loopbreakr.filesend", report);


Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, reciever);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

Intent chooser = Intent.createChooser(intent, "Share File");

List<ResolveInfo> resInfoList = this.getPackageManager().queryIntentActivities(chooser, PackageManager.MATCH_DEFAULT_ONLY);

for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
this.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

startActivity(chooser);
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed because of this and that")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
}

我的 list 中是否遗漏了什么?

最佳答案

我尝试使用 ACTION_SEND_MULTIPLE 发送 PDF 附件,我发现您的问题是您需要授予对 email Intent 的明确许可(而不是像您一样授予选择器 Intent做)。我的代码:

    Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);//ACTION_SEND does not support purParcelableArrayListExtra
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{testBox.getEmail()});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Covid Test Certificate result");
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);//attaching the pdf file(s) to the email
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//does not really work right now, I had to give explicit permissions

//GRANTING THE PERMISSIONS EXPLICITLY HERE! to all possible choosers (3rd party apps):
List<ResolveInfo> resolvedInfoActivities =
activity.getPackageManager().queryIntentActivities(emailIntent, PackageManager.MATCH_DEFAULT_ONLY);

for (ResolveInfo ri : resolvedInfoActivities) {
for (Uri uri : uris) {
Log.d(TAG, "Granting permission to - " + ri.activityInfo.packageName);
activity.grantUriPermission(ri.activityInfo.packageName,uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}

try {
Intent chooserIntent =Intent.createChooser(emailIntent, "Send mail...").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

activity.startActivity(
chooserIntent
);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(activity, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
Log.e(TAG, "ERROR, THERE ARE NO EMAIL CLIENTS INSTALLED.");
}

对于其他想知道权限的人来说,这是一篇好文章: https://medium.com/@benexus/dealing-with-permissions-when-sharing-files-android-m-cee9ecc287bf它说需要显式权限,因为通过 Manifest 中的提供程序和通过 Intent 添加的权限不起作用。

关于java - Android 11,可以启动意图共享文件但文件未附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65962997/

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