2012-05-19 5 views
0

진행률 대화 상자를 열고 파일을 다운로드하는 스레드가 있습니다. 스레드가 파일을 다운로드하는 동안 진행률 표시 줄을 업데이트합니다. 그러나 진행 대화 상자가 숨겨진 경우 스레드는 알림을 생성하고 알림의 진행률 막대를 업데이트합니다. 나는 이것을 만들고 싶어 : 사용자가 알림을 클릭하면, 안드로이드는 활동을 열고 진행 대화 상자를 보여줍니다. 어떻게해야합니까?알림을 클릭 할 때 코드를 실행하는 방법은 무엇입니까?

public void downloadAction(int id) { 
    if(id<0 || id>data.length) { IO.showNotify(MusicActivity.this, getResources().getStringArray(R.array.errors)[4]); return; } 
    final int itemId = id; 

    AsyncTask<Void, Integer, Boolean> downloadTask = new AsyncTask<Void, Integer, Boolean>() { 
     ProgressDialog progressDialog = new ProgressDialog(MusicActivity.this); 
     String error = null; 
     int nId = -1; 
     int progressPercent = 0; 
     boolean notificated = false; 
     int urlFileLength; 
     String FILE_NAME = fileName(data.getName(itemId)); 

     @Override 
     protected void onPreExecute() { 
      progressDialog.setTitle(data.getName(itemId)); 
      progressDialog.setIndeterminate(false); 
      progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      progressDialog.setCancelable(true); 
      progressDialog.setOnCancelListener(new OnCancelListener() { 
       public void onCancel(DialogInterface dialog) { 
        cancel(true); 
       } 
      }); 

      progressDialog.setButton(Dialog.BUTTON_POSITIVE, getResources().getString(R.string.hide), new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        progressDialog.hide(); 
       } 
      }); 
      progressDialog.setButton(Dialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        if(progressDialog.isShowing()) { cancel(true); progressDialog.dismiss();} 
       } 
      }); 

      progressDialog.show(); 
      progressDialog.setProgressNumberFormat("");        
     } 

     @Override 
     protected Boolean doInBackground(Void... params) { 
      int localFileLength, len; 
      int fullProgress = 0; 
      byte[] bytes = new byte[1024]; 
      File rootDir = new File(PATH); 

      if(!rootDir.isDirectory()) rootDir.mkdir(); 

      try { 
       URLConnection urlConnection = new URL(data.getUrl(itemId)).openConnection(); 
       urlConnection.setConnectTimeout(20000); 
       urlConnection.setReadTimeout(60000); 

       localFileLength = (int) new File(FILE_NAME).length(); 
       urlFileLength = urlConnection.getContentLength(); 

       if (urlFileLength == 169 || urlFileLength == 0 || urlFileLength == -1) { 
        error = getResources().getStringArray(R.array.errors)[5]; 
        return false; 
       } 
       if (urlFileLength == localFileLength) { 
        error = getResources().getString(R.string.file_exist); 
        return false; 
       } else { 
        publishProgress(0, urlFileLength); 
        InputStream in = urlConnection.getInputStream(); 
        OutputStream out = new FileOutputStream(FILE_NAME); 

        while((len=in.read(bytes))!=-1) { 
         if(!isCancelled()) { 
          out.write(bytes, 0, len); 
          fullProgress += len; 
          publishProgress(fullProgress); 
         } else { 
          new File(FILE_NAME).delete(); 
          error = getResources().getString(R.string.stopped); 
          return false;        
         } 
        } 

       } 

      } catch (MalformedURLException e) { 
       new File(FILE_NAME).delete(); 
       error = getResources().getStringArray(R.array.errors)[2]; 
      } catch (IOException e) { 
       new File(FILE_NAME).delete(); 
       error = getResources().getStringArray(R.array.errors)[3]; 
      } 



      return true; 
     } 

     @Override 
     protected void onProgressUpdate(Integer ... progress) { 
      int tmp; 

      if (progress.length==2) { 
       progressDialog.setProgress(progress[0]); 
       progressDialog.setMax(progress[1]); 
      } else if(progress.length==1) { 
       if(!progressDialog.isShowing()) { 
        if(!notificated) { 
         nId = NotificationUtils.getInstace(MusicActivity.this).createDownloadNotification(data.getName(itemId)); 
         notificated = true; 
        } else { 
         tmp = (int) (progress[0]/(urlFileLength*0.01)); 
         if(progressPercent!=tmp) { 
          progressPercent = tmp; 
          NotificationUtils.getInstace(MusicActivity.this).updateProgress(nId, progressPercent); 
         } 
        } 
       } else { 
        progressDialog.setProgress(progress[0]); 
       } 
      } 
     } 

     @Override 
     protected void onPostExecute(Boolean result) { 
      if(result==true && error == null) { 
       if(progressDialog.isShowing()) { 
        IO.showNotify(MusicActivity.this, getResources().getString(R.string.downloaded) + " " + PATH); 
        progressDialog.dismiss(); 
       } else if (nId!=-1) { 
        NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId); 
        NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(data.getName(itemId) + " " + getResources().getString(R.string.finished)); 
       } 
      } else { 
       if(progressDialog.isShowing()) { 
        IO.showNotify(MusicActivity.this, error); 
        progressDialog.dismiss(); 
       } else if (nId!=-1){ 
        NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId); 
        NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(getResources().getString(R.string.error) + "! " + error); 
       } 
      } 

     } 

     @Override 
     protected void onCancelled() { 
      IO.showNotify(MusicActivity.this, getResources().getString(R.string.stopped)); 
     } 

    }; 

    if(downloadTask.getStatus().equals(AsyncTask.Status.PENDING) || downloadTask.getStatus().equals(AsyncTask.Status.FINISHED)) 
     downloadTask.execute(); 
} 

그리고 그 생성 통지 그게 두 가지 방법입니다 :

public int createDownloadNotification(String fileName) { 
    String text = context.getString(R.string.notification_downloading).concat(" ").concat(fileName); 
    RemoteViews contentView = createProgressNotification(text, text); 
    contentView.setImageViewResource(R.id.notification_download_layout_image, android.R.drawable.stat_sys_download); 

    return lastId++; 
} 


private RemoteViews createProgressNotification(String text, String topMessage) { 
    Notification notification = new Notification(android.R.drawable.stat_sys_download, topMessage, System.currentTimeMillis()); 
    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_download_layout); 
    contentView.setProgressBar(R.id.notification_download_layout_progressbar, 100, 0, false); 
    contentView.setTextViewText(R.id.notification_download_layout_title, text); 

    notification.contentView = contentView; 
    notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE; 

    Intent notificationIntent = new Intent(context, NotificationUtils.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 

    notification.contentIntent = contentIntent; 

    manager.notify(lastId, notification); 
    notifications.put(lastId, notification); 

    return contentView; 
} 

이 제발 도와주세요 ...

답변

0

나는 확실하지 않다 파일을 다운로드하는 나의 방법이다

하지만 알림 코드에 notification.contentIntent = contentIntent;이없고 manager.notify(lastId, notification); 줄 전에 누락 된 것 같습니다 :

notification.setLatestEventInfo(context, MyNotifyTitle, MyNotifiyText, contentIntent); 

MyNotifyTitle은 알림 제목이며, MyNotifyText는 텍스트입니다. contentIntent 앞에 추가하십시오.

MyIntent.putExtra("extendedTitle", notificationIntent); 
MyIntent.putExtra("extendedText" , notificationIntent); 

희망이 있습니다.

+0

setLatestEventInfo (...)는 내가 왜 그렇게하지 않았는가에 대해 부인했습니다. 그리고 당신이 내 문제를 잡지 않았다고 생각합니다. 나는 이것을 만들고 싶어 : 알림을 만든 후, 사용자가 알림을 클릭하면 스레드로 돌아가서, 그것을 만든 후 progressDialog.show();를 실행합니다. HOW? : – ruslanys

+0

오, 그래, 내가 잡았어, 고마워. – ruslanys

+0

그래, 미안, 너의 문제를 오해해서 도울 수 없어. – erdomester

관련 문제