Android两个网络运营同时进行

时间:2014-01-05 13:11:09

标签: java android

我在同时遇到两个网络操作的问题。

这是我正在处理的代码:

 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 


}

基本上,我的应用程序将音频文件上传到服务器,并将文件的元数据插入数据库服务器。但是我收到了一个错误。请在下面看到我的logcat错误:

 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)

注意:

保存音频文件的元数据是有效的,但音频文件的上传似乎无法正常工作。

有什么想法吗?我遇到了这个问题。我真的需要你的帮助。感谢。

1 个答案:

答案 0 :(得分:1)

从我看到的内容,您对UI进行了2次更改, 您可以关闭对话框或关闭活动。

我认为您正在关闭活动,然后尝试使用对话框执行某些操作。 因此,你有一个泄露的窗户,因为没有活动。