android 通知里面的进度如何走动

 我来答
厦门侯
高粉答主

2016-01-21 · 信息管理员
厦门侯
采纳数:30618 获赞数:90295

向TA提问 私信TA
展开全部

实现在android实现带进度条的上传效果效果如图:

用到以下两个类就可实现带进度条的文件上传:


1、CustomMultiPartEntity extends MultipartEntity, 


2、HttpMultipartPost extends AsyncTask


代码如下:


 import java.io.FilterOutputStream;


import java.io.IOException;


import java.io.OutputStream;


import java.nio.charset.Charset;


import org.apache.http.entity.mime.HttpMultipartMode;


import org.apache.http.entity.mime.MultipartEntity;


 


public class CustomMultipartEntity extends MultipartEntity {


    private final ProgressListener listener;


    public CustomMultipartEntity(final ProgressListener listener) {


        super();


        this.listener = listener;


    }


    public CustomMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener)     {


        super(mode);


        this.listener = listener;


    }


    public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,


            final Charset charset, final ProgressListener listener) {


        super(mode, boundary, charset);


        this.listener = listener;


    }


    @Override


    public void writeTo(final OutputStream outstream) throws IOException {


        super.writeTo(new CountingOutputStream(outstream, this.listener));


    }


    public static interface ProgressListener {


        void transferred(long num);


    }


 


    public static class CountingOutputStream extends FilterOutputStream {


        private final ProgressListener listener;


        private long transferred;


        public CountingOutputStream(final OutputStream out, final ProgressListener listener) {


            super(out);


            this.listener = listener;


            this.transferred = 0;


        }


        public void write(byte[] b, int off, int len) throws IOException {


            out.write(b, off, len);


            this.transferred += len;


            this.listener.transferred(this.transferred);


        }


        public void write(int b) throws IOException {


            out.write(b);


            this.transferred++;


            this.listener.transferred(this.transferred);


        }


    }


}


该类计算写入的字节数,我们需要在实现ProgressListener中的trasnfered()方法,更行进度条


 


public  class HttpMultipartPost extends AsyncTask<HttpResponse, Integer, TypeUploadImage> {


 


    ProgressDialogpd;


 


    longtotalSize;


 


    @Override


    protectedvoidonPreExecute(){


        pd= newProgressDialog(this);


        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


        pd.setMessage("Uploading Picture...");


        pd.setCancelable(false);


        pd.show();


    }


 


    @Override


    protectedTypeUploadImagedoInBackground(HttpResponse... arg0) {


        HttpClienthttpClient = newDefaultHttpClient();


        HttpContexthttpContext = newBasicHttpContext();


        HttpPosthttpPost = newHttpPost("http://herpderp.com/UploadImage.php");


 


        try{


            CustomMultipartEntitymultipartContent = newCustomMultipartEntity(


                    newProgressListener() {


 


                        @Override


                        public void transferred(longnum){


                            publishProgress((int) ((num / (float) totalSize) * 100));


                        }


                    });


 


            // We use FileBody to transfer an image


            multipartContent.addPart("uploaded_file", newFileBody(


                    newFile(m_userSelectedImagePath)));


            totalSize= multipartContent.getContentLength();


 


            // Send it


            httpPost.setEntity(multipartContent);


            HttpResponseresponse = httpClient.execute(httpPost, httpContext);


            String serverResponse = EntityUtils.toString(response.getEntity());


 


            ResponseFactoryrp = newResponseFactory(serverResponse);


            return(TypeImage) rp.getData();


        }


 


        catch(Exception e) {


            System.out.println(e);


        }


        returnnull;


    }


 


    @Override


    protectedvoidonProgressUpdate(Integer... progress){


        pd.setProgress((int) (progress[0]));


    }


 


    @Override


    protectedvoidonPostExecute(TypeUploadImageui) {


        pd.dismiss();


    }


}

在 transferred()函数中调用publishProgress((int) ((num / (float) totalSize) * 100));


在onProgressUpdate()实现上传进度的更新操作

man0306
2014-11-13 · TA获得超过958个赞
知道小有建树答主
回答量:707
采纳率:33%
帮助的人:400万
展开全部
通知栏显示所用到的布局文件content_view.xml

<?xml version="1.0" encoding="utf-8"?>
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00000000"
android:orientation="vertical"
android:padding="5dp">

<ImageView
android:id="@+id/content_view_image"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@drawable/logo"

/>
<TextView
android:id="@+id/content_view_text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0%"
android:textColor="#000000"
android:layout_toRightOf="@id/content_view_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="15dp"
/>
<ProgressBar
android:id="@+id/content_view_progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:layout_below="@id/content_view_image"
android:layout_marginTop="4dp"
/>

< /RelativeLayout>
主运行类:
[java]
package yyy.testandroid4;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

public class TestAndroid4Activity extends Activity {

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 0:
notif.contentView.setTextViewText(R.id.content_view_text1, len+"%");
notif.contentView.setProgressBar(R.id.content_view_progress, 100, len, false);
manager.notify(0, notif);

break;
case 1:
Toast.makeText(TestAndroid4Activity.this, "下载完成", 0).show();
break;
default:
break;
}
}

};

private Button update,cancel;
private int localVersion,serverVersion;
private int len;
private NotificationManager manager;
private Notification notif;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

update = (Button) findViewById(R.id.update);

update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//点击通知栏后打开的activity
Intent intent = new Intent(TestAndroid4Activity.this,OtherActivity.class);

PendingIntent pIntent = PendingIntent.getActivity(TestAndroid4Activity.this, 0, intent, 0);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notif = new Notification();
notif.icon = R.drawable.logo;
notif.tickerText = "新通知";
//通知栏显示所用到的布局文件
notif.contentView = new RemoteViews(getPackageName(), R.layout.content_view);
notif.contentIntent = pIntent;
manager.notify(0, notif);
new DownLoadThread().start();
}
});

}
}

private class DownLoadThread extends Thread{
private Timer timer = new Timer();
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub

Message msg = new Message();
msg.what = 0;
msg.obj = len;
handler.sendMessage(msg);

if(len == 100){
timer.cancel();
handler.sendEmptyMessage(1);
}

}
}, 0, 1000);
len = 0;
try {
while(len < 100){
len++;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式