android - 我正在尝试使用此代码从应用程序的资产中共享 pdf 但它显示错误
问题描述
我正在尝试使用此代码从应用程序的资产中共享 pdf 但它显示错误
InputStream outputFile = getAssets().open("new-age-careers-careers-that-didnt-exist-20-yr-ago.pdf") ; Uri uri = Uri.fromFile( (File) InputStream );
**这是我的代码**
Intent share = new Intent();
share.setAction(Intent.ACTION_SEND);
share.setType("application/pdf");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setPackage("com.whatsapp");
activity.startActivity(share);
解决方案
public class MainActivity extends AppCompatActivity {
ImageView share;
String pdfsname = "PAX-POS Manual.pdf";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
share = findViewById( R.id.share );
share.setOnClickListener( new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
@Override
public void onClick(View view) {
String message = "Choose today Enjoy tomorrow - Make right career choices";
File fileBrochure = new File( Environment.getExternalStorageDirectory().getPath() + "/" + pdfsname );
if (!fileBrochure.exists()) {
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File( Environment.getExternalStorageDirectory().getPath() + "/" + pdfsname );
Intent intent = new Intent( Intent.ACTION_SEND );
intent.putExtra( Intent.EXTRA_STREAM, Uri.fromFile( file ) );
intent.setType( "application/pdf" );
// intent.putExtra( Intent.EXTRA_TEXT, message );
intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
intent.setPackage( "com.whatsapp" );
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity( intent );
} catch (ActivityNotFoundException e) {
Toast.makeText( MainActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT ).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list( "" );
} catch (IOException e) {
Log.e( "tag", e.getMessage() );
}
for (int i = 0; i < files.length; i++) {
String fStr = files[i];
if (fStr.equalsIgnoreCase( pdfsname)) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open( files[i] );
out = new FileOutputStream( Environment.getExternalStorageDirectory() + "/" + files[i] );
copyFile( in, out );
in.close();
out.flush();
out.close();
break;
} catch (Exception e) {
Log.e( "tag", e.getMessage() );
}
}
}
}
} );
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
使用此代码它工作正常
推荐阅读
- php - PayPal PHP SDK:由于身份验证凭据无效或缺少授权标头,身份验证失败
- ionic-framework - Ionic 4、Angular Navigation 和 Android 后退按钮
- string - Lua - 使用模式获取第一次出现的子字符串
- c - 删除链表中的节点时出错
- c# - 根据现有的带有元组的字典创建带有组和计数的新字典
- javascript - 如何从对话框提示()中的用户输入创建数组
- python - 如何在训练自动编码器时为中间层的输出添加非负性和峰值约束?
- javascript - 以更短的方式从数组中获取字符串
- php - 在while循环中求和值
- android - 如果没有动作,如何抓住仍然在按钮上的手指?