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);
}
}
use this code it's working properly
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…