在android中的后台服务中上传图片时应用程序卡住

时间:2015-06-18 09:06:21

标签: android service android-service

我正在从后台服务上传图片。 我的应用程序在上传图片时卡住了。 此外,在处理后台服务之前,我无法处理其他网络API请求。

我的活动课程 的 CartActivity.class

public class CartActivity extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart_screen);

        Intent serviceIntent = new Intent(CartActivity.this, UploadImgService.class);
        startService(serviceIntent);
        }
}

我的服务类,我从本地数据库中获取数据并上传到服务器。 的 UploadImgService.class

public class UploadImgService  extends Service {

//local database
private DataSourceUserRecords dataResource ; 
private SQLiteDatabase _database = null;
private Cursor _cursor = null;
private MySqliteHelper DBHelper; 


private String _userID = "";
private  String _uniqueID = "";
private String _imageName = "";
private String _imgPath = "";
private int _idDB =0; 
private Bitmap _imgBitmap;
private String _base64Str = "";



JSONObject outerJsonObject ;
JSONArray _mainArray ;


HttpClient client;
String _responseMain = "";
HttpResponse responseMain;
@Override
public void onCreate() {
    super.onCreate();
    // This method is invoked when the service is called.
    // Need to fetch all the data from Local database

    // do subroutines here
    System.out.println("onCreate of Service  " );
    try{

        outerJsonObject = new JSONObject();
        _mainArray = new JSONArray();

        DBHelper = new MySqliteHelper(UploadImgService.this);
        _database = DBHelper.getWritableDatabase();
        dataResource  = new DataSourceUserRecords(UploadImgService.this);
        dataResource.open();

        //  _database = context.openOrCreateDatabase(MySqliteHelper, arg1, arg2)

        //dataResource  = new DataSourceUserRecords(context);
        //_database= context.openOrCreateDatabase(MySqliteHelper.DATABASE_NAME, MODE_PRIVATE, null);
        _cursor = _database.rawQuery("select * from "+MySqliteHelper.TABLE_NAME, null);

        _cursor.moveToFirst(); 
        while(_cursor.isAfterLast() == false){

            _idDB =  _cursor.getInt(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_ID));
            _userID =  _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_USER_ID));
            _uniqueID =  _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_UNIQUE_ID));
            _imageName =  _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_IMG_NAME));
            _imgPath =  _cursor.getString(_cursor.getColumnIndex(MySqliteHelper.READING_DETAILS_COLUMN_IMAGE_PATH));

            System.out.println("DATA base column id :" + _idDB);
            System.out.println("USer id from db : "  + _userID);
            System.out.println("Unique Name from db : " + _uniqueID);
            System.out.println("Image Name from db : " + _imageName);
            System.out.println("Image path from db : " +_imgPath);




            JSONObject _jSubObj = new JSONObject();
            _imgBitmap = BitmapFactory.decodeFile(_imgPath);
            _base64Str =  Constant.convertBitmapToBase64(_imgBitmap);
            _jSubObj.put("user_id", _userID);
            _jSubObj.put("unique_id", _uniqueID);
            _jSubObj.put("img_name", "image_" + _cursor.getPosition()/*+_temp_orderid*/);
            _jSubObj.put("img_base", _base64Str);


            _mainArray.put(_jSubObj);


            _cursor.moveToNext();
        }
        _cursor.close();

        try {
            outerJsonObject.put("image_details",_mainArray);
            if (NetworkAvailablity.checkNetworkStatus(UploadImgService.this)) {





                try {
                    // Creating HTTP client
                    client = new DefaultHttpClient();

                    // Creating HTTP Post
                    HttpPost httpPost= new HttpPost(WebServiceConstants
                            .getMethodUrl(WebServiceConstants.METHOD_UPLOAD_IMAGES));



                    // Building post parameters, key and value pair
                    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

                    nameValuePair.add(new BasicNameValuePair("image_details", outerJsonObject.toString()));
                    //                  nameValuePair.add(new BasicNameValuePair("order_details", _mainArray.toString()));

                    // Url Encoding the POST parameters
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
                    responseMain = client.execute(httpPost);
                    HttpEntity entitity = responseMain.getEntity();

                    _responseMain = EntityUtils.toString(entitity); // content will be consume only once
                    System.out.println("Response of Upload image : "+_responseMain);
                    //                      System.out.println("_catID : "  +_catID);
                } catch (UnsupportedEncodingException e) {
                    // writing error to Log
                    e.printStackTrace();
                    /*Constant.alertDialogShow(UploadImgService.this, getResources().getString(R.string.messageText),
                            "Internal server error.", "");*/

                }
                catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();


                }




            System.out.println("OuterJSON request upload image "+outerJsonObject);


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

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

}




@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
    // A client or activity is binded to service
}

}

1 个答案:

答案 0 :(得分:4)

使用IntentService而不是服务。 IntentService在反向线程上工作。 read this