Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用AsyncTask更新状态栏中的我的进度栏和文本_Android - Fatal编程技术网

Android 使用AsyncTask更新状态栏中的我的进度栏和文本

Android 使用AsyncTask更新状态栏中的我的进度栏和文本,android,Android,我有一个asynctask,它可以下载mp3,在状态栏中有一个自定义的扩展通知,其中有一个进度栏和一个文本视图。问题是我无法让他们更新。这是我的尝试,我做错了什么 public class DownloadFile extends AsyncTask<Void, Integer, String> { /*public WebRequest(Context context, String Progress

我有一个asynctask,它可以下载mp3,在状态栏中有一个自定义的扩展通知,其中有一个进度栏和一个文本视图。问题是我无法让他们更新。这是我的尝试,我做错了什么

 public class DownloadFile extends AsyncTask<Void, Integer, String> {                       
    /*public WebRequest(Context context, 
            String ProgressTitle, String ProgressMessage) {
        this._context = context;

        this._title = ProgressTitle;
        this._message = ProgressMessage;
    }*/
    ProgressBar progressBar;
    private int progress = 0;
    NotificationManager notificationManager;
    Notification notification2;
    private static final int PROGRESS = 0x1;
    private static final int MAX_PROGRESS = 100;
    int downloadedSize;
    int totalSize;



    @Override
    protected void onPreExecute() {
        /*SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
        Intent in = new Intent(mainmenu.this, DownloadService.class);
        in.putExtra("url", SDCardRoot);
        in.putExtra("songname", filename3);
        startService(in);*/

        // get the layout
        //setContentView(R.layout.download_progress);

        // configure the intent
        Intent intent = new Intent();
        final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        // configure the notification
        notification2 = new Notification(R.drawable.download, "DOWNLOADING: " + filename3, System
                .currentTimeMillis());
        notification2.flags = notification2.flags | Notification.FLAG_ONGOING_EVENT;
        notification2.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_progress);
        notification2.contentIntent = pendingIntent;
        notification2.contentView.setTextViewText(R.id.percentage,"hi" );
        notification2.contentView.setTextViewText(R.id.status_text, "DOWNLOADING: " + filename3);
        notification2.contentView.setProgressBar(R.id.status_progress, 100, progress, false);

        getApplicationContext();
        notificationManager = (NotificationManager) getApplicationContext().getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.notify(2, notification2);


    }

    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {

            //set the download URL, a url that points to a file on the internet
            //this is the file to be downloaded
            URL url = songURL2;


            //create the new connection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            //and connect!
            urlConnection.connect();

            //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot,filename3);

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file
            Integer totalSize = urlConnection.getContentLength();
            //variable to store total downloaded bytes
            Integer downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    //add the data in the buffer to the file in the file output stream (the     file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    //add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    //this is where you would do something to report the prgress, like this maybe
                    //updateProgress(downloadedSize, totalSize);
                    publishProgress(downloadedSize/totalSize);


            }
            //close the output stream when done
            fileOutput.close();

           return "Success";



    //catch some possible errors...
    } catch (MalformedURLException e) {             
            e.printStackTrace();
        return "Failed";
    } catch (IOException e) {               
            e.printStackTrace();
               return "Failed";
    }
}               

    protected void onProgressUpdate(Integer... progress) {

        notification2.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false);
        String stringy = progress + "%";
        TextView textytext = (TextView) findViewById(R.id.percentage);
        textytext.setText(stringy);
        notificationManager.notify(2, notification2);           
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub                  
        notificationManager.cancel(2);          
    }
}       
公共类下载文件扩展异步任务{
/*公共WebRequest(上下文,
String ProgressTitle、String ProgressMessage){
这._context=context;
本._title=ProgressTitle;
此._message=ProgressMessage;
}*/
ProgressBar ProgressBar;
私有int进程=0;
通知经理通知经理;
通知2;
私有静态最终整数进度=0x1;
私有静态最终整数最大进度=100;
int下载大小;
整数总大小;
@凌驾
受保护的void onPreExecute(){
/*SDCardRoot=Environment.getExternalStorageDirectory()+“/download/”;
Intent in=新Intent(main menu.this,DownloadService.class);
in.putExtra(“url”,SDCardRoot);
in.putExtra(“songname”,filename3);
startService(in)*/
//获取布局
//setContentView(R.layout.download_progress);
//配置意图
意图=新意图();
final pendingent pendingent=pendingent.getActivity(getApplicationContext(),0,intent,0);
//配置通知
notification2=新通知(R.drawable.download,“下载:”+filename3,系统
.currentTimeMillis());
notification2.flags=notification2.flags | Notification.FLAG_持续事件;
notification2.contentView=新的远程视图(getApplicationContext().getPackageName(),R.layout.download_progress);
notification2.contentIntent=待定内容;
notification2.contentView.setTextViewText(R.id.percentage,“hi”);
通知2.contentView.setTextViewText(R.id.status_text,“下载:”+filename3);
notification2.contentView.setProgressBar(R.id.status\u progress,100,progress,false);
getApplicationContext();
notificationManager=(notificationManager)getApplicationContext().getSystemService(
通知服务);
通知经理。通知(2,通知2);
}
@凌驾
受保护字符串doInBackground(无效…参数){
//TODO自动生成的方法存根
试一试{
//设置下载URL,该URL指向internet上的文件
//这是要下载的文件
URL=songURL2;
//创建新连接
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
//在连接上设置一些东西
urlConnection.setRequestMethod(“GET”);
urlConnection.setDoOutput(true);
//连接!
urlConnection.connect();
//设置要保存文件的路径
//在本例中,将其保存在
//sd卡。
SDCardRoot=Environment.getExternalStorageDirectory()+“/download/”;
//创建一个新文件,指定路径和文件名
//我们希望将文件另存为。
File File=新文件(SDCardRoot,filename3);
//这将用于将下载的数据写入我们创建的文件中
FileOutputStream fileOutput=新的FileOutputStream(文件);
//这将用于从互联网读取数据
InputStream InputStream=urlConnection.getInputStream();
//这是文件的总大小
整数totalSize=urlConnection.getContentLength();
//用于存储总下载字节数的变量
整数downloadedSize=0;
//创建一个缓冲区。。。
字节[]缓冲区=新字节[1024];
int bufferLength=0;//用于存储缓冲区的临时大小
//现在,读取输入缓冲区并将内容写入文件
而((bufferLength=inputStream.read(buffer))>0){
//将缓冲区中的数据添加到文件输出流中的文件(sd卡上的文件)
fileOutput.write(buffer,0,bufferLength);
//把大小加起来,这样我们就知道下载了多少
downloadedSize+=缓冲区长度;
//在这里,你可以做一些事情来报告事件,也许像这样
//updateProgress(downloadedSize,totalSize);
publishProgress(下载大小/总大小);
}
//完成后关闭输出流
fileOutput.close();
返回“成功”;
//捕捉一些可能的错误。。。
}捕获(格式错误){
e、 printStackTrace();
返回“失败”;
}捕获(IOE){
e、 printStackTrace();
返回“失败”;
}
}               
受保护的void onProgressUpdate(整数…进度){
notification2.contentView.setProgressBar(R.id.status\u progress,100,progress[0],false);
字符串stringy=进度+“%”;
TextView textytext=(TextView)findViewById(R.id.percentage);
textytext.setText(stringy);
通知经理。通知(2,通知2);
}
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
通知经理。取消(2);
}
}       

}

您总是发布0,因为您使用
Integer
作为进度和下载大小
将其更改为
Double
并尝试
publishProgress((Double)(downloadedSize/totalSize))

由于使用了
Integer
fo,所以始终发布0