One of the challenges in working with Ti.Android.Intent‘s is knowing if the device has an app installed that will be able to handle the request. The recommended approach until now was to wrap your startActivity statement within a try/catch statement.
With the new Android.Tools module you can now check if a Ti.Android.Intent has a receiver before submitting. This allows you to write more defensive code blocks like the one below:
//Add our tools module
var tools = require('bencoding.android.tools');
var platformTools = tools.createPlatform();
//Check we have external storage access
if(!Ti.Filesystem.isExternalStoragePresent()){
alert("Access to external storage required");
return;
}
//Create a Ti.File to our sample file
var pdfSource = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + 'your_file.pdf');
//Create a temp file so the intent can read the file
var timeStampName = new Date().getTime();
var tempFile = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,timeStampName +'.pdf');
if(tempFile.exists()){
tempFile.deleteFile();
}
tempFile.write(pdfSource.read());
pdfSource = null;
//Create our PDF intent
var intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: "application/pdf",
data: session.tempFile.nativePath
});
//Check that the device can open the intent
if(platformTools.intentAvailable(intent)){
//Since the device can open the intent run startActivity
try {
Ti.Android.currentActivity.startActivity(intent);
} catch(e) {
Ti.API.debug(e);
alert('Something went wrong');
}
}else{
//No PDF reader to we need to alert the user to go get one.
alert("Please go to the Google Play Store and download a PDF reader");
}
Android.Tools project
Github Repo:
https://github.com/benbahrenburg/benCoding.Android.Tools
Documentation:
https://github.com/benbahrenburg/benCoding.Android.Tools/tree/master/documentation
Example:
https://github.com/benbahrenburg/benCoding.Android.Tools/tree/master/example