I have an application that request DownloadManager to start a download.
What I want to do is launch my app when user clicks on the download notification for the download that my app requested from DownloadManager. Below is the code in BroadcastReceiver for DownloadManager broadcasts.
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action))
{
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
long dlRef = getDlRef();
if (downloadId != dlRef) {
Log.d(Constants.TAG, "MY_DL_ID: " + dlRef + " EVENT FOR: " + downloadId);
} else {
Log.d(Constants.TAG, "Starting my activity");
Intent i = new Intent(context, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
How can I do that? In above code I get downloadId as 0.
Thanks,
Vinay
You want to be using:
intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)
which returns an long array.
After starting the download you can simply start your application as: Intent launchint = getPackageManager().getLaunchIntentForPackage("com.package.yourapp");
startActivity(launchint );
Related
I am having some problems with the following.
When a file is downloaded, I show a notification to the user, when he/she tabs the notification it searches for the applicable application (example PDF reader) to open the file with.
Eveything works when I tab the notification but when NO PDF reader is installed no toast message is shown to the user.
Could somebody assist me please? I know the try block is empty as I do not know exactly what comes in there to invoke the toast message.
Thank you.
EDIT: It works when I uncomment "context.startActivity(target);" but this starts the open process automatically, it should start when the user tabs the notification.
Notification code:
if (file.getName().endsWith(".pdf")) {
Intent install = openPdf(urlPath, context, mNotificationManager,
NOTIFYCATIONID);
PendingIntent pending = PendingIntent.getActivity(context, 0, install, 0);
mBuilder = new NotificationCompat.Builder(context)
.setContentTitle(appName)
.setContentText("ready to open pdf.");
mBuilder.setContentIntent(pending);
mBuilder.setSmallIcon(R.drawable.placeholder);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
Code to open the PDF file:
public static Intent openPdf(String urlPath, Context context,
NotificationManager mNotificationManager, int NOTIFYCATIONID) {
File file = new File(urlPath);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = file.getName().substring(file.getName().lastIndexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext).toLowerCase();;
Intent target = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
target.setDataAndType(Uri.fromFile(file), type);
target.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
try {
//context.startActivity(target);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
mNotificationManager.cancel(NOTIFYCATIONID);
return target;
}
You shouldn't try to start an Activity to determine whether it exists. Instead you can check with PackageManager if there is Activity that can handle your Intent, without starting it.
Try one of the following methods (they are all equivalent):
PackageManager pm = context.getPackageManager();
if (pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) == null) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
or:
PackageManager pm = context.getPackageManager();
if (intent.resolveActivity(pm) == null) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
or:
PackageManager pm = context.getPackageManager();
if (pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) == 0) {
Toast.makeText(context, "No application found to open PDF, please install one.", Toast.LENGTH_SHORT).show();
}
And instead of cancelling the notification in openPdf you can simply return null if there is no available app and don't try to show the notification at all.
I have this code for download by download manger,
code:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription(name);
request.setTitle("دانلود ویدیو");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir("/mlindr/101ideas/video", video);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//manager.enqueue(request);
long id = manager.enqueue(request);
Download class:
public static boolean isDownloadManagerAvailable(Context context) {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
return false;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
} catch (Exception e) {
return false;
}
}
Now I want when click on download processing in notification, current download be cancelled.
If you want to cancel download action to the download notification you need to use custom notification instead of built-in notification.
or you can open download list with cancle action one the user click in the notification
You can read more about download manager click action here
****** Now a have completed the code, but the notification display is running again after cancel !
I'm using the DownloadManager for downloading a file by url, it works fine.
Code creating Manager:
String[] url = {urlsProz,urlsMb};
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url[i]));
downloadFile=url[i];
request.setDescription("Some description");
request.setTitle("Some titles");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
String s= Environment.DIRECTORY_DOWNLOADS;
Log.i("*** testDownloadManager***",s+"/"+url[i]);
request.setDestinationInExternalPublicDir(s, "name-of-the-file"+(++j)+".ext");
// get download service and enqueue file
manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//Download progress will be showing in the notification bar
downloadId=manager.enqueue(request);
Log.i("*** testDownloadManager***","downloadId:"+downloadId);
My code after pressing the cancel-Button:
if (manager != null) {
//remove() method will return the number of downloads removed
//Any downloaded files (complete or partial) will be deleted
int i = manager.remove(downloadId);
Log.i(TAG, downloadId + "," + i + " cancelled");
NotificationManager notifManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
//notifManager.cancelAll(); //doesn'nt work
manager = null;
}
The manager is cancelled but the notification display is still running even after the app.
Any ideas how to cancel this notification ?
Regards Wicki
cancelAll() method only cancel notification created by your application.
I think you use DownloadManager as this:
// start download
Request request = new Request(Uri.parse(urltoDownload));
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
request.setTitle("my title");
long enqueue = downloadManager.enqueue(request);
So it's DownloadManager app (service) which create notification, and it's only DownloadManager app could cancel it.
You can't cancel other apps notifications, thats not possible.
DownloadManager dm = (DownloadManager) c
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request dlrequest = new DownloadManager.Request(
Uri.parse(url));
dlrequest
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setTitle("Downloading")
.setDescription("Downloading in Progress..")
.setDestinationInExternalPublicDir("folder_name", name + ".jpg")
**.setNotificationVisibility(visibility)**
.allowScanningByMediaScanner();
dm.enqueue(dlrequest);
.setNotificationVisibility(visibility) -->set visibility true or false. and its done..!
I'm using following code for sending text message via Intent ( can not ask for permission so smsmanager is not an option)
//Code from this question
// <http://stackoverflow.com/questions/20079047/android-kitkat-4-4-hangouts-cannot-handle-sending-sms-intent>
private void sendsms(String toContact, String text){
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Android 4.4 and up
{
String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(this);
intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(toContact)));
intent.putExtra("sms_body", text);
if (defaultSmsPackageName != null) // Can be null in case that there is no default, then the user would be able to choose any app that supports this intent.
{
intent.setPackage(defaultSmsPackageName);
}
}
else
{
intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("address", toContact);
intent.putExtra("sms_body", text);
}
this.startActivity(intent);
}
and I'm calling this in a for loop :
for(int i = 0; i<4 ;i++) {
sendsms(phoneNo[i],smsBody[i]);
}
Now the problem is whenever user gets to this line, the void will be called 4 times, but user will only see the last message in the devices default messaging app ready to be sent, but to get to the other ones, user should press back on the device and if not, he/she would never see the other messages.
what I need to be done is using a method like startActivityForResult(); so each time user sends the message he would be redirected to my app, and then my app starts another activity for the next text message.
any idea?
Thanks in advance
First of all you need to create a String with your phones, for that you have to use "; " as separator, but take care with Samsung, in those devices you have to use ", ".
So your code has to be similar to this one:
private void sendSms(String phone1, String phone2){
String separator = "; "
if (Build.MANUFACTURER.toLowerCase().contains("samsung"))
separator = ", "
String phones = phone1 + separator + phone2...
Intent intentSms = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phones, null));
intentSms.putExtra("sms_body","your text") // Just if you want to add text
startActivity(intentSms);
}
Hi i'm downloading a file and i'm wanting to fire an ACTION_VIEW Intent once its finished downloading. so does anyone know how to detect when DownloadManager has finished.
heres how i'm running DownloadManager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(filename);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
ContextWrapper c = new ContextWrapper(getBaseContext());
String filePath = c.getFilesDir().getPath();
request.setDestinationInExternalFilesDir(getBaseContext(), filePath, filename);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Toast.makeText(getBaseContext(), "Downloading...", Toast.LENGTH_LONG).show();
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String path = getFilesDir().getPath() +"/" + filename;
File f = new File(path);
Intent myIntent = new Intent(Intent.ACTION_VIEW);
myIntent.setData(Uri.fromFile(f));
startActivity(myIntent);
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
It looks OK for me. That example is not working? But different thing is how you fire next Intent in onReceive method. Please try use your action in
myIntent = new Intent(YourActionClass.class);
Figured it out myself i needed to set the mimeType so it knows which apps to look for