为什么publishProgress方法在Service中不起作用?

时间:2014-10-13 19:05:03

标签: android user-interface service android-asynctask progress-bar

我是Android开发的菜鸟,我正在尝试在服务中执行AsyncTask。当我注释掉publishProgress方法时,Asynctask工作正常,但是当我尝试调用publishProgress时,我的应用程序在doInBackground方法中停止。它不会崩溃,它只是退出,当我用调试器运行应用程序时,会弹出一条eclipse错误消息,说明“Update Progress”遇到错误。这个相同的代码在Activity中可以正常工作但不在Service中。任何帮助解决这个问题都非常感谢。

我的代码:

我在哪里实例化进度条

@Override
public void onCreate() {
super.onCreate();

//https://gist.github.com/bjoernQ/6975256 <--Tutorial URL


layout_inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT);
params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
params.x = 0;
params.y = 0;
topLeftView = layout_inflater.inflate(R.layout.layout_service, null);
wm.addView(topLeftView, params); 

btn_retry = (Button) topLeftView.findViewById(R.id.btn_retry);
btn_cancel = (Button) topLeftView.findViewById(R.id.btn_cancel);
progress_bar = (VerticalProgressBar) topLeftView.findViewById(R.id.progressbar);
upload_image = (ImageView) topLeftView.findViewById(R.id.imageView1);

btn_retry.setOnTouchListener(this);
btn_retry.setOnClickListener(this);

btn_cancel.setOnTouchListener(this);
btn_cancel.setOnClickListener(this);

progress_bar.setOnTouchListener(this);
upload_image.setOnTouchListener(this);

topLeftView.setOnTouchListener(this); 

  }

  class saveMedia extends AsyncTask<Void, Integer, String> {

    // @Override
    protected void onPreExecute() {


        progress_bar.setProgress(0);
        progress_bar.setMax(100);
    }

    @Override
    protected String doInBackground(Void... params) {



             HttpURLConnection connection = null;
             DataOutputStream outputStream = null;
             DataInputStream inputStream = null;

             String urlServer = "";
             if(is_club){ //For Clubs
                 urlServer = "http://example.com/App/ppfunctions.php?action=upload&club_id=" + club_id + "&club_name=" + club_name + "&user_id=" + user_id + "&user_name=" + user_name + "&club_city=" + club_city + "&comment=" + comments + "&price=" + price + "&line=" + line + "&capacity=" + capacity ;
             }else{ //For Parties
                 urlServer = "http://example.com/App/ppfunctions.php?action=upload_party&club_id=" + party_id + "&club_name=" + party_name + "&user_id=" + user_id + "&user_name=" + user_name + "&comment=" + comments + "&price=" + price + "&line=" + line + "&capacity=" + capacity ;
             }
             String lineEnd = "\r\n";
             String twoHyphens = "--";
             String boundary =  "*****";

             int bytesRead, bytesAvailable, bufferSize;
             byte[] buffer;
             int maxBufferSize = 15*1024*1024; 

             try{                

                 URL url = new URL(urlServer);
                 connection = (HttpURLConnection) url.openConnection();

                 // Allow Inputs & Outputs
                 connection.setDoInput(true);
                 connection.setDoOutput(true);
                 connection.setUseCaches(false);

                 // Enable POST method
                 connection.setRequestMethod("POST");

                 connection.setRequestProperty("Connection", "Keep-Alive");
                 connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                 outputStream = new DataOutputStream( connection.getOutputStream() );
                 outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
                 Date date = new Date();
                 SharedPreferences preferences = getSharedPreferences("PPPref", MODE_WORLD_READABLE);
                 String filename = "";
                 if(is_photo){
                     filename = String.valueOf(System.currentTimeMillis()) + ".jpg";
                 }else{
                     filename = String.valueOf(System.currentTimeMillis()) + ".mp4";
                 }                       
                 outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename +"\"" + lineEnd);
                 outputStream.writeBytes(lineEnd);

                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 buffer = new byte[bufferSize];


                 int sentBytes=0;

                 // Read file
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                 while (bytesRead > 0){
                     outputStream.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                     sentBytes += bufferSize;
                     publishProgress((int)(sentBytes * 100 / bytesAvailable)); //<--Dies here.

                 }

                 outputStream.writeBytes(lineEnd);
                 outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                 // Responses from the server (code and message)
                 int serverResponseCode = connection.getResponseCode();
                 String serverResponseMessage = connection.getResponseMessage();

                 StringBuilder response = null;
                 DataInputStream dis = null;
                 String con  = null;
                 try {
                     dis = new DataInputStream(connection.getInputStream());
                     response = new StringBuilder();

                     String line2;
                     con = dis.readLine();
                     while ((line2 = dis.readLine()) != null) {
                         response.append(line2);

                     }
                 }catch(Exception e){

                 }

                 Log.e("s", con );

                 fileInputStream.close();
                 outputStream.flush();
                 outputStream.close();

                 //Kill Service
                 stopSelf();
                 //onDestroy();

             }catch (Exception ex){
                 ex.printStackTrace();
             } 

            return null;


    }

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

        super.onProgressUpdate(progress);
        // Update the ProgressBar
        progress_bar.setProgress(progress[0]);



    }

    @Override
    protected void onPostExecute(String result) {
        /*dialog.dismiss();

        Intent intent = new Intent (Share_Media_Activity.this, PhotoVideo_Activity.class);
        startActivity(intent); */
    }

}

}

1 个答案:

答案 0 :(得分:0)

之前我遇到过这个问题。在while循环中检查你的bytesAvailable = fileInputStream.available();正在回归正在回归零。如果是这样,它可能会导致算术异常。