如果应用程序转到后台,服务中的AsyncTask不会被执行

时间:2014-09-21 06:25:12

标签: android service android-asynctask

我在服务中使用AsyncTask,以便将数据从本地数据库上传到服务器。

如果我从Activity启动服务并且应用程序仍处于前台,则所有工作都完美无缺。但是,如果我将我的应用程序发送到后台,则Asynctask不会被执行,因此不会上传任何数据。

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

public class UploadDataService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        final Intent dataIntent = intent;

        ArrayList<String>CASE_ID_ARRAY                = dataIntent.getStringArrayListExtra("CASE_ID_ARRAY");
        ArrayList<String>CPV_NUMBER_ARRAY             = dataIntent.getStringArrayListExtra("CPV_NUMBER_ARRAY");
        ArrayList<String>CUSTOMER_NAME_ARRAY          = dataIntent.getStringArrayListExtra("CUSTOMER_NAME_ARRAY");
        ArrayList<String>BILLING_LANDMARK_ARRAY       = dataIntent.getStringArrayListExtra("BILLING_LANDMARK_ARRAY");
        ArrayList<String>BILLING_LANDLINE_ARRAY       = dataIntent.getStringArrayListExtra("BILLING_LANDLINE_ARRAY");
        ArrayList<String>EMAIL_ID_ARRAY               = dataIntent.getStringArrayListExtra("EMAIL_ID_ARRAY");
        ArrayList<String>BILLING_ADDRESS_CHANGE_ARRAY = dataIntent.getStringArrayListExtra("BILLING_ADDRESS_CHANGE_ARRAY");
        ArrayList<String>COMPANY_LANDMARK_ARRAY       = dataIntent.getStringArrayListExtra("COMPANY_LANDMARK_ARRAY");
        ArrayList<String>COMPANY_LANDLINE_ARRAY       = dataIntent.getStringArrayListExtra("COMPANY_LANDLINE_ARRAY");
        ArrayList<String>COMPANY_ADDRESS_CHANGE_ARRAY = dataIntent.getStringArrayListExtra("COMPANY_ADDRESS_CHANGE_ARRAY");
        ArrayList<String>ADDRESS_TYPE_ARRAY           = dataIntent.getStringArrayListExtra("ADDRESS_TYPE_ARRAY");
        ArrayList<String>ADDRESS_VERIFIED_ARRAY       = dataIntent.getStringArrayListExtra("ADDRESS_VERIFIED_ARRAY");
        ArrayList<String>SUB_IDENTITY_CONFIRM_ARRAY   = dataIntent.getStringArrayListExtra("SUB_IDENTITY_CONFIRM_ARRAY");
        ArrayList<String>VISIT_MONTH_ARRAY            = dataIntent.getStringArrayListExtra("VISIT_MONTH_ARRAY");
        ArrayList<String>VISIT_DATE_ARRAY             = dataIntent.getStringArrayListExtra("VISIT_DATE_ARRAY");
        ArrayList<String>VISIT_YEAR_ARRAY             = dataIntent.getStringArrayListExtra("VISIT_YEAR_ARRAY");             
        ArrayList<String>VISIT_TIME_HOUR_ARRAY        = dataIntent.getStringArrayListExtra("VISIT_TIME_HOUR_ARRAY");
        ArrayList<String>VISIT_TIME_MINUTE_ARRAY      = dataIntent.getStringArrayListExtra("VISIT_TIME_MINUTE_ARRAY");
        ArrayList<String>PERSON_CONTACT_ARRAY         = dataIntent.getStringArrayListExtra("PERSON_CONTACT_ARRAY");
        ArrayList<String>RELATION_PERSON_ARRAY        = dataIntent.getStringArrayListExtra("RELATION_PERSON_ARRAY");
        ArrayList<String>REMARKS_ARRAY                = dataIntent.getStringArrayListExtra("REMARKS_ARRAY");
        ArrayList<String>SIM_RECEIVED_ARRAY           = dataIntent.getStringArrayListExtra("SIM_RECEIVED_ARRAY");
        ArrayList<String>NEIGHBOUR_CHECKED_ARRAY      = dataIntent.getStringArrayListExtra("NEIGHBOUR_CHECKED_ARRAY");
        ArrayList<String>HOUSE_AREA_ARRAY             = dataIntent.getStringArrayListExtra("HOUSE_AREA_ARRAY");
        ArrayList<String>HOUSE_LOCALITY_ARRAY         = dataIntent.getStringArrayListExtra("HOUSE_LOCALITY_ARRAY");
        ArrayList<String>HOUSE_OWNERSHIP_ARRAY        = dataIntent.getStringArrayListExtra("HOUSE_OWNERSHIP_ARRAY");
        ArrayList<String>RESIDENCE_TYPE_ARRAY         = dataIntent.getStringArrayListExtra("RESIDENCE_TYPE_ARRAY");
        ArrayList<String>HOUSE_APPROACH_ARRAY         = dataIntent.getStringArrayListExtra("HOUSE_APPROACH_ARRAY");
        ArrayList<String>HOUSE_LOCATION_ARRAY         = dataIntent.getStringArrayListExtra("HOUSE_LOCATION_ARRAY");
        ArrayList<String>EXTERIOR_CONDITION_ARRAY     = dataIntent.getStringArrayListExtra("EXTERIOR_CONDITION_ARRAY");
        ArrayList<String>INTERIOR_CONDITION_ARRAY     = dataIntent.getStringArrayListExtra("INTERIOR_CONDITION_ARRAY");
        ArrayList<String>THIRD_PARTY_CONTACT_ARRAY    = dataIntent.getStringArrayListExtra("THIRD_PARTY_CONTACT_ARRAY");
        ArrayList<String>ASSETS_TV_ARRAY              = dataIntent.getStringArrayListExtra("ASSETS_TV_ARRAY");
        ArrayList<String>ASSETS_AC_ARRAY              = dataIntent.getStringArrayListExtra("ASSETS_AC_ARRAY");
        ArrayList<String>ASSETS_FRIDGE_ARRAY          = dataIntent.getStringArrayListExtra("ASSETS_FRIDGE_ARRAY");
        ArrayList<String>ASSETS_MUSIC_ARRAY           = dataIntent.getStringArrayListExtra("ASSETS_MUSIC_ARRAY");
        ArrayList<String>ASSETS_NA_ARRAY              = dataIntent.getStringArrayListExtra("ASSETS_NA_ARRAY");
        ArrayList<String>NEGATIVE_AREA_ARRAY          = dataIntent.getStringArrayListExtra("NEGATIVE_AREA_ARRAY");
        ArrayList<String>FAMILY_STRUCTURE_ARRAY       = dataIntent.getStringArrayListExtra("FAMILY_STRUCTURE_ARRAY");
        ArrayList<String>FAMILY_STATUS_ARRAY          = dataIntent.getStringArrayListExtra("FAMILY_STATUS_ARRAY");
        ArrayList<String>ORGANISATION_ARRAY           = dataIntent.getStringArrayListExtra("ORGANISATION_ARRAY");
        ArrayList<String>PROFESSION_ARRAY             = dataIntent.getStringArrayListExtra("PROFESSION_ARRAY");
        ArrayList<String>SERVICE_YEAR_ARRAY           = dataIntent.getStringArrayListExtra("SERVICE_YEAR_ARRAY");
        ArrayList<String>VEHICLE_ARRAY                = dataIntent.getStringArrayListExtra("VEHICLE_ARRAY");
        ArrayList<String>EDUCATION_ARRAY              = dataIntent.getStringArrayListExtra("EDUCATION_ARRAY");
        ArrayList<String>AGENT_RATING_ARRAY           = dataIntent.getStringArrayListExtra("AGENT_RATING_ARRAY");
        ArrayList<String>CPV_STATUS_ARRAY             = dataIntent.getStringArrayListExtra("CPV_STATUS_ARRAY");
        ArrayList<String>ST_REMARK_ARRAY              = dataIntent.getStringArrayListExtra("ST_REMARK_ARRAY");
        ArrayList<String>LATITUDE_ARRAY               = dataIntent.getStringArrayListExtra("LATITUDE_ARRAY");
        ArrayList<String>LONGITUDE_ARRAY              = dataIntent.getStringArrayListExtra("LONGITUDE_ARRAY");
        ArrayList<String>SIGNATURE_IMAGE_ARRAY        = dataIntent.getStringArrayListExtra("SIGNATURE_IMAGE_ARRAY");
        ArrayList<String>JPEG_ONE_ARRAY               = dataIntent.getStringArrayListExtra("JPEG_ONE_ARRAY");
        ArrayList<String>JPEG_TWO_ARRAY               = dataIntent.getStringArrayListExtra("JPEG_TWO_ARRAY");
        ArrayList<String>JPEG_THREE_ARRAY             = dataIntent.getStringArrayListExtra("JPEG_THREE_ARRAY");


        for (int i = 0; i < CASE_ID_ARRAY.size(); i++) {
            new UploadDataTask(getApplicationContext()).execute(
                    CASE_ID_ARRAY.get(i),
                    CPV_NUMBER_ARRAY.get(i),
                    CUSTOMER_NAME_ARRAY.get(i),
                    BILLING_LANDMARK_ARRAY.get(i),
                    BILLING_LANDLINE_ARRAY.get(i),
                    EMAIL_ID_ARRAY.get(i),
                    BILLING_ADDRESS_CHANGE_ARRAY.get(i),
                    COMPANY_LANDMARK_ARRAY.get(i),
                    COMPANY_LANDLINE_ARRAY.get(i),
                    COMPANY_ADDRESS_CHANGE_ARRAY.get(i),
                    ADDRESS_TYPE_ARRAY.get(i),
                    ADDRESS_VERIFIED_ARRAY.get(i),
                    SUB_IDENTITY_CONFIRM_ARRAY.get(i),
                    VISIT_MONTH_ARRAY.get(i),
                    VISIT_DATE_ARRAY.get(i),
                    VISIT_YEAR_ARRAY.get(i),    
                    VISIT_TIME_HOUR_ARRAY.get(i),
                    VISIT_TIME_MINUTE_ARRAY.get(i),
                    PERSON_CONTACT_ARRAY.get(i),
                    RELATION_PERSON_ARRAY.get(i),
                    REMARKS_ARRAY.get(i),
                    SIM_RECEIVED_ARRAY.get(i),
                    NEIGHBOUR_CHECKED_ARRAY.get(i),
                    HOUSE_AREA_ARRAY.get(i),
                    HOUSE_LOCALITY_ARRAY.get(i),
                    HOUSE_OWNERSHIP_ARRAY.get(i),
                    RESIDENCE_TYPE_ARRAY.get(i),
                    HOUSE_APPROACH_ARRAY.get(i),
                    HOUSE_LOCATION_ARRAY.get(i),
                    EXTERIOR_CONDITION_ARRAY.get(i),
                    INTERIOR_CONDITION_ARRAY.get(i),
                    THIRD_PARTY_CONTACT_ARRAY.get(i),
                    ASSETS_TV_ARRAY.get(i),
                    ASSETS_AC_ARRAY.get(i),
                    ASSETS_FRIDGE_ARRAY.get(i),
                    ASSETS_MUSIC_ARRAY.get(i),
                    ASSETS_NA_ARRAY.get(i),
                    NEGATIVE_AREA_ARRAY.get(i),
                    FAMILY_STRUCTURE_ARRAY.get(i),
                    FAMILY_STATUS_ARRAY.get(i),
                    ORGANISATION_ARRAY.get(i),
                    PROFESSION_ARRAY.get(i),
                    SERVICE_YEAR_ARRAY.get(i),
                    VEHICLE_ARRAY.get(i),
                    EDUCATION_ARRAY.get(i),
                    AGENT_RATING_ARRAY.get(i),
                    CPV_STATUS_ARRAY.get(i),
                    ST_REMARK_ARRAY.get(i),
                    LATITUDE_ARRAY.get(i),
                    LONGITUDE_ARRAY.get(i),
                    SIGNATURE_IMAGE_ARRAY.get(i),
                    JPEG_ONE_ARRAY.get(i),
                    JPEG_TWO_ARRAY.get(i),
                    JPEG_THREE_ARRAY.get(i)
                    );
        }

        return Service.START_NOT_STICKY;
    }




}

class UploadDataTask extends AsyncTask<String, Integer, String> {

    Context mContext;
    String CPVNUMBER = null;

    public UploadDataTask(Context context) {
        this.mContext = context;
    }

    @Override
    protected String doInBackground(String... strings) {
        String CASEID               = strings[0];
        CPVNUMBER                   = strings[1];
        String EXEC_CODE            = strings[2];
        String BILLINGLANDMARK      = strings[3];
        String BILLINGLANDLINE      = strings[4];
        String EMAILID              = strings[5];
        String BILLINGADDRESSCHANGE = strings[6];
        String COMPANYLANDMARK      = strings[7];
        String COMPANYLANDLINE      = strings[8];
        String COMPANYADDRESSCHANGE = strings[9];
        String ADDTYPE              = strings[10];
        String ADDRESSVERIFIED      = strings[11];
        String SUBIDENTITYCONFIRM   = strings[12];
        String VISITMONTH           = strings[13];
        String VISITDATE            = strings[14];
        String VISITYEAR            = strings[15];
        String VISITTIMEHOUR        = strings[16];
        String VISITTIMEMINUTE      = strings[17];
        String PERSONCONTACT        = strings[18];
        String RELATIONPERSON       = strings[19];
        String REMARKS              = strings[20];
        String SIMRECEIVED          = strings[21];
        String NEIGHBORCHECK        = strings[22];
        String HOUSEAREA            = strings[23];
        String HOUSELOCALITY        = strings[24];
        String HOUSEOWNERSHIP       = strings[25];
        String RESIDENCETYPE        = strings[26];
        String HOUSEAPPROACH        = strings[27];
        String HOUSELOCATION        = strings[28];
        String EXTERIORCONDITION    = strings[29];
        String INTERIORCONDITION    = strings[30];
        String THIRDPARTYCONTACT    = strings[31];
        String ASSETSTV             = strings[32];
        String ASSETSAC             = strings[33];
        String ASSETSFRIDGE         = strings[34];
        String ASSETSMUSIC          = strings[35];
        String ASSETSNA             = strings[36];
        String NEGATIVEAREA         = strings[37];
        String FAMILYSTRUCTURE      = strings[38];
        String FAMILYSTATUS         = strings[39];
        String ORGANISATION         = strings[40];
        String PROFESSION           = strings[41];
        String SERVICEYEAR          = strings[42];
        String VEHICLE              = strings[43];
        String EDUCATION            = strings[44];
        String AGENTRATING          = strings[45];
        String CPVSTATUS            = strings[46];
        String STREMARK             = strings[47];
        String LATITUDE             = strings[48];
        String LONGITUDE            = strings[49];
        String SIGNATUREIMAGE       = strings[50];
        String JPEGONEIMAGE         = strings[51];
        String JPEFTWOIMAGE         = strings[52];
        String JPEGTHREEIMAGE       = strings[53];



        List<NameValuePair> pairs = new ArrayList<NameValuePair>();

        pairs.add(new BasicNameValuePair("ID", CASEID));
        pairs.add(new BasicNameValuePair("cpv_number", CPVNUMBER));
        pairs.add(new BasicNameValuePair("EXEC_CODE", EXEC_CODE));
        pairs.add(new BasicNameValuePair("code", EXEC_CODE));
        pairs.add(new BasicNameValuePair("BILLING_LANDMARK", BILLINGLANDMARK));
        pairs.add(new BasicNameValuePair("BILLING_LANDLINE", BILLINGLANDLINE));
        pairs.add(new BasicNameValuePair("EMAIL", EMAILID));
        pairs.add(new BasicNameValuePair("BILLING_ADDRESS_CHANGE", BILLINGADDRESSCHANGE));
        pairs.add(new BasicNameValuePair("COMPANY_LANDMARK", COMPANYLANDMARK));
        pairs.add(new BasicNameValuePair("COMPANY_LANDLINE", COMPANYLANDLINE));
        pairs.add(new BasicNameValuePair("COMPANY_ADDRESS_CHANGE", COMPANYADDRESSCHANGE));
        pairs.add(new BasicNameValuePair("ADD_TYPE", ADDTYPE));
        pairs.add(new BasicNameValuePair("ADDRESS_VERIFIED", ADDRESSVERIFIED));


        pairs.add(new BasicNameValuePair("SUB_IDENTITY_CONFIRM", SUBIDENTITYCONFIRM));
        pairs.add(new BasicNameValuePair("visit_mm", VISITMONTH));
        pairs.add(new BasicNameValuePair("visit_dd", VISITDATE));
        pairs.add(new BasicNameValuePair("visit_yy", VISITYEAR));
        pairs.add(new BasicNameValuePair("visit_time_hh", VISITTIMEHOUR));
        pairs.add(new BasicNameValuePair("visit_time_mm", VISITTIMEMINUTE));


        pairs.add(new BasicNameValuePair("PERSON_CONTACT", PERSONCONTACT));
        pairs.add(new BasicNameValuePair("RELATION_PERSON", RELATIONPERSON));
        pairs.add(new BasicNameValuePair("REMARKS", REMARKS));
        pairs.add(new BasicNameValuePair("SIM_RECD", SIMRECEIVED));
        pairs.add(new BasicNameValuePair("NEIGHBOR_CHECK", NEIGHBORCHECK));
        pairs.add(new BasicNameValuePair("HOUSE_AREA", HOUSEAREA));


        pairs.add(new BasicNameValuePair("HOUSE_LOCALITY", HOUSELOCALITY));
        pairs.add(new BasicNameValuePair("HOUSE_OWNERSHIP", HOUSEOWNERSHIP));
        pairs.add(new BasicNameValuePair("RESIDENCE_TYPE", RESIDENCETYPE));
        pairs.add(new BasicNameValuePair("HOUSE_APPROACH", HOUSEAPPROACH));
        pairs.add(new BasicNameValuePair("HOUSE_LOCATION", HOUSELOCATION));
        pairs.add(new BasicNameValuePair("EXTERIOR_CONDITION", EXTERIORCONDITION));


        pairs.add(new BasicNameValuePair("INTERIOR_CONDITION", INTERIORCONDITION));
        pairs.add(new BasicNameValuePair("THIRD_PARTY_CONTACT", THIRDPARTYCONTACT));
        pairs.add(new BasicNameValuePair("ASSETS_TV", ASSETSTV));
        pairs.add(new BasicNameValuePair("ASSETS_AC", ASSETSAC));
        pairs.add(new BasicNameValuePair("ASSETS_FRIDGE", ASSETSFRIDGE));
        pairs.add(new BasicNameValuePair("ASSETS_MUSIC", ASSETSMUSIC));


        pairs.add(new BasicNameValuePair("ASSETS_NA", ASSETSNA));
        pairs.add(new BasicNameValuePair("NEGATIVE_AREA", NEGATIVEAREA));
        pairs.add(new BasicNameValuePair("FAMILY_STRUCTURE", FAMILYSTRUCTURE));
        pairs.add(new BasicNameValuePair("FAMILY_STATUS", FAMILYSTATUS));
        pairs.add(new BasicNameValuePair("ORGANISATION", ORGANISATION));
        pairs.add(new BasicNameValuePair("PROFESSION", PROFESSION));


        pairs.add(new BasicNameValuePair("SERVICE_YEAR", SERVICEYEAR));
        pairs.add(new BasicNameValuePair("VEHICLE", VEHICLE));
        pairs.add(new BasicNameValuePair("EDUCATION", EDUCATION));
        pairs.add(new BasicNameValuePair("AGENT_RATING", AGENTRATING));
        pairs.add(new BasicNameValuePair("CPV_STATUS", CPVSTATUS));
        pairs.add(new BasicNameValuePair("ST_REMARK", STREMARK));

        pairs.add(new BasicNameValuePair("cpv_lat", LATITUDE));
        pairs.add(new BasicNameValuePair("cpv_long", LONGITUDE));


        pairs.add(new BasicNameValuePair("jpgfile2", JPEGONEIMAGE));
        pairs.add(new BasicNameValuePair("jpgfile3", JPEFTWOIMAGE));
        pairs.add(new BasicNameValuePair("jpgfile4", JPEGTHREEIMAGE));
        pairs.add(new BasicNameValuePair("signature", SIGNATUREIMAGE));


        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);
        HttpClient mHttpClient = new DefaultHttpClient(params);
        HttpPost localHttpPost = new HttpPost("http://example.com/Update.aspx");
        localHttpPost.setHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=UTF-8");


        try {
            localHttpPost.setEntity(new UrlEncodedFormEntity(pairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();               

            String response = mHttpClient.execute(localHttpPost, responseHandler);
            System.out.println(response);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("Exception", e.getLocalizedMessage());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e("Exception", e.getLocalizedMessage());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Exception", e.getLocalizedMessage());
        }



        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(mContext)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Case Upload Successfully")
        .setContentText("Case With CPV Number "+ CPVNUMBER +" uploaded successfully")
        .setAutoCancel(true);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(mContext, MainActivity.class);

        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
        NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.
        mNotificationManager.notify(0, mBuilder.build());

    }



}

1 个答案:

答案 0 :(得分:0)

没有理由创建所有这些AsyncTasks。创建一个简单的Thread来完成您的工作并在那里进行循环。

您正在Service.START_NOT_STICKY中返回onStartCommand,告知系统 NOT 如果过早被杀,则重新启动服务。你应该回来了。 Service.START_REDELIVER_INTENT