2012-07-06 162 views
0

我已經將我的onCreate()移動到asynctask,除通知欄外,現在所有的工作都很好,我不知道應該在哪裏放置它。下面是功能代碼:通知欄在asynctask

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


    tvDescription = (TextView)findViewById(R.id.tvDescription); 

    tvTitle = (TextView)findViewById(R.id.tvTitle); 
    tvDeveloper = (TextView)findViewById(R.id.tvDeveloper); 

    rbRating = (RatingBar)findViewById(R.id.rbRating); 

    ivLogo = (ImageView)findViewById(R.id.ivLogo); 
    ivPhoto1 = (ImageView)findViewById(R.id.ivPhoto1); 
    ivPhoto2 = (ImageView)findViewById(R.id.ivPhoto2); 
    ivPhoto3 = (ImageView)findViewById(R.id.ivPhoto3); 

    new loadPage().execute(null, null, null);    
} 

public void onClickDownload(View view){ 
    String url = "http://www.mydomain.com/apk/" + apkURL; 
    url = url.replaceAll(" ","%20"); 
    String sourceUrl = url; 
    new DownloadFileAsync().execute(sourceUrl); 
} 

private Bitmap LoadImage(String URL, BitmapFactory.Options options){  
    Bitmap bitmap = null; 
    InputStream in = null; 
     try { 
      in = OpenHttpConnection(URL); 
      bitmap = BitmapFactory.decodeStream(in, null, options); 
      in.close(); 
     } catch (IOException e1) { 
     } 
     return bitmap; 
     } 

private InputStream OpenHttpConnection(String strURL) throws IOException{ 
    InputStream inputStream = null; 
    URL url = new URL(strURL); 
    URLConnection conn = url.openConnection(); 

    try{ 
     HttpURLConnection httpConn = (HttpURLConnection)conn; 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
      inputStream = httpConn.getInputStream(); 
      } 
     } 
    catch (Exception ex){   
    } 
    return inputStream; 
} 

/////start download 
public class DownloadFileAsync extends AsyncTask<String, Integer, Void> { 
    private boolean run_do_in_background = true; 

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

    @Override 
    protected Void doInBackground(String... aurl) { 
     int count; 
     try { 
      URL url = new URL(aurl[0]); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 

      int lengthOfFile = conexion.getContentLength(); 
      Log.d("ANDRO_ASYNC", "Lenght of file: " + lengthOfFile); 

      File folder = new File(Environment.getExternalStorageDirectory() + "/MaxApps"); 
      boolean success = false; 
      if (!folder.exists()) { 
       success = folder.mkdirs(); 
      } 
      if (!success) { 
      } else { 
      } 

      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/MaxApps/" + apkURL); 

      byte data[] = new byte[100*1024]; 

      long total = 0; 

      //use try catch here to notice a disconnect    
      while ((count = input.read(data)) != -1) { 
      total += count;    
      int progressPercent = (int) ((total*100)/lengthOfFile); 
      if(progressPercent % 5 == 0){ //publish progress on completion of every 10% 
       publishProgress(progressPercent); 
       } 
      output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
      } catch (Exception e) { 

       notificationManager.cancel(Integer.parseInt(ID.toString())); 

       Notification MyN = new Notification(); MyN.icon = R.drawable.logo1; 
       MyN.tickerText = "Download Failed"; 
       MyN.number = 1; 
       MyN.setLatestEventInfo (getApplicationContext(), apkURL + " Download Failed.", "Please try again", MyPI); 
       MyN.flags |= Notification.FLAG_AUTO_CANCEL; 
       MyNM.notify(1, MyN);  
       run_do_in_background = false; 
      } 

     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) {   
     notification.contentView.setProgressBar(R.id.pbStatus, 100, progress[0], false); 
     notificationManager.notify(Integer.parseInt(ID.toString()), notification); 
     } 

    @Override 
    protected void onPostExecute(Void unused) { 
     if(run_do_in_background) { 
     notificationManager.cancel(Integer.parseInt(ID.toString())); 

     Notification MyN = new Notification(); MyN.icon = R.drawable.logo1; 
     MyN.tickerText = "Download Complete"; 
     MyN.number = 1; 
     MyN.setLatestEventInfo (getApplicationContext(), "Download Complete, Click to install.", apkURL, MyPI); 
     MyN.flags |= Notification.FLAG_AUTO_CANCEL; 
     MyNM.notify(Integer.parseInt(ID.toString()) , MyN); 
     } 
    } 
} 


public class loadPage extends AsyncTask<String, Integer, Void> { 
    private ProgressDialog pdia; 

    @Override 
    protected void onPreExecute(){ 
     super.onPreExecute(); 
     pdia = new ProgressDialog(AppDetails.this); 
     pdia.setMessage("Loading..."); 
     pdia.show(); 
     } 

    @Override 
    protected Void doInBackground(String... aurl) { 
     SoapObject Request = new SoapObject (NAMESPACE, METHOD_NAME); 

     Request.addProperty("title", getIntent().getExtras().getString("xdaTitle")); 

     SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 

     soapEnvelope.dotNet = true; 
     soapEnvelope.setOutputSoapObject(Request); 

     AndroidHttpTransport aht = new AndroidHttpTransport(URL); 

     try 
     { 
      aht.call(SOAP_ACTION, soapEnvelope); 
      SoapObject resultString = (SoapObject) soapEnvelope.getResponse(); 

      for(int i =0; i<resultString.getPropertyCount(); i++) 
      { 
       SoapObject array = (SoapObject) resultString .getProperty(i); 

       title = array.getProperty(1).toString(); 
       description = array.getProperty(2).toString(); 
       developer = array.getProperty(3).toString(); 
       rating = array.getProperty(4).toString(); 
       apkURL = array.getProperty(10).toString();     

       String logo_URL = array.getProperty(5).toString(); //get logo url 

       BitmapFactory.Options bmOptions; 
       bmOptions = new BitmapFactory.Options(); 
       bmOptions.inSampleSize = 1; 

       bmLogo = LoadImage(logo_URL, bmOptions); 

       String photo1_URL = array.getProperty(6).toString(); 
       bmPhoto1 = LoadImage(photo1_URL, bmOptions); 

       String photo2_URL = array.getProperty(7).toString(); 
       bmPhoto2 = LoadImage(photo2_URL, bmOptions); 

       String photo3_URL = array.getProperty(8).toString(); 
       bmPhoto3 = LoadImage(photo3_URL, bmOptions); 
      } 
     } 
     catch(Exception e) 
     { 

     }   
     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 

    } 

    @Override 
    protected void onPostExecute(Void unused) { 
     tvTitle.setText(title); 
     tvDeveloper.setText(developer);   

     ivLogo.setImageBitmap(bmLogo); 
     ivPhoto1.setImageBitmap(bmPhoto1); 
     ivPhoto2.setImageBitmap(bmPhoto2); 
     ivPhoto3.setImageBitmap(bmPhoto3); 

     pdia.dismiss(); 
    } 
} 

這是我想用,代碼將打開下載的文件,在此之前,它的運作之前一切搬到的AsyncTask代碼。

MyI = new Intent(Intent.ACTION_VIEW); 
MyI.setAction(android.content.Intent.ACTION_VIEW); 
MyI.setDataAndType(Uri.parse("file:///sdcard/MaxApps/" + apkURL.toString()), "application/vnd.android.package-archive"); 

MyPI = PendingIntent.getActivity(getApplicationContext(), 0, MyI, 0); 
MyNM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 

Intent intent = new Intent(getApplicationContext(), AppDetails.class); 
intent.putExtra("xdaTitle", title); 
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); 

notification = new Notification(R.drawable.logo, "Downloading...", System.currentTimeMillis()); 
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT; 
notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.downloadapk); 
notification.contentIntent = pendingIntent; 
notification.contentView.setImageViewResource(R.id.imgIcon, R.drawable.save); 
notification.contentView.setTextViewText(R.id.tvText, "Downloading " + apkURL); 
notification.contentView.setViewVisibility(R.id.pbStatus, View.VISIBLE); 
notification.contentView.setProgressBar(R.id.pbStatus, 100, progress, false);   
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE); 

錯誤: enter image description here

+0

檢查http://stackoverflow.com/questions/11135389/android-show-notification-bar-on-downloading-application/11135489#11135489和http這一行://計算器。 COM /問題/ 11339847 /如何對附加progressdialog/11339895#11339895 – Nermeen 2012-07-06 07:30:49

回答

0

我找到了解決辦法,這是因爲我忘了獲取ID的價值。所以當應用程序想要創建通知時,他們不能創建它,因爲沒有ID。 只需添加doInBackground

title = array.getProperty(1).toString();