Import PDF from adobe - java

I am looking to do the following in andriod studio
User will open his mail client and click preview on a PDF. It opens the file in adobe reader.
The user makes comments in adobe and when done press share
My andriod app is shown and the users selects my app
My andriod app gets the pdf and saves it externally to my server.
I have part 1,2,3 so far but not 4,5. Its my understanding that you can not access applications storage, but a poster posted this, but I am unsure on how to use that?

In order to get the PDF you'll need to create an activity for this use case that listens for those "sharing" intents.
ShareActivity.java
void onCreate (Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("application/pdf".equals(type)) {
handlePDF(intent);
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("application/pdf")) {
// Handle multiple pdfs being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
}
void handlePDF(Intent intent) {
Uri pdfUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (pdfUri != null) {
// TODO: Use your server-side here to save.
}
}
And then add this to your AndroidManifest.xml so Android knows what activity to get when they select your application to share to:
<activity android:name=".ui.ShareActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/pdf" />
</intent-filter>
</activity>

public class savepdf extends ActionBarActivity {
static final int REQUEST_IMAGE_OPEN = 1;
private static final int WRITE_REQUEST_CODE = 43;
private Uri mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savepdf);
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("application/pdf".equals(type)) {
handlePDF(intent);
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("application/pdf")) {
// Handle multiple pdfs being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
}
void handlePDF(Intent intent) {
Uri pdfUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (pdfUri != null) {
//savefile(pdfUri);
String sourceFilename= pdfUri.getPath();
String destinationFilename = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"abc.pdf";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
} catch (IOException e) {
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
// TODO: Use your server-side here to save.
}
}

Related

How to open exact app with Intent.ACTION_VIEW and Uri

I am trying to open zoom app by passing uri to the intent with below and it works fine.
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("<zoom url>"))
val packageManager = packageManager
if (intent.resolveActivity(packageManager) != null) {
startActivity(launchApp)
}
But this shows my browser also as user can select it and open the uri I pass. what I want to do is only open zoom app with the uri.
By using val activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) I can filter the apps that can open my intent but how can I select the exact app(zoom) and pass uri to it and open zoom app only with my meeting url?
May be need a packageName?
I referenced some code from Google in this
public static void openCustomTab(Activity activity,
CustomTabsIntent customTabsIntent,
Uri uri,
CustomTabFallback fallback) {
String packageName = CustomTabsHelper.getPackageNameToUse(activity);
//If we cant find a package name, it means theres no browser that supports
//Chrome Custom Tabs installed. So, we fallback to the webview
if (packageName == null) {
if (fallback != null) {
fallback.openUri(activity, uri);
}
} else {
customTabsIntent.intent.setPackage(packageName);
customTabsIntent.launchUrl(activity, uri);
}
}
it use setPackage(),then the app will open the chrome app without chooser.
This is the method of getPackageNameToUse
static final String STABLE_PACKAGE = "com.android.chrome";
static final String BETA_PACKAGE = "com.chrome.beta";
static final String DEV_PACKAGE = "com.chrome.dev";
static final String LOCAL_PACKAGE = "com.google.android.apps.chrome";
...
...
public static String getPackageNameToUse(Context context) {
if (sPackageNameToUse != null) return sPackageNameToUse;
PackageManager pm = context.getPackageManager();
// Get default VIEW intent handler.
Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0);
String defaultViewHandlerPackageName = null;
if (defaultViewHandlerInfo != null) {
defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName;
}
// Get all apps that can handle VIEW intents.
List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
List<String> packagesSupportingCustomTabs = new ArrayList<>();
for (ResolveInfo info : resolvedActivityList) {
Intent serviceIntent = new Intent();
serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
serviceIntent.setPackage(info.activityInfo.packageName);
if (pm.resolveService(serviceIntent, 0) != null) {
packagesSupportingCustomTabs.add(info.activityInfo.packageName);
}
}
// Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
// and service calls.
if (packagesSupportingCustomTabs.isEmpty()) {
sPackageNameToUse = null;
} else if (packagesSupportingCustomTabs.size() == 1) {
sPackageNameToUse = packagesSupportingCustomTabs.get(0);
} else if (!TextUtils.isEmpty(defaultViewHandlerPackageName)
&& !hasSpecializedHandlerIntents(context, activityIntent)
&& packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) {
sPackageNameToUse = defaultViewHandlerPackageName;
} else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
sPackageNameToUse = STABLE_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
sPackageNameToUse = BETA_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
sPackageNameToUse = DEV_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
sPackageNameToUse = LOCAL_PACKAGE;
}
return sPackageNameToUse;
}
Maybe it will help you.

Show different layout depending on a condition

In my case I have two layout, but I have check the mainactivity's oncreate, if the file is created then open indexpage, activity_indexpage2.xml, but I can't not print this result to check bug.
protected void onCreate(Bundle savedInstanceState) {
try {
contentfile = read();
} catch (IOException e) {
e.printStackTrace();
}
if(contentfile!=null
){
Intent intent = new Intent(MainActivity.this, indexpage.class);
setContentView(R.layout.activity_indexpage2);
startActivity(intent);
}
`super.onCreate(savedInstanceState);`
public String read() throws IOException {
FileInputStream input = this.openFileInput(File_NAME);
byte[] temp = new byte[1024];
StringBuffer stringBuffer = new StringBuffer("");
int len = 0;
while ((len = input.read(temp)) > 0) {
stringBuffer.append(new String(temp, 0, len));
}
input.close();
return stringBuffer.toString();
}
In onCreate() your first statement should be setContentView() then you need to request permission for reading external storage then if you have permission granted then check if the file exists or not. Then depending on the condition show your proper layout or navigate to another activity using Intent

Take Photo with Camera Samsung galaxy s5 destroy activity

I am working on app which uses an ImageView to display a photo. But after a photo is taken, it is not being shown in the ImageView. Furthermore, the app gets force closed after taking the picture. I try this with my Nexus 5 (Marshmallow), Samsung Galaxy S4(Lollipop & CustomRom), Xiaomi Mi4, Asus Zenfone 1, and Lenovo tablet which all run smoothly. Here are some scenarios that I tried with the Samsung Galaxy S5 :
Take a photo, wait a couple of seconds before clicking "Ok", then I press back to my apps. (Result : sometimes this works, sometimes image does not show in the ImageView)
Take a photo and immediately click "Ok". (Result : force closed. Logcat says TextView in abstract class is null )
Take a photo, immediately click "Ok" while debuging in function OnActivityResult (Result : it works)
Here's the code :
AndroidManifest.xml
<application
android:name=".coreclass.CoreApp"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/unik_fintech"
android:label="#string/appname"
android:largeHeap="true"
android:launchMode="singleInstance"
android:noHistory="true"
android:theme="#style/Theme.MyTheme"
tools:replace="android:label">
<activity
android:name=".activities.MainPage"
android:configChanges="screenSize|keyboardHidden|orientation"
android:exported="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activities.KantinActivity"
android:configChanges="screenSize|keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
/>
KantinActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Timber.d("isi request code:" + String.valueOf(requestCode));
Timber.d("isi result Code:"+ String.valueOf(resultCode));
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case RESULT_GALERY:
if(resultCode == RESULT_OK){
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.kantinActivityContent);
if(currentFrag instanceof StockBarangAction){
Bitmap photo = null;
Uri _urinya = data.getData();
if(data.getData() == null) {
photo = (Bitmap)data.getExtras().get("data");
} else {
try {
photo = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
GeneralizeImage mGI = new GeneralizeImage(this,photo,_urinya);
StockBarangAction mFrag = (StockBarangAction) currentFrag;
mFrag.setFileImageCatalog(false, mGI.Convert(), _urinya.toString());
}
}
break;
case RESULT_CAMERA:
if(resultCode == RESULT_OK && mCapturedImageURI!=null){
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.kantinActivityContent);
if(currentFrag instanceof StockBarangAction){
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection, null, null, null);
String filePath;
if (cursor != null) {
cursor.moveToFirst();
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
filePath = cursor.getString(column_index_data);
}
else
filePath = data.getData().getPath();
GeneralizeImage mGI = new GeneralizeImage(this,filePath);
StockBarangAction mFrag = (StockBarangAction) currentFrag;
mFrag.setFileImageCatalog(true, mGI.Convert(), filePath);
if (cursor != null) {
cursor.close();
}
}
}
else{
Toast.makeText(this, "Try Again", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mCapturedImageURI != null) {
outState.putString("cameraImageUri", String.valueOf(mCapturedImageURI));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
mCapturedImageURI = Uri.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void setmCapturedImageURI(Uri _uri) {
mCapturedImageURI = _uri;
}
StockBarangAction.java
private void chooseCamera() {
if (reqPermissionClass.checkPermission(Manifest.permission.CAMERA, ReqPermissionClass.PERMISSIONS_REQ_CAMERA)) {
runCamera();
}
}
public void runCamera(){
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
KantinActivity parent = (KantinActivity) getActivity();
parent.setmCapturedImageURI(mCapturedImageURI);
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
getActivity().startActivityForResult(takePictureIntent, KantinActivity.RESULT_CAMERA);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (reqPermissionClass.checkOnPermissionResult(requestCode,grantResults,
ReqPermissionClass.PERMISSIONS_REQ_WRITEEXTERNALSTORAGE)||
reqPermissionClass.checkOnPermissionResult(requestCode,grantResults,
ReqPermissionClass.PERMISSIONS_REQ_CAMERA)) {
chooseCamera();
}
else {
Toast.makeText(getActivity(), getString(R.string.cancel_permission_read_contacts), Toast.LENGTH_SHORT).show();
}
}
public void setFileImageCatalog(boolean isCamera, File mFile, String imageContent) {
mFileImageCatalog = mFile;
Picasso mPic;
if(MyApiClient.PROD_FLAG_ADDRESS)
mPic = MyPicasso.getImageLoader(getActivity());
else
mPic= Picasso.with(getActivity());
if(mFileImageCatalog != null){
if(isCamera) {
mPic.load(new File(imageContent))
.error(R.drawable.icon_no_photo)
.placeholder(R.drawable.progress_animation)
.fit()
.centerInside()
.into(img_catalog);
}else
mPic.load(imageContent)
.error(R.drawable.icon_no_photo)
.fit()
.centerInside()
.placeholder(R.drawable.progress_animation)
.into(img_catalog);
}
}
StockBarangAction.java is a fragment that call intent camera, the result catch by KantinActivity(Extend BaseActivity) where the image get resize using "GeneralizeImage" function, then sent back to fragment with "setFileImageCatalog" function.
What I want to know is :
does the camera app on the Samsung Galaxy S5 really have problem ?
Why my apps get killed and some components become null (like TextView). I try to "findViewId" again, but its still not working. Do i need to
save the textview instance?
Thank you and sorry for my English.
Most likely, your process is being terminated while your app is in the background. This is perfectly normal. You will get a fresh process when needed, and the user may be returned to whatever activity they had been on previously.
Your app needs to handle this case, because it is not only going to happen when you take a picture — it can happen for other reasons as well:
User is in your app
User presses HOME
Five minutes later, Android terminates your process to free up system RAM for other processes
Two minutes after that, the user goes back to your app (home screen launcher icon, overview/recent-tasks screen, etc.)
does camera app samsung galaxy s5 really have problem ?
No.
Do i need to save the textview instance ?
That is not possible.

Having trouble exporting .txt files to Google Drive through play services API

I have an Android app that writes .txt files to the downloads folder based off your inputs, a listview that displays all your downloads and lets you click to view them (I have this working), and I'm now trying to code a way to upload them to Google Drive. I have done the developer's verification process with the SHA1 key so it should be fine as far as that goes. I often see this demo app that takes pictures and uploads them being recommended and it looks like a good code to start with and modify, but when I run it on my phone, it doesn't work-it just repeatedly asks me to select my account endlessly. The java code inside the project itself is this (I'm pretty new and don't quite understand how all of it works, but this is for the google demo in the link):
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "drive-quickstart";
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = mBitmapToSave;
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
// If the operation was not successful, we cannot do anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle("Android Photo.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
// Called after a photo has been taken.
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
mBitmapToSave = (Bitmap) data.getExtras().get("data");
}
break;
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
// Just start the camera again for another photo.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
}
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
if (mBitmapToSave == null) {
// This activity has no UI of its own. Just start the camera.
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
REQUEST_CODE_CAPTURE_IMAGE);
return;
}
saveFileToDrive();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
}
And in the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gms.drive.sample.quickstart"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.google.android.gms.drive.sample.quickstart.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
And with that, my main two questions are:
Any idea why the quick start project from Google is behaving the way it is?
If it's not too much, but what parts of the java code do I need to modify to make it upload a .txt file after pressing a button?
You are supposed to create a project in Google Api COnsole,then enable Drive API. Then create required credentials(SHA-1, key, CLIENT-ID) for the the android app to connect with drive api.
After getting all the credentials, include them in Manifest file and String File.
Follow the instructions here, QuickStart Android Instructions

Android PDF Load Timing

The requirements: ensure that the PDF document is deleted from the device after the user has left the PDF viewing screen
The problem: on certain devices (Samsung 4.4.2 and Samsung 4.1.2 for sure, but not Asus 4.2.1) only the first time that the PDF is requested after restarting the application an error message is displayed stating "This document cannot be opened". Thereafter the PDF will load normally. I'm thinking this is a timing issue due to processes that need to be started the first time, but are running after the first attempted load.
The code: note that createFile() is called first, then startActivityForIntentResult()
private File file;
private ArrayList<Uri> uriList = new ArrayList<Uri>();
private void createFile() {
int fileNameLength = pdfFileName[0].length();
String fileName = pdfFileName[0].substring(0, fileNameLength - 4) + DateTime.now();
String fileExtension = pdfFileName[0].substring(fileNameLength - 4, fileNameLength);
byte[] content = Base64.decodeBase64(pdfData[0].getBytes());
BufferedOutputStream outputStream = null;
try {
File path = new File(getExternalFilesDir(null).getAbsolutePath(), "temp");
if (!path.exists()) {
path.mkdirs();
}
file = new File(path, fileName + fileExtension);
outputStream = new BufferedOutputStream(new FileOutputStream(file));
outputStream.write(content);
file.deleteOnExit();
uriList.add(Uri.fromFile(file));
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static int REQUEST_CODE = 1;
private Intent intent;
private void startActivityForIntentResult() {
if (file.exists()) {
Uri targetUri = uriList.get(0);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivityForResult(intent, REQUEST_CODE);
}
catch (ActivityNotFoundException e) {
toastTitle = "Error Displaying PDF";
toastMessage = "Please make sure you have an application for viewing PDFs installed on your device and try again.";
toast = new GenericCustomToast();
toast.show(toastTitle, toastMessage, QueryForPDF.this);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_CANCELED && requestCode == REQUEST_CODE) {
if(!file.delete()) {
file.delete();
}
}
searchAgain();
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(!file.delete()) {
file.delete();
}
searchAgain();
}
#Override
public void onStop() {
super.onStop();
if(!file.delete()) {
file.delete();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(!file.delete()) {
file.delete();
}
}
EDIT: I have also tried implementing a callback to be absolutely certain that createFile() has finished it's work. I even tried adding delays (of different time increments) as well as adding (the completely unnecessary) flags for Intent.FLAG_GRANT_READ_URI_PERMISSION, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION.
I still don't know why this works, but here's the solution in case anyone else runs into this issue:
It's the directory where the file is created. For some reason on the two Samsung devices there was something different in how the files were either accessed or created versus the Asus device. So File path = new File(getExternalFilesDir(null).getAbsolutePath(), "temp"); becomes File path = new File(getExternalCacheDir().getAbsolutePath()); and the problem goes away.

Categories

Resources