在AsyncTask的通知栏 [英] notification bar in asynctask

查看:127
本文介绍了在AsyncTask的通知栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经把我的的onCreate()来AsyncTask的,一切运作良好,现在除了通知栏,我不知道我应该在哪里把它。下面是运行code:

i have move my onCreate() to asynctask, all works well now except the notification bar, i have no idea where should i place it. below is the functioning code:

@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();
    }
}

这是code我想使用,code将打开下载的文件,在此之前,它的运作前的一切搬到AsyncTask的。

this is the code i wanted to use, the code will open the downloaded files, before this, it's functioning before everything moved to 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);

错误:

ERROR:

推荐答案

我发现了解决方案,这是因为我忘了获取ID的值。所以当应用程序想创造该通知,他们不能因为没有ID创建它。
只需添加doInBackground下此行

i found out the solution, this is because i forgot to get the value of the ID. so when the apps wanted to create the notification, they cant create it because there is no ID. just add this line under doInBackground

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

这篇关于在AsyncTask的通知栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆