android– 如何使用意图服务与服务更新UI进行多个图像上传

android– 如何使用意图服务与服务更新UI进行多个图像上传,第1张

概述我是android开发人员.当我使用intent服务在后台发送多个图像时,我有面子问题ANR.我在Resume()方法上有调用服务.我在逐步图像上传完成时有更新UI.我的所有代码都在服务中.但是我不明白为什么我的UI挂起.我已经为UpdateUI创建了ResultReceiver类.请告诉我我在做什么问题.publicc

我是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, dateTime, classtype, loginUserID;// Declare Web services variableprivate multipartentity multipartentityBuilder;Database database;Bundle bundle;ResultReceiver receiver;public UploadImageService() {    super(UploadImageService.class.getname());}@OverrIDeprotected 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, chatThreadID, threadtopicname, chatAttachmentType, chatMessage, thumbBase64AttachmentPath /*original_image*/, loginUsername, recipIEntname, 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, chatMessage, thumbBase64AttachmentPath, originalBase64Image, 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, result, "#", db_message, db_thumb, loginUserID, toUser, chatThreadID, 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 totalChunks = 0;                                                        if (!TextUtils.isEmpty(originalBase64Image)) {                                                            for (int k = 0; index < originalBase64Image.length(); k++) {                                                                index = index + subLength;                                                                totalChunks++;                                                            }                                            database.insertOriginalUploadImageList(APIChat.getAttachment_ID(), totalChunks, 0, originalfilePath, chatThreadID, 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和httpmime-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;@OverrIDepublic 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, null, 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,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, null, 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://schemas.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进行多个图像上传所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1119879.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存