Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – 如何使用意图服务与服务更新UI进行多个图像上传大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 android开发人员.当我使用intent服务在后台发送多个图像时,我有面子问题ANR.我在Resume()方法上有调用服务.我在逐步图像上传完成时有更新UI.我的所有代码在服务中.但是我不明白为什么我的UI挂起.我已经为update UI创建了ResultReceiver类.请告诉我我在做什么问题.

public class UploadImageservice extends Intentservice {


public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;

private static final String TAG = "UploadImageservice";
public static String SHOW_MSG = "showMsg";
public static String SET_IN_ADAPTER = "setData";
public static String UPLOAD_IMAGE = "uploadImage";
public static String RESULT = "result";

private String threadType,toUser,chatThreadId,gcmRegistrationId,openCloseChatWindowType,recipientName,threadTopicName,attachmentID,attachmentType,currentChunks,originalBase64Img,datetiR_826_11845@e,classType,loginUserId;

// Declare Web services variable
private multipartentity multipartentityBuilder;

Database database;

Bundle bundle;

ResultReceiver receiver;

public UploadImageservice() {
    super(UploadImageservice.class.getName());
}

@Override
protected void onHandleIntent(Intent intent) {


    //initialize database
    database = new Database(UploadImageservice.this,Database.DATABASE_NAME,null,Database.DATABASE_VERSION);

    Log.d(tag,"service Started!");

    receiver = intent.getParcelableExtra("receiver");

    try {



        bundle = new Bundle();

        /* update UI: upload service is Running */
        //receiver.send(STATUS_RUNNING,Bundle.EMPTY);

        try {
            new UploadThumbImageAsync().execute();

        } catch (Exception E) {
            e.printStackTrace();
            bundle.putString(Intent.EXTRA_TEXT,e.toString());
            receiver.send(STATUS_ERROR,bundlE);
        }

       /* new Thread(new Runnable(){
            public void run() {
                // TODO Auto-generated method stub
                while(true)
                {
                    try {
                          new UploadThumbImageAsync().execute();

                    } catch (Exception E) {
                        e.printStackTrace();
                        bundle.putString(Intent.EXTRA_TEXT,e.toString());
                        receiver.send(STATUS_ERROR,bundlE);
                    }

                }

            }
        }).start();*/

    } catch (Exception E) {
        e.printStackTrace();
    }

    Log.e(tag,"service Stopping!");
    //this.stopSelf();
}
 private class UploadThumbImageAsync extends AsyncTask<String,Void,String> {
    /*this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing*/
    String toUser,comTypEID,threadType,chatAttachmentType,chatmessage,thumbBase64AttachmentPath /*original_image*/,loginUserName,originalBase64Image,originalFilePath;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //showProgressDialog();
    }

    /*starts the loading of the data in BACkground in doInBACkground() method  */
    @Override
    protected String doInBACkground(String... params) {
        try {
            toUser = params[0];
            comTypEID = params[1];
            threadType = params[2];
            chatThreadId = params[3];
            threadTopicName = params[4];
            chatAttachmentType = params[5];
            chatmessage = params[6];
            thumbBase64AttachmentPath = params[7];
            loginUserName = params[8];
            recipientName = params[9];
            originalBase64Image = params[10];
            originalFilePath = params[11];
            String url;
            if (!TextUtils.isEmpty(threadTypE) && threadType.equals(RecentChatList.SIMPLE_TYPE)) {
                url = WS.URl.concat(Ws.SAVE_CHAT);
            } else {
                url = WS.URl.concat(Ws.GROUP_SAVE_CHAT);
            }
            Log.e(tag,"url_" + chatmessage + " = " + url);
            String response = httpClientexecuteMethod.executeMultipartPostMethod(url,multipartentityBuilder);
            //Log.e(tag,"save_chat_history_response_" + threadType + "_" + chatmessage + " =" + responsE);
            return response;
        } catch (Exception E) {
            e.printStackTrace();
            return null;
        }

    }

    /*This method is called after the BACkground computation finishes.
        The result of BACkground process in passed in this method as parameters
         and Now you can dismiss progress dialog
        and get the result and display on onPostExecute() method
        */
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            // Log.e(tag,"chatAttachmentType = " + chatAttachmentTypE);
            updateCounter();
            if (result != null) {



                    JSONObject jo = new JSONObject(result);
                    String success = null;
                    final int storeLimit = SharedPreference.getLimit(UploadImageservice.this);

                    if (jo.has(Ws.succesS)) {
                        success = jo.getString(Ws.succesS);

                        if (!TextUtils.isEmpty(success) && success.equals("0")) {
                            return;
                        }

                        if (!TextUtils.isEmpty(success) && success.equals("100")) {

                            callWsSaveChat(chatAttachmentType,thumbBase64AttachmentPath,originalFilePath);
                            updateRecentChatandThreadList();
                            return;
                        }

                        if (!TextUtils.isEmpty(success) && success.equals("99")) {

                            updateRecentChatandThreadList();
                            return;
                        }


                    }


                    try {
                        ArrayList<Chat> saveChatArrayList = null;
                        if (!TextUtils.isEmpty(success) && success.equals("1")) {

                            saveChatArrayList = new Chat().getChatHistory(UploadImageservice.this,result,TAG,"");
                            // Log.e(tag,"onPostExecute_saveChatArrayList.size = " + saveChatArrayList);

                            ArrayList<Chat> chatHistoryWithoutmsgId = database.getWithoutmsgIdChatHistory(chatThreadId,"#");
                            //Log.e(tag,"onPostExecute_chatHistoryWithoutmsgId.size = " + chatHistoryWithoutmsgId.size());

                            if (saveChatArrayList != null && !saveChatArrayList.isEmpty() && saveChatArrayList.size() > 0) {

                                for (int i = 0; i < saveChatArrayList.size(); i++) {
                                    final Chat apiChat = saveChatArrayList.get(i);


                                    String apiMsg = apiChat.getmessage();
                                    String apiThumb = null;
                                    if (!TextUtils.isEmpty(apiChat.getAttachment_thumb())) {
                                        apiThumb = apiChat.getAttachment_thumb().concat("$");

                                    }

                                    if (chatHistoryWithoutmsgId != null && !chatHistoryWithoutmsgId.isEmpty() && chatHistoryWithoutmsgId.size() > 0) {
                                        for (int j = 0; j < chatHistoryWithoutmsgId.size(); j++) {

                                            Chat dbChat = chatHistoryWithoutmsgId.get(j);

                                            final String db_message = dbChat.getmessage();


                                            final String db_thumb = dbChat.getAttachment_thumb();

                                                    if (apiThumb.equals(db_thumb)) {
                                                        database.updateChatList(apiChat,"#",db_message,db_thumb,loginUserId,threadTypE);


                                                     bundle.putString(RESULT,UPLOAD_IMAGE);
                                                      receiver.send(STATUS_FINISHED,bundlE);

                                                        if (!TextUtils.isEmpty(chatAttachmentTypE) && chatAttachmentType.equals(getresources().getString(R.String.ImagE))) {
                                                            originalBase64Image = getBase64Image(originalFilePath);
                                                        }

                                                        int subLength = 1024 * 256;
                                                        //Log.e(tag,"upload_subLength = " + subLength);
                                                        int index = 0;
                                                        int @R_223_10586@lChunks = 0;
                                                        if (!TextUtils.isEmpty(originalBase64ImagE)) {
                                                            for (int k = 0; index < originalBase64Image.length(); k++) {
                                                                index = index + subLength;
                                                                @R_223_10586@lChunks++;
                                                            }


                                            database.insertOriginalUploadImageList(apiChat.getAttachment_id(),@R_223_10586@lChunks,originalFilePath,apiChat.getDt_sender_created(),chatAttachmentTypE);


                                                            // database.deleteAttachmentImageList(originalBase64ImagE);
                                                            database.deleteAttachmentImageList(originalFilePath);

                                                            UploadOriginalImageList(apiChat.getAttachment_id());

                                                        }
                                                  break;
                                                    } else {
                                                        // Log.e(tag,"onPostExecute_not_equal_image");
                                                    }
                                                }

                                            }
                                        }
                                    }


                            }

                        }
                    } catch (Exception E) {
                        e.printStackTrace();
                    }
                } else {
                    // Util.showAlertDialog(mContext,mContext.getresources().getString(R.String.No_internet_connection_availablE));
                }
            }
        } catch (Exception E) {
            e.printStackTrace();
            Log.e(tag,"error = " + e.getmessage());
        }

    }

解决方法

有很多方法可以将更多图像上传到服务器..一个可能包括两个库:apache-mime4j-0.6.jar和httpR_826_11845@ime-4.0.1.jar ..之后创建你的java主代码

import java.io.File;
import org.apache.http.httpentity;
import org.apache.http.httpResponse;
import org.apache.http.client.httpClient;
import org.apache.http.client.methods.httpPost;
import org.apache.http.entity.mime.multipartentity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaulthttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.progressDialog;
import android.content.Intent;
import android.database.cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.onClickListener;
import android.widget.button;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadTest extends Activity {

private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String SELEctedPath1 = "NONE";
String SELEctedPath2 = "NONE";
TextView tv,res;
ProgressDialog progressDialog;
Button b1,b2,b3;
httpentity resEntity;

@Override
public void onCreate(Bundle savedInstanceStatE) {
    super.onCreate(savedInstanceStatE);
    setContentView(R.layout.main);

    tv = (TextView)findViewById(R.id.tv);
    res = (TextView)findViewById(R.id.res);
    tv.setText(tv.getText() + SELEctedPath1 + "," + SELEctedPath2);
    b1 = (Button)findViewById(R.id.button01);
    b2 = (Button)findViewById(R.id.button02);
    b3 = (Button)findViewById(R.id.upload);
    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery(SELECT_FILE1);
        }
    });
    b2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery(SELECT_FILE2);
        }
    });
    b3.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!(SELEctedPath1.trim().equalsIgnoreCase("NONE")) && !(SELEctedPath2.trim().equalsIgnoreCase("NONE"))){
                progressDialog = ProgressDialog.show(FileUploadTest.this,"","Uploading files to server.....",falsE);
                 Thread thread=new Thread(new Runnable(){
                        public void run(){
                            doFileUpload();
                            runOnUiThread(new Runnable(){
                                public void run() {
                                    if(progressDialog.isShowing())
                                        progressDialog.dismiss();
                                }
                            });
                        }
                });
                thread.start();
            }else{
                        Toast.makeText(getApplicationContext(),"Please SELEct two files to upload.",Toast.LENGTH_SHORT).show();
            }
        }
    });

}

public void openGallery(int req_codE){

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"SELEct file to upload "),req_codE);

}

public void onActivityResult(int requestCode,int resultCode,Intent data) {

    if (resultCode == RESULT_OK) {
        Uri SELEctedImageUri = data.getData();
        if (requestCode == SELECT_FILE1)
        {
            SELEctedPath1 = getPath(SELEctedImageUri);
            System.out.println("SELEctedPath1 : " + SELEctedPath1);
        }
        if (requestCode == SELECT_FILE2)
        {
            SELEctedPath2 = getPath(SELEctedImageUri);
            System.out.println("SELEctedPath2 : " + SELEctedPath2);
        }
        tv.setText("SELEcted File paths : " + SELEctedPath1 + "," + SELEctedPath2);
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    cursor cursor = managedQuery(uri,projection,null);
    int column_index = cursor.getcolumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_indeX);
}

private void doFileUpload(){

    File file1 = new File(SELEctedPath1);
    File file2 = new File(SELEctedPath2);



import java.io.File;
import org.apache.http.httpentity;
import org.apache.http.httpResponse;
import org.apache.http.client.httpClient;
import org.apache.http.client.methods.httpPost;
import org.apache.http.entity.mime.multipartentity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaulthttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.progressDialog;
import android.content.Intent;
import android.database.cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.onClickListener;
import android.widget.button;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadTest extends Activity {

    private static final int SELECT_FILE1 = 1;
    private static final int SELECT_FILE2 = 2;
    String SELEctedPath1 = "NONE";
    String SELEctedPath2 = "NONE";
    TextView tv,res;
    ProgressDialog progressDialog;
    Button b1,b3;
    httpentity resEntity;

    @Override
    public void onCreate(Bundle savedInstanceStatE) {
        super.onCreate(savedInstanceStatE);
        setContentView(R.layout.main);

        tv = (TextView)findViewById(R.id.tv);
        res = (TextView)findViewById(R.id.res);
        tv.setText(tv.getText() + SELEctedPath1 + "," + SELEctedPath2);
        b1 = (Button)findViewById(R.id.button01);
        b2 = (Button)findViewById(R.id.button02);
        b3 = (Button)findViewById(R.id.upload);
        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(SELECT_FILE1);
            }
        });
        b2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(SELECT_FILE2);
            }
        });
        b3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!(SELEctedPath1.trim().equalsIgnoreCase("NONE")) && !(SELEctedPath2.trim().equalsIgnoreCase("NONE"))){
                    progressDialog = ProgressDialog.show(FileUploadTest.this,falsE);
                     Thread thread=new Thread(new Runnable(){
                            public void run(){
                                doFileUpload();
                                runOnUiThread(new Runnable(){
                                    public void run() {
                                        if(progressDialog.isShowing())
                                            progressDialog.dismiss();
                                    }
                                });
                            }
                    });
                    thread.start();
                }else{
                            Toast.makeText(getApplicationContext(),Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    public void openGallery(int req_codE){

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,req_codE);

 }


   public void onActivityResult(int requestCode,Intent data) {

        if (resultCode == RESULT_OK) {
            Uri SELEctedImageUri = data.getData();
            if (requestCode == SELECT_FILE1)
            {
                SELEctedPath1 = getPath(SELEctedImageUri);
                System.out.println("SELEctedPath1 : " + SELEctedPath1);
            }
            if (requestCode == SELECT_FILE2)
            {
                SELEctedPath2 = getPath(SELEctedImageUri);
                System.out.println("SELEctedPath2 : " + SELEctedPath2);
            }
            tv.setText("SELEcted File paths : " + SELEctedPath1 + "," + SELEctedPath2);
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        cursor cursor = managedQuery(uri,null);
        int column_index = cursor.getcolumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_indeX);
    }

    private void doFileUpload(){

        File file1 = new File(SELEctedPath1);
        File file2 = new File(SELEctedPath2);
        String urlString = "http://10.0.2.2/upload_test/upload_media_test.PHP";
        try
        {
             httpClient client = new DefaulthttpClient();
             httpPost post = new httpPost(urlString);
             FileBody bin1 = new FileBody(file1);
             FileBody bin2 = new FileBody(file2);
             multipartentity reqEntity = new multipartentity();
             reqEntity.addPart("uploadedfile1",bin1);
             reqEntity.addPart("uploadedfile2",bin2);
             reqEntity.addPart("user",new StringBody("User"));
             post.setEntity(reqEntity);
             httpResponse response = client.execute(post);
             resEntity = response.getEntity();
             final String response_str = EntityUtils.toString(resEntity);
             if (resEntity != null) {
                 Log.i("RESPONSE",response_str);
                 runOnUiThread(new Runnable(){
                        public void run() {
                             try {
                                res.setTextColor(Color.GREEN);
                                res.setText("n Response from server : n " + response_str);
                                Toast.makeText(getApplicationContext(),"Upload Complete. check the server uploads directory.",Toast.LENGTH_LONG).show();
                            } catch (Exception E) {
                                e.printStackTrace();
                            }
                           }
                    });
             }
        }
        catch (Exception eX){
             Log.e("Debug","error: " + ex.getmessage(),eX);
        }
      }
}

现在你的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://scheR_826_11845@as.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Multiple File Upload from CoderzHeaven"
    />
<Button
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get First File">
</Button>
<Button
    android:id="@+id/Button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Second File">
</Button>
<Button
    android:id="@+id/upload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Upload">
</Button>
<TextView
    android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="SELEcted File path : "
    />

<TextView
    android:id="@+id/res"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text=""
   />
</LinearLayout>

当然,在您的清单中包含互联网权限:

<uses-permission android:name="android.permission.INTERNET" />

瞧.无论如何,我在我的情况下遵循这个例子:http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/尝试看那里..有4种方法上传多个文件.看看你喜欢哪个

大佬总结

以上是大佬教程为你收集整理的android – 如何使用意图服务与服务更新UI进行多个图像上传全部内容,希望文章能够帮你解决android – 如何使用意图服务与服务更新UI进行多个图像上传所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。