Open File on Notification click downloaded using Retrofit2How can I open a URL in Android's web browser from my application?Sending an Intent to browser to open specific URLDownload a file with Android, and showing the progress in a ProgressDialogIs there a way to get the source code from an APK file?How to start new activity on button clickNotification passes old Intent ExtrasCopying data from one file to another file very slow in android?How to open the Google Play Store directly from my Android application?NanoHTTPD. Cache InputStream to file and continue streamingOpen a Directory of Downloads by Clicking the Notification

What defines a dissertation?

Time travel short story where a man arrives in the late 19th century in a time machine and then sends the machine back into the past

Lay out the Carpet

Your magic is very sketchy

Should my PhD thesis be submitted under my legal name?

The plural of 'stomach"

Why did Kant, Hegel, and Adorno leave some words and phrases in the Greek alphabet?

Displaying the order of the columns of a table

Where in the Bible does the greeting ("Dominus Vobiscum") used at Mass come from?

What is difference between behavior and behaviour

Is a roofing delivery truck likely to crack my driveway slab?

I'm in charge of equipment buying but no one's ever happy with what I choose. How to fix this?

How will losing mobility of one hand affect my career as a programmer?

Cynical novel that describes an America ruled by the media, arms manufacturers, and ethnic figureheads

How do I keep an essay about "feeling flat" from feeling flat?

Print name if parameter passed to function

Mapping a list into a phase plot

What will be the benefits of Brexit?

If you attempt to grapple an opponent that you are hidden from, do they roll at disadvantage?

Greatest common substring

Can somebody explain Brexit in a few child-proof sentences?

What's the purpose of "true" in bash "if sudo true; then"

Everything Bob says is false. How does he get people to trust him?

Coordinate position not precise



Open File on Notification click downloaded using Retrofit2


How can I open a URL in Android's web browser from my application?Sending an Intent to browser to open specific URLDownload a file with Android, and showing the progress in a ProgressDialogIs there a way to get the source code from an APK file?How to start new activity on button clickNotification passes old Intent ExtrasCopying data from one file to another file very slow in android?How to open the Google Play Store directly from my Android application?NanoHTTPD. Cache InputStream to file and continue streamingOpen a Directory of Downloads by Clicking the Notification













0















I am downloading a PDF using retrofit webservice. And then I am showing a self created notification to show that the file has been downloaded. But I am not able to understand how to show or open the file when clicked on notification.



Here's my notification call:



RestClient.webServices()
.downloadFile(id)
.enqueue(new Callback<ResponseBody>()
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)

if (response.isSuccessful())

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.e(TAG, "file download was a success? " + writtenToDisk);

if (writtenToDisk)

showToast("Invoice downloaded successfully");
showDownloadNotification();





@Override
public void onFailure(Call<ResponseBody> call, Throwable t)


);


Here's the writeResponseBodyToDisk() function:



private boolean writeResponseBodyToDisk(ResponseBody body) 
try
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/bill.pdf");

InputStream inputStream = null;
OutputStream outputStream = null;

try
byte[] fileReader = new byte[4096];

long fileSize = body.contentLength();
long fileSizeDownloaded = 0;

inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);

while (true)
int read = inputStream.read(fileReader);

if (read == -1)
break;


outputStream.write(fileReader, 0, read);

fileSizeDownloaded += read;

// Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);


outputStream.flush();

return true;
catch (IOException e)
return false;
finally
if (inputStream != null)
inputStream.close();


if (outputStream != null)
outputStream.close();


catch (IOException e)
return false;




And here's the showDownloadNotification() function:



void showDownloadNotification() 
try
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
// startActivity(intent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo_winds)
.setContentTitle("Invoice downloaded")
.setContentText("")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build());

catch (Exception e)
Log.e(TAG, "Notification " + e.toString());




So when I tap on the created notification, nothing happens, and when I uncomment startActivity (intent); it crashes by saying cannot find activity for intent.
How do I open the file I have downloaded by clicking the notification I have created for it?










share|improve this question
























  • Have you checked developer.android.com/training/notify-user/navigation

    – ashazar
    Mar 6 at 13:23











  • @ashazar Yes i have seen, wasnt able to find where and how i am supposed to open a file/folder from my notification click

    – Maximus
    Mar 6 at 13:30















0















I am downloading a PDF using retrofit webservice. And then I am showing a self created notification to show that the file has been downloaded. But I am not able to understand how to show or open the file when clicked on notification.



Here's my notification call:



RestClient.webServices()
.downloadFile(id)
.enqueue(new Callback<ResponseBody>()
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)

if (response.isSuccessful())

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.e(TAG, "file download was a success? " + writtenToDisk);

if (writtenToDisk)

showToast("Invoice downloaded successfully");
showDownloadNotification();





@Override
public void onFailure(Call<ResponseBody> call, Throwable t)


);


Here's the writeResponseBodyToDisk() function:



private boolean writeResponseBodyToDisk(ResponseBody body) 
try
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/bill.pdf");

InputStream inputStream = null;
OutputStream outputStream = null;

try
byte[] fileReader = new byte[4096];

long fileSize = body.contentLength();
long fileSizeDownloaded = 0;

inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);

while (true)
int read = inputStream.read(fileReader);

if (read == -1)
break;


outputStream.write(fileReader, 0, read);

fileSizeDownloaded += read;

// Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);


outputStream.flush();

return true;
catch (IOException e)
return false;
finally
if (inputStream != null)
inputStream.close();


if (outputStream != null)
outputStream.close();


catch (IOException e)
return false;




And here's the showDownloadNotification() function:



void showDownloadNotification() 
try
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
// startActivity(intent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo_winds)
.setContentTitle("Invoice downloaded")
.setContentText("")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build());

catch (Exception e)
Log.e(TAG, "Notification " + e.toString());




So when I tap on the created notification, nothing happens, and when I uncomment startActivity (intent); it crashes by saying cannot find activity for intent.
How do I open the file I have downloaded by clicking the notification I have created for it?










share|improve this question
























  • Have you checked developer.android.com/training/notify-user/navigation

    – ashazar
    Mar 6 at 13:23











  • @ashazar Yes i have seen, wasnt able to find where and how i am supposed to open a file/folder from my notification click

    – Maximus
    Mar 6 at 13:30













0












0








0








I am downloading a PDF using retrofit webservice. And then I am showing a self created notification to show that the file has been downloaded. But I am not able to understand how to show or open the file when clicked on notification.



Here's my notification call:



RestClient.webServices()
.downloadFile(id)
.enqueue(new Callback<ResponseBody>()
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)

if (response.isSuccessful())

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.e(TAG, "file download was a success? " + writtenToDisk);

if (writtenToDisk)

showToast("Invoice downloaded successfully");
showDownloadNotification();





@Override
public void onFailure(Call<ResponseBody> call, Throwable t)


);


Here's the writeResponseBodyToDisk() function:



private boolean writeResponseBodyToDisk(ResponseBody body) 
try
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/bill.pdf");

InputStream inputStream = null;
OutputStream outputStream = null;

try
byte[] fileReader = new byte[4096];

long fileSize = body.contentLength();
long fileSizeDownloaded = 0;

inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);

while (true)
int read = inputStream.read(fileReader);

if (read == -1)
break;


outputStream.write(fileReader, 0, read);

fileSizeDownloaded += read;

// Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);


outputStream.flush();

return true;
catch (IOException e)
return false;
finally
if (inputStream != null)
inputStream.close();


if (outputStream != null)
outputStream.close();


catch (IOException e)
return false;




And here's the showDownloadNotification() function:



void showDownloadNotification() 
try
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
// startActivity(intent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo_winds)
.setContentTitle("Invoice downloaded")
.setContentText("")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build());

catch (Exception e)
Log.e(TAG, "Notification " + e.toString());




So when I tap on the created notification, nothing happens, and when I uncomment startActivity (intent); it crashes by saying cannot find activity for intent.
How do I open the file I have downloaded by clicking the notification I have created for it?










share|improve this question
















I am downloading a PDF using retrofit webservice. And then I am showing a self created notification to show that the file has been downloaded. But I am not able to understand how to show or open the file when clicked on notification.



Here's my notification call:



RestClient.webServices()
.downloadFile(id)
.enqueue(new Callback<ResponseBody>()
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)

if (response.isSuccessful())

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.e(TAG, "file download was a success? " + writtenToDisk);

if (writtenToDisk)

showToast("Invoice downloaded successfully");
showDownloadNotification();





@Override
public void onFailure(Call<ResponseBody> call, Throwable t)


);


Here's the writeResponseBodyToDisk() function:



private boolean writeResponseBodyToDisk(ResponseBody body) 
try
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/bill.pdf");

InputStream inputStream = null;
OutputStream outputStream = null;

try
byte[] fileReader = new byte[4096];

long fileSize = body.contentLength();
long fileSizeDownloaded = 0;

inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);

while (true)
int read = inputStream.read(fileReader);

if (read == -1)
break;


outputStream.write(fileReader, 0, read);

fileSizeDownloaded += read;

// Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);


outputStream.flush();

return true;
catch (IOException e)
return false;
finally
if (inputStream != null)
inputStream.close();


if (outputStream != null)
outputStream.close();


catch (IOException e)
return false;




And here's the showDownloadNotification() function:



void showDownloadNotification() 
try
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
// startActivity(intent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo_winds)
.setContentTitle("Invoice downloaded")
.setContentText("")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build());

catch (Exception e)
Log.e(TAG, "Notification " + e.toString());




So when I tap on the created notification, nothing happens, and when I uncomment startActivity (intent); it crashes by saying cannot find activity for intent.
How do I open the file I have downloaded by clicking the notification I have created for it?







android android-intent android-notifications android-pendingintent






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 12:31









Natig Babayev

449313




449313










asked Mar 6 at 13:05









MaximusMaximus

266




266












  • Have you checked developer.android.com/training/notify-user/navigation

    – ashazar
    Mar 6 at 13:23











  • @ashazar Yes i have seen, wasnt able to find where and how i am supposed to open a file/folder from my notification click

    – Maximus
    Mar 6 at 13:30

















  • Have you checked developer.android.com/training/notify-user/navigation

    – ashazar
    Mar 6 at 13:23











  • @ashazar Yes i have seen, wasnt able to find where and how i am supposed to open a file/folder from my notification click

    – Maximus
    Mar 6 at 13:30
















Have you checked developer.android.com/training/notify-user/navigation

– ashazar
Mar 6 at 13:23





Have you checked developer.android.com/training/notify-user/navigation

– ashazar
Mar 6 at 13:23













@ashazar Yes i have seen, wasnt able to find where and how i am supposed to open a file/folder from my notification click

– Maximus
Mar 6 at 13:30





@ashazar Yes i have seen, wasnt able to find where and how i am supposed to open a file/folder from my notification click

– Maximus
Mar 6 at 13:30












1 Answer
1






active

oldest

votes


















0














It seems like you're passing wrong data type to intent on showDownloadNotification() method. Here is how you can open PDF:



Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "application/pdf"); // here we set correct type for PDF
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023823%2fopen-file-on-notification-click-downloaded-using-retrofit2%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    It seems like you're passing wrong data type to intent on showDownloadNotification() method. Here is how you can open PDF:



    Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(selectedUri, "application/pdf"); // here we set correct type for PDF
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);






    share|improve this answer



























      0














      It seems like you're passing wrong data type to intent on showDownloadNotification() method. Here is how you can open PDF:



      Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");

      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setDataAndType(selectedUri, "application/pdf"); // here we set correct type for PDF
      intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);






      share|improve this answer

























        0












        0








        0







        It seems like you're passing wrong data type to intent on showDownloadNotification() method. Here is how you can open PDF:



        Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(selectedUri, "application/pdf"); // here we set correct type for PDF
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);






        share|improve this answer













        It seems like you're passing wrong data type to intent on showDownloadNotification() method. Here is how you can open PDF:



        Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(selectedUri, "application/pdf"); // here we set correct type for PDF
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 9:46









        Natig BabayevNatig Babayev

        449313




        449313





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023823%2fopen-file-on-notification-click-downloaded-using-retrofit2%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived