返回从通知栏下载活动

发布于 2024-12-15 02:04:50 字数 8878 浏览 0 评论 0原文

我知道关于这个主题有很多问题,但没有人能回答我的具体问题,或者也许我无论如何都无法识别正确的答案!

就像Android Market下载一个文件时,Activity中有进度条,通知栏有进度条一样,点击通知进度条返回到原来的Activity,进度条会随着下载进度而更新。

我正在使用 AsyncTask 进行下载和创建&更新通知栏一切正常,但是当我单击通知时,它返回到相同的活动,但没有任何数据或进度条(空白活动),换句话说,它启动新活动并丢失额外内容和所有字段数据,包括活动进度条状态。

我尝试使用标志和意图,但在单击通知栏时未能加载原始活动,特别是在返回另一个活动然后转到主屏幕然后按通知栏时。

我通过以下方式运行下载:

df = new AsyncDownloadTask();
df.execute(m_item.getiid(),m_item.getipackage());

和代码片段(我更改了通知栏只是为了显示进度文本):

protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_app_display);
//get extras
Bundle extras = getIntent().getExtras();

    if (extras == null) {
        return;
    }
    itemId = extras.getString("id");
    itemStatus = extras.getString("IorU");
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
    progressBar.setVisibility(0);

   showUI();

}
private void showUI() {

if(m_item != null) { 

    TextView actvTitle = (TextView) findViewById(R.id.title_text);
    actvTitle.setText(m_item.geticategory());

    appinstall = (Button) findViewById(R.id.app_install_btn);
    appudinstall = (Button) findViewById(R.id.app_udinstall_btn);

    permlist = (LinearLayout) findViewById(R.id.app_perm); //
    info = (LinearLayout) findViewById(R.id.info);
    mList = (HeightListView) findViewById(R.id.app_perm_list);
    mList.setTextFilterEnabled(true);


    instTxt = (TextView) findViewById(R.id.app_install);

    TextView titleTxt = (TextView) findViewById(R.id.app_titlebig);
    TextView companyTxt = (TextView) findViewById(R.id.app_descbig);

    TextView descTxt = (TextView) findViewById(R.id.long_desc);
    TextView verTxt = (TextView) findViewById(R.id.version);

    //fill info
    titleTxt.setText(m_item.getititle());
    companyTxt.setText(m_item.geticompany());
    descTxt.setText(m_item.getidescription());
    verTxt.setText(" Version:" + m_item.getiversion());


}
   }

@Override
protected void onResume(){
super.onResume();
}

@Override
public Object onRetainNonConfigurationInstance() {
Toast.makeText (getApplicationContext(), "onRetainNonConfigurationInstance", Toast.LENGTH_SHORT).show();
return null;
}
@Override
protected void onDestroy() {
super.onDestroy();
/*
if(df != null)
{
  if(!df.isCancelled())
    df.cancel(true);
}
CN=true;
*/

}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStart() {
super.onStart(); 
}



private class AsyncDownloadTask extends AsyncTask<String, Integer, Void>
   {
  private int successCount;
  private int numTotalFiles;
  private File outputFile;
  private String pack;
  private int downloadErr = 0;


  @Override
  protected void onPreExecute()
  {
super.onPreExecute();

successCount = 0;
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
CN=false;
  }


  @Override
  protected Void doInBackground(String... params)
  {
    String remoteFilepath;
String id = params[0];
pack = params[1];
  remoteFilepath = "http://www.myserver/download/1.zip";

  String PATH = Environment.getExternalStorageDirectory()+ "/download/";
  File file = new File(PATH);
  file.mkdirs();
  try
  {
    if(isCancelled())
      return null;

    URL url = new URL(remoteFilepath);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setConnectTimeout(getConnectTimeout());
    c.setReadTimeout(getReadTimeout());
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    int filesize = c.getContentLength();
    if(filesize > 0)
    {

      outputFile = new File(file, "1.zip");
      FileOutputStream fos = new FileOutputStream(outputFile);

      InputStream is = c.getInputStream();
      int bytesRead, totalBytesRead = 0;
      byte[] bytes = new byte[BYTES_BUFFER_SIZE];
      String progress, kbytes;
      while(!isCancelled() && (bytesRead = is.read(bytes)) != -1)
      {
        totalBytesRead += bytesRead;
        fos.write(bytes, 0, bytesRead);
        if(!isCancelled() ) //&& loopCount++ % 20 == 0)
        {
          RemoteViews progressView = getProgressView(successCount + 1, numTotalFiles, totalBytesRead, filesize);
          if(progressView == null)
          {
            progress = "Download "+pack;
            kbytes = String.format("%s / %s", getStringByteSize(totalBytesRead), getStringByteSize(filesize));

            if(!isCancelled() && !CN){
              showNotification("Downloading File(s)", progress , kbytes);
              publishProgress(totalBytesRead,filesize);
            } else { return null; }
          }
          else
          {

            if(!isCancelled() && !CN){
              showNotification(progressView, "Downloading File(s)");
            } else { return null; }
          }

        }
      }
      fos.close();
      is.close();
      if(isCancelled())
        return null;

      successCount ++;
    }
    else
    {
    }
  }
  catch(Exception e)
  {
      e.printStackTrace();
    showNotification("Download Failed", "Download Progress", "Failed: " + (new File(remoteFilepath)).getName());
    //updateCancelInstall();
    publishProgress(100,100);
    notificationManager.cancel(42);
    downloadErr = 1;
    CN = true;
  }

return null;
  }

  @Override
  protected void onCancelled()
  {
super.onCancelled();
showNotification("Download Cancelled", "Download Progress", "Cancelled");
CN = true;
publishProgress(100,100);
notificationManager.cancel(42);
  }

  protected void onProgressUpdate(Integer... prog) {
  if(prog[0]<prog[1]){
      updateProgress(prog[0],prog[1],false);
  } else {
      updateProgress(100,100,true);
      notificationManager.cancel(42);
  }
  }


  @Override
 protected void onPostExecute(Void result)
 {
super.onPostExecute(result);
if(!CN){
    if(downloadErr==0) {
        showNotification("Installing", "Installing "+pack, "Completed");
        updateDLcount udl = new updateDLcount();
        udl.execute("hello"); 
        //updateCancelInstall();
        notificationManager.cancel(42);
    } else {

        showNotification("Download Error", "Failed to download "+pack, "Error");
        //updateCancelInstall();
        notificationManager.cancel(42);
       }
   }
 }
}

   protected RemoteViews getProgressView(int currentNumFile, int totalNumFiles, int  currentReceivedBytes, int totalNumBytes)
  {
    return null;
  }



   protected Class<?> getIntentForLatestInfo()
   {
 return DisplayApp.class;
   }

protected void showNotification(String ticker, String title, String content)
{

  Notification notification = new Notification(R.drawable.download_icon, ticker, System.currentTimeMillis());
  Intent i=new Intent(this, DisplayApp.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("id", itemId);
i.putExtra("IorU", "itemStatus");
i.putExtra("progrss", content);
  PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
  notification.setLatestEventInfo(getApplicationContext(), title, content, contentIntent);
  notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;

  notificationManager.notify(42, notification);
if(content.equalsIgnoreCase("Cancelled")||content.equalsIgnoreCase("Completed")||CN)notificationManager.cancel(42);
}
protected void updateProgress(int downsize, int totalsize, boolean cancel){

//Log.i("YYYY","cancel="+cancel);

if(!cancel || (downsize<totalsize)){
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
    TextView pb_t = (TextView) findViewById(R.id.progressbar_text);
    progressBar.setVisibility(0);
    pb_t.setVisibility(0);
    progressBar.setProgress((int)downsize*100/totalsize);
    pb_t.setText(String.format("%s / %s", getStringByteSize(downsize), getStringByteSize(totalsize)));
} else {
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
    TextView pb_t = (TextView) findViewById(R.id.progressbar_text);
    progressBar.setProgress(100);
    progressBar.setVisibility(4);
    pb_t.setVisibility(4);
    updateCancelInstall();
} 
}


protected void showNotification(RemoteViews remoteView, String ticker)
{
  Notification notification = new Notification(R.drawable.download_icon, ticker, System.currentTimeMillis());
  notification.contentView = remoteView;
  Intent i=new Intent(this, DisplayApp.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
  notification.contentIntent = PendingIntent.getActivity(this, 0, i, 0);
  //Log.d("YYYY","2:"+notification.contentIntent.toString());
  notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;

  notificationManager.notify(42, notification);
}

如果您可以通过代码、网址或任何模仿市场方式的文档来帮助我,我们将不胜感激。

谢谢

I know many questions been asked on this topic but none could answer my specific question or maybe I failed to recognize the right reply anyway!!

Just like Android Market during the download of a file with progressbar in the activity and progressbar in the notification bar, clicking the notification progressbar return back to the original activity with the progressbar updated with the download progress.

I am using AsyncTask for the download and creating & updating the notification bar all works fine, but when I click the notification it return me to same activity but without any data or progressbar (blank activity) in other word it start new activity and loose the extras and all fields data including the activity progressbar status.

I tried playing with flags and intent but failed to get my original activity loaded when clicking the notification bar specially when going back to another activity and then going to home screen then press the notification bar.

I run the download by:

df = new AsyncDownloadTask();
df.execute(m_item.getiid(),m_item.getipackage());

and the snippet (I changed the notification bar just to display progress text):

protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_app_display);
//get extras
Bundle extras = getIntent().getExtras();

    if (extras == null) {
        return;
    }
    itemId = extras.getString("id");
    itemStatus = extras.getString("IorU");
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
    progressBar.setVisibility(0);

   showUI();

}
private void showUI() {

if(m_item != null) { 

    TextView actvTitle = (TextView) findViewById(R.id.title_text);
    actvTitle.setText(m_item.geticategory());

    appinstall = (Button) findViewById(R.id.app_install_btn);
    appudinstall = (Button) findViewById(R.id.app_udinstall_btn);

    permlist = (LinearLayout) findViewById(R.id.app_perm); //
    info = (LinearLayout) findViewById(R.id.info);
    mList = (HeightListView) findViewById(R.id.app_perm_list);
    mList.setTextFilterEnabled(true);


    instTxt = (TextView) findViewById(R.id.app_install);

    TextView titleTxt = (TextView) findViewById(R.id.app_titlebig);
    TextView companyTxt = (TextView) findViewById(R.id.app_descbig);

    TextView descTxt = (TextView) findViewById(R.id.long_desc);
    TextView verTxt = (TextView) findViewById(R.id.version);

    //fill info
    titleTxt.setText(m_item.getititle());
    companyTxt.setText(m_item.geticompany());
    descTxt.setText(m_item.getidescription());
    verTxt.setText(" Version:" + m_item.getiversion());


}
   }

@Override
protected void onResume(){
super.onResume();
}

@Override
public Object onRetainNonConfigurationInstance() {
Toast.makeText (getApplicationContext(), "onRetainNonConfigurationInstance", Toast.LENGTH_SHORT).show();
return null;
}
@Override
protected void onDestroy() {
super.onDestroy();
/*
if(df != null)
{
  if(!df.isCancelled())
    df.cancel(true);
}
CN=true;
*/

}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStart() {
super.onStart(); 
}



private class AsyncDownloadTask extends AsyncTask<String, Integer, Void>
   {
  private int successCount;
  private int numTotalFiles;
  private File outputFile;
  private String pack;
  private int downloadErr = 0;


  @Override
  protected void onPreExecute()
  {
super.onPreExecute();

successCount = 0;
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
CN=false;
  }


  @Override
  protected Void doInBackground(String... params)
  {
    String remoteFilepath;
String id = params[0];
pack = params[1];
  remoteFilepath = "http://www.myserver/download/1.zip";

  String PATH = Environment.getExternalStorageDirectory()+ "/download/";
  File file = new File(PATH);
  file.mkdirs();
  try
  {
    if(isCancelled())
      return null;

    URL url = new URL(remoteFilepath);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setConnectTimeout(getConnectTimeout());
    c.setReadTimeout(getReadTimeout());
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    int filesize = c.getContentLength();
    if(filesize > 0)
    {

      outputFile = new File(file, "1.zip");
      FileOutputStream fos = new FileOutputStream(outputFile);

      InputStream is = c.getInputStream();
      int bytesRead, totalBytesRead = 0;
      byte[] bytes = new byte[BYTES_BUFFER_SIZE];
      String progress, kbytes;
      while(!isCancelled() && (bytesRead = is.read(bytes)) != -1)
      {
        totalBytesRead += bytesRead;
        fos.write(bytes, 0, bytesRead);
        if(!isCancelled() ) //&& loopCount++ % 20 == 0)
        {
          RemoteViews progressView = getProgressView(successCount + 1, numTotalFiles, totalBytesRead, filesize);
          if(progressView == null)
          {
            progress = "Download "+pack;
            kbytes = String.format("%s / %s", getStringByteSize(totalBytesRead), getStringByteSize(filesize));

            if(!isCancelled() && !CN){
              showNotification("Downloading File(s)", progress , kbytes);
              publishProgress(totalBytesRead,filesize);
            } else { return null; }
          }
          else
          {

            if(!isCancelled() && !CN){
              showNotification(progressView, "Downloading File(s)");
            } else { return null; }
          }

        }
      }
      fos.close();
      is.close();
      if(isCancelled())
        return null;

      successCount ++;
    }
    else
    {
    }
  }
  catch(Exception e)
  {
      e.printStackTrace();
    showNotification("Download Failed", "Download Progress", "Failed: " + (new File(remoteFilepath)).getName());
    //updateCancelInstall();
    publishProgress(100,100);
    notificationManager.cancel(42);
    downloadErr = 1;
    CN = true;
  }

return null;
  }

  @Override
  protected void onCancelled()
  {
super.onCancelled();
showNotification("Download Cancelled", "Download Progress", "Cancelled");
CN = true;
publishProgress(100,100);
notificationManager.cancel(42);
  }

  protected void onProgressUpdate(Integer... prog) {
  if(prog[0]<prog[1]){
      updateProgress(prog[0],prog[1],false);
  } else {
      updateProgress(100,100,true);
      notificationManager.cancel(42);
  }
  }


  @Override
 protected void onPostExecute(Void result)
 {
super.onPostExecute(result);
if(!CN){
    if(downloadErr==0) {
        showNotification("Installing", "Installing "+pack, "Completed");
        updateDLcount udl = new updateDLcount();
        udl.execute("hello"); 
        //updateCancelInstall();
        notificationManager.cancel(42);
    } else {

        showNotification("Download Error", "Failed to download "+pack, "Error");
        //updateCancelInstall();
        notificationManager.cancel(42);
       }
   }
 }
}

   protected RemoteViews getProgressView(int currentNumFile, int totalNumFiles, int  currentReceivedBytes, int totalNumBytes)
  {
    return null;
  }



   protected Class<?> getIntentForLatestInfo()
   {
 return DisplayApp.class;
   }

protected void showNotification(String ticker, String title, String content)
{

  Notification notification = new Notification(R.drawable.download_icon, ticker, System.currentTimeMillis());
  Intent i=new Intent(this, DisplayApp.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("id", itemId);
i.putExtra("IorU", "itemStatus");
i.putExtra("progrss", content);
  PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
  notification.setLatestEventInfo(getApplicationContext(), title, content, contentIntent);
  notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;

  notificationManager.notify(42, notification);
if(content.equalsIgnoreCase("Cancelled")||content.equalsIgnoreCase("Completed")||CN)notificationManager.cancel(42);
}
protected void updateProgress(int downsize, int totalsize, boolean cancel){

//Log.i("YYYY","cancel="+cancel);

if(!cancel || (downsize<totalsize)){
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
    TextView pb_t = (TextView) findViewById(R.id.progressbar_text);
    progressBar.setVisibility(0);
    pb_t.setVisibility(0);
    progressBar.setProgress((int)downsize*100/totalsize);
    pb_t.setText(String.format("%s / %s", getStringByteSize(downsize), getStringByteSize(totalsize)));
} else {
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
    TextView pb_t = (TextView) findViewById(R.id.progressbar_text);
    progressBar.setProgress(100);
    progressBar.setVisibility(4);
    pb_t.setVisibility(4);
    updateCancelInstall();
} 
}


protected void showNotification(RemoteViews remoteView, String ticker)
{
  Notification notification = new Notification(R.drawable.download_icon, ticker, System.currentTimeMillis());
  notification.contentView = remoteView;
  Intent i=new Intent(this, DisplayApp.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
  notification.contentIntent = PendingIntent.getActivity(this, 0, i, 0);
  //Log.d("YYYY","2:"+notification.contentIntent.toString());
  notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;

  notificationManager.notify(42, notification);
}

Appreciate if you can help me by code, url or any documentations that mimics the market way of doing this.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半暖夏伤 2024-12-22 02:04:50

我在 Activity 的 launchMode 中使用了 singleInstance,该 Activity 出现在前面,进度条随着下载的进行而进行。

我发现只有当我返回然后回家然后单击通知栏时才会感到困惑,这一点很明显,因为单击返回会破坏我的活动并且我会丢失历史记录,所以我的解决方法是禁用我的活动中的后退键并让应用程序用户浏览我的 UI 菜单和按钮。

我知道应该有办法存储我的活动实例并在以后检索它,无论历史记录/堆栈发生什么,但到目前为止,上面的内容对我来说已经足够了!

谢谢,

I have used singleInstance in the launchMode of my activity, the activity comes to front with the progress bar progressing along with the download.

I figured out that it get confused only if I moved back and then home then click notification bar, this obvious since clicking back will destroy my activity and I loose history so my work around was to disable the back key in my activity and let the application user navigate through my UI menu and button.

I know there should be away to store my activity instance and retrieve it later no matter what happened to the history/stack but so far the above is enough for me!!

Thanks,

孤芳又自赏 2024-12-22 02:04:50

在您的 AndroidManifest.xml 文件中,尝试在您希望返回的 Activity 下添加 android:launchMode="singleTop" 行。例如:

这将阻止创建 Activity 的新实例,并将 Intent 路由到 Activity 的任何当前实例。有关详细信息,请参阅此处

In your AndroidManifest.xml file try adding under the activity you wish to return to the line android:launchMode="singleTop". For example:

<activity android:name=".MainLayout"
android:label="@string/app_name"
android:launchMode="singleTop">

This will prevent a new instance of your activity being created and will route the intent to any current instances of your activity. For more info see here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文