Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.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 为什么publishProgress方法在服务中不起作用?_Android_User Interface_Service_Android Asynctask_Progress Bar - Fatal编程技术网

Android 为什么publishProgress方法在服务中不起作用?

Android 为什么publishProgress方法在服务中不起作用?,android,user-interface,service,android-asynctask,progress-bar,Android,User Interface,Service,Android Asynctask,Progress Bar,我是android开发的新手,我试图在服务中执行异步任务。当我注释掉publishProgress方法时,Asynctask工作正常,但当我尝试调用publishProgress时,我的应用程序会在doInBackground方法中停止。它没有崩溃,只是退出,当我使用调试器运行应用程序时,会弹出一条eclipse错误消息,说明更新进度遇到错误。同样的代码在活动中对我来说很好,但在服务中却不行。非常感谢您对解决此问题的任何帮助 我的代码: 在这里我实例化了进度条 @Override public

我是android开发的新手,我试图在服务中执行异步任务。当我注释掉publishProgress方法时,Asynctask工作正常,但当我尝试调用publishProgress时,我的应用程序会在doInBackground方法中停止。它没有崩溃,只是退出,当我使用调试器运行应用程序时,会弹出一条eclipse错误消息,说明更新进度遇到错误。同样的代码在活动中对我来说很好,但在服务中却不行。非常感谢您对解决此问题的任何帮助

我的代码:

在这里我实例化了进度条

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

}

}

我曾经遇到过这个问题。在while循环中检查bytesavable=fileInputStream.available;正在返回,正在返回零。如果是这样,它可能会导致算术异常。

那么此异步任务在您拥有的服务中?是的,我的异步正在服务中运行。此进度条来自何处?我通过服务的onCreate方法中的窗口管理器创建它。它在UI中显示为覆盖。@Commonware请检查我的编辑