2015-06-25 3 views
1

Из моего приложения я загружаю некоторые музыкальные файлы и сохраняю их в папке. На панели уведомлений отображается статус загрузки. Когда загрузка завершается, если нажимается уведомление, мое устройство Android должно непосредственно перейти к папке назначения, аналогичной «перейти в папку» на ПК после завершения любой загрузки.Как перейти к папке назначения при нажатии на уведомление загрузки

Я пробовал его из-под кода, но он не работает. Это просто открытие приложения.

public class Temp extends Activity { 

    String[] link; 
    String[] items; 
    String song_link; 
    String song_name; 
    int song_index; 
    int link_index; 
    String url_link; 
    Exception error; 
    private ProgressBar mProgress; 
    long total = 0; 
    boolean downloadStatus = false; 
    ProgressDialog progressBar; 
    private Handler progressBarHandler = new Handler(); 
    int progressBarStatus = 0; 
    Uri selectedUri; 
    Intent intent; 
    PendingIntent resultPendingIntent; 



    NotificationCompat.Builder mBuilder= 
      new NotificationCompat.Builder(this) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("My notification") 
      .setContentText("Downloading"); 
    NotificationManager mNotificationManager; 

    int id=1; 


    private class DownloadFilesTask extends AsyncTask<String, Integer, Long> { 
     protected Long doInBackground(String... urls) { 
      mNotificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
      // mProgress = (ProgressBar) findViewById(R.id.progress_bar); 
      url_link = urls[0]; 
       try { 
        /* runOnUiThread(new Runnable() { 
         public void run() { 
          Toast.makeText(getApplicationContext(),"link: "+url_link,Toast.LENGTH_SHORT).show(); 

         } 
        });*/ 
        int count; 
        URL url = new URL(url_link); 
        URLConnection conexion = url.openConnection(); 
        conexion.connect(); 
        // this will be useful so that you can show a typical 0-100% progress bar 
        final int lenghtOfFile = conexion.getContentLength(); 

        // Download the file 
        InputStream input = new BufferedInputStream(url.openStream()); 
        // String name = "first.mp3"; 

         File folder = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_MUSIC), "Vaishnav Songs"); 
          if (!folder.mkdirs()) { 
           Log.e(DOWNLOAD_SERVICE, "Directory not created"); 
          } 

         File filename = new File(folder,song_name); 
         OutputStream output = null; 

          output = new BufferedOutputStream(new FileOutputStream(filename)); 

        byte data[] = new byte[1024]; 


        mBuilder.setContentTitle(song_name); 
        int percentage; 
        id = song_index*10 + link_index; 
        while ((count = input.read(data)) != -1) { 
         total += count; 
         // publishing the progress.... 
        // publishProgress((int)(total*100/lenghtOfFile)); 
         percentage = (int)(total*100/lenghtOfFile) ; 
         if(percentage%5 ==0){ 
          new Thread(new Runnable() { 
           public void run() { 
           mBuilder.setProgress(100, (int)total*100/lenghtOfFile, false); 
           // Displays the progress bar for the first time. 
           mNotificationManager.notify(id, mBuilder.build()); 

           } 
          }).start(); 
         } 



         output.write(data, 0, count); 
        } 

        output.flush(); 
        output.close(); 
        input.close(); 
        mBuilder.setContentIntent(resultPendingIntent); 
        new Thread(new Runnable() { 
         public void run() { 
         mBuilder.setContentText("Download complete") 
         // Removes the progress bar 
           .setProgress(100,100,false); 
         mNotificationManager.notify(id, mBuilder.build()); 

         } 
        }).start(); 



        } 
        catch (Exception e) { 
         error = e; 
         runOnUiThread(new Runnable() { 
          public void run() { 
           Toast.makeText(getApplicationContext(),"Error: "+error,Toast.LENGTH_SHORT).show(); 

          } 
         }); 
        } 





       // Escape early if cancel() is called 
       // if (isCancelled()) break; 


      return total; 
     } 

     protected void onProgressUpdate(Integer... progress) { 
      progressBarStatus = progress[0]; 




     } 

     protected void onPostExecute(Long result) { 
      /* Toast.makeText(getApplicationContext(),"Downloaded "+result+" bytes",Toast.LENGTH_SHORT).show();*/ 
      Intent intent = getIntent(); 
      finish(); 
      //startActivity(intent); 
    } 

    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     selectedUri = Uri.parse(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_MUSIC) + "/"+"Vaishnav Songs"+"/"); 
      intent = new Intent(Intent.ACTION_VIEW); 
      intent.setDataAndType(selectedUri, "resource/folder"); 
      resultPendingIntent = 
       PendingIntent.getActivity(
       this, 
       0, 
       intent, 
       PendingIntent.FLAG_UPDATE_CURRENT 
      ); 

     song_name = (String) getIntent().getExtras().getString("songName"); 
     song_link = (String) getIntent().getExtras().getString("songLink"); 
     song_index = getIntent().getIntExtra("songIndex",0); 
     link_index = getIntent().getIntExtra("position",0); 
     Toast.makeText(getApplicationContext(),"Download started. Check progress in notification panel",Toast.LENGTH_SHORT).show(); 

     //new DownloadFilesTask().execute(song_link); 
     DownloadFilesTask task = new DownloadFilesTask(); 
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,song_link); 
     finish(); 
    } 
} 

ответ

0

Откройте для себя этот https://developer.android.com/reference/android/app/Notification.Builder.html
Вы можете попробовать добавить setContentIntent(PendingIntent intent) в уведомлении с действием для открытия диспетчера файлов.

+0

спасибо за ваше предложение. Но это я знаю и уже использую в коде. Возможно, я ошибаюсь в создании намерения открыть папку. вы можете предложить что-то для этого. – prem

Смежные вопросы