0

我已经将我的 onCreate() 移动到 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);

错误: 在此处输入图像描述

4

1 回答 1

0

我找到了解决方案,这是因为我忘记获取 ID 的值。所以当应用程序想要创建通知时,他们无法创建它,因为没有 ID。只需在 doInBackground 下添加这一行

 title = array.getProperty(1).toString();
于 2012-07-07T09:51:09.393 回答