简体   繁体   中英

Android two network operations at the same time

I'm having a problem with two network operations at the same time.

This is the code I'm working on:

 public void onClick(View v) {
    // TODO onClick

    switch(v.getId()){
    case R.id.btSelectSong:
        openGalleryAudio();
        break;
    case R.id.btUpload:

        if(etSongTitle.getText().toString().isEmpty()){
            Toast.makeText(getBaseContext(), 
                    "Select an audio file", Toast.LENGTH_SHORT).show();

        } else {
            dialog = ProgressDialog.show(AddSong.this, "", "Uploading file...", true);

                  new Thread(new Runnable() {
                        public void run() {
                             runOnUiThread(new Runnable() {
                                    public void run() {
                                        Log.d("Upload", "Uploading started.....");
                                    }
                                });                      

                             uploadFile(uploadFilePath);

                        }
                  }).start();

                  new Thread(new Runnable() {
                        public void run(){
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Log.d("Insert", "Inserting audio file metadata to server...");
                                }
                            });

                            insertToServer();

                        }
                  }).start();
        }
        break;
    }

}

private void insertToServer(){

    String strSongFileName = etSongTitle.getText().toString();
    String strSongTitleName = etSongTitleName.getText().toString();
    String strSongType = spSongType.getSelectedItem().toString();
    String strSongUrl = 
            "http://mlssabio.x10.mx/strings-of-beads/songs/" + 
                    strSongFileName.replaceAll("\\s+","-").replaceAll("\\'", "") + ".mp3";
    String strSongLanguage = spSongLanguage.getSelectedItem().toString();

    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(TAG_SONGTYPE, strSongType));
    params.add(new BasicNameValuePair(TAG_SONGTITLE, strSongTitleName));
    params.add(new BasicNameValuePair(TAG_SONGURL, strSongUrl));
    params.add(new BasicNameValuePair(TAG_SONGLANGUAGE, strSongLanguage));

    // getting JSON Object
    // Note that create product url accepts POST method
    JSONObject json = jsonParser.makeHttpRequest(url_insert_song,
            "POST", params);

    // check log cat fro response
    Log.d("Create Response", json.toString());

    // check for success tag
    try {
        int success = json.getInt(TAG_SUCCESS);

        if (success == 1) {
            // successfully created product
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);

            // closing this screen
            finish();
        } else {
            // failed to create product
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

public int uploadFile(String sourceFileUri) {

      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                               +uploadFilePath);

           runOnUiThread(new Runnable() {
               public void run() {
                   Log.d("Test", "Source File not exist :"
                           + uploadFilePath);
               }
           }); 

           return 0;

      } else { 
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);

               // Open a HTTP  connection to  the URL
               conn = (HttpURLConnection) url.openConnection(); 
               conn.setChunkedStreamingMode(maxBufferSize);
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("uploaded_file", fileName); 

               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
                     + fileName + "'" + lineEnd);

               dos.writeBytes(lineEnd);

               // create a buffer of  maximum size
               bytesAvailable = fileInputStream.available(); 

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

               // read file and write it into form...
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

               Log.i("uploadFile", "HTTP Response is : "
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                          + uploadFilePath;

                            Log.d("Test", msg);
                            Toast.makeText(AddSong.this, "File Upload Complete.", 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          } // end of try  

           catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      Log.d("Test", "MalformedURLException Exception : check script url.");
                      Toast.makeText(AddSong.this, "MalformedURLException", 
                                                          Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } //  end of MalformedURLException ex 

           catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      Log.d("Exception", "Got Exception : see logcat ");
                      Toast.makeText(AddSong.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "
                                               + e.getMessage(), e);  
          } // End of catch Exception e
          dialog.dismiss();       
          return serverResponseCode; 


       } // End else block 


}

Basically, my app uploads an audio file to the server and also inserts the file's metadata to the database server. But I'm getting an error. Please see my logcat errors below:

 01-05 07:31:56.112: E/WindowManager(32278): Activity  com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
 01-05 07:31:56.112: E/WindowManager(32278): android.view.WindowLeaked: Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.Dialog.show(Dialog.java:281)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.ProgressDialog.show(ProgressDialog.java:116)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.ProgressDialog.show(ProgressDialog.java:99)
 01-05 07:31:56.112: E/WindowManager(32278):    at com.thesis.string.of.beads.AddSong.onClick(AddSong.java:158)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.View.performClick(View.java:4240)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.View$PerformClick.run(View.java:17721)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.os.Handler.handleCallback(Handler.java:730)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.os.Handler.dispatchMessage(Handler.java:92)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.os.Looper.loop(Looper.java:137)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.ActivityThread.main(ActivityThread.java:5103)
 01-05 07:31:56.112: E/WindowManager(32278):    at java.lang.reflect.Method.invokeNative(Native Method)
 01-05 07:31:56.112: E/WindowManager(32278):    at java.lang.reflect.Method.invoke(Method.java:525)
 01-05 07:31:56.112: E/WindowManager(32278):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 01-05 07:31:56.112: E/WindowManager(32278):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 01-05 07:31:56.112: E/WindowManager(32278):    at dalvik.system.NativeStart.main(Native Method)
 01-05 07:39:22.201: I/uploadFile(32278): HTTP Response is : OK: 200
 01-05 07:39:22.221: D/Test(32278): File Upload Completed.
 01-05 07:39:22.221: D/Test(32278):  See uploaded file here : 
 01-05 07:39:22.221: D/Test(32278): /storage/sdcard/John Farnham - Please Don't Ask Me.mp3
 01-05 07:39:22.290: D/AndroidRuntime(32278): Shutting down VM
 01-05 07:39:22.290: W/dalvikvm(32278): threadid=1: thread exiting with uncaught exception (group=0x41465700)
 01-05 07:39:22.332: E/AndroidRuntime(32278): FATAL EXCEPTION: main
 01-05 07:39:22.332: E/AndroidRuntime(32278): java.lang.IllegalArgumentException: View not attached to window manager
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:406)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:308)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.app.Dialog.dismissDialog(Dialog.java:323)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.app.Dialog$1.run(Dialog.java:119)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.os.Handler.handleCallback(Handler.java:730)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.os.Handler.dispatchMessage(Handler.java:92)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.os.Looper.loop(Looper.java:137)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.app.ActivityThread.main(ActivityThread.java:5103)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at java.lang.reflect.Method.invokeNative(Native Method)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at java.lang.reflect.Method.invoke(Method.java:525)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at dalvik.system.NativeStart.main(Native Method)

 01-05 07:31:56.112: E/WindowManager(32278): Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
 01-05 07:31:56.112: E/WindowManager(32278): android.view.WindowLeaked: Activity  com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.Dialog.show(Dialog.java:281)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.ProgressDialog.show(ProgressDialog.java:116)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.ProgressDialog.show(ProgressDialog.java:99)
 01-05 07:31:56.112: E/WindowManager(32278):    at com.thesis.string.of.beads.AddSong.onClick(AddSong.java:158)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.View.performClick(View.java:4240)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.view.View$PerformClick.run(View.java:17721)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.os.Handler.handleCallback(Handler.java:730)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.os.Handler.dispatchMessage(Handler.java:92)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.os.Looper.loop(Looper.java:137)
 01-05 07:31:56.112: E/WindowManager(32278):    at android.app.ActivityThread.main(ActivityThread.java:5103)
 01-05 07:31:56.112: E/WindowManager(32278):    at java.lang.reflect.Method.invokeNative(Native Method)
 01-05 07:31:56.112: E/WindowManager(32278):    at java.lang.reflect.Method.invoke(Method.java:525)
 01-05 07:31:56.112: E/WindowManager(32278):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 01-05 07:31:56.112: E/WindowManager(32278):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 01-05 07:31:56.112: E/WindowManager(32278):    at dalvik.system.NativeStart.main(Native Method)
 01-05 07:39:22.201: I/uploadFile(32278): HTTP Response is : OK: 200
 01-05 07:39:22.221: D/Test(32278): File Upload Completed.
 01-05 07:39:22.221: D/Test(32278):  See uploaded file here : 
 01-05 07:39:22.221: D/Test(32278): /storage/sdcard/John Farnham - Please Don't Ask Me.mp3
 01-05 07:39:22.290: D/AndroidRuntime(32278): Shutting down VM
 01-05 07:39:22.290: W/dalvikvm(32278): threadid=1: thread exiting with uncaught exception (group=0x41465700)
 01-05 07:39:22.332: E/AndroidRuntime(32278): FATAL EXCEPTION: main
 01-05 07:39:22.332: E/AndroidRuntime(32278): java.lang.IllegalArgumentException: View not attached to window manager
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:406)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:308)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.app.Dialog.dismissDialog(Dialog.java:323)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.app.Dialog$1.run(Dialog.java:119)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.os.Handler.handleCallback(Handler.java:730)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.os.Handler.dispatchMessage(Handler.java:92)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.os.Looper.loop(Looper.java:137)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at android.app.ActivityThread.main(ActivityThread.java:5103)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at java.lang.reflect.Method.invokeNative(Native Method)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at java.lang.reflect.Method.invoke(Method.java:525)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 01-05 07:39:22.332: E/AndroidRuntime(32278):   at dalvik.system.NativeStart.main(Native Method)

Note:

the saving of audio file's metadata is working, but the uploading of audio file seems to be not working.

Any ideas? I'm stuck with this problem. I really need your help. Thanks.

From what i see, you make 2 changes to the UI, you either dismiss the dialog or closing the activity.

I think that you are closing the activity and then trying to do something with the dialog. therefor you have a leaked window cause there is no activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM