0

我正在android wrein中开发一个应用程序我调用一个服务,该服务将在单击按钮时将xml文件上传到服务器。问题是当我第一次单击按钮时它没有被上传但是当我第二次单击按钮时它得到上传...所以让我知道是否有任何解决方案..请帮助我。

下面是扩展服务的代码

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

public class Uploader extends Service
{
    String info;
    String phot_loc;
    int category;
    String phonenumber = null,profile_name=null,email_id=null;
    double longi;
    double latti;
    Runnable runner;


    //UIhandler to display the status of upload on response from server
    Handler uiHandler = new Handler();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        if(intent!=null)
        {
            info=intent.getStringExtra("info");
            phot_loc=intent.getStringExtra("photo_loc");
            category=intent.getIntExtra("category",0);
            phonenumber=intent.getStringExtra("phone_number");
            profile_name=intent.getStringExtra("profile_name");
            email_id=intent.getStringExtra("email_id");
            longi=intent.getDoubleExtra("longitude",0);
            latti=intent.getDoubleExtra("latitude",0);
            phonenumber=intent.getStringExtra("phone_number");
            Log.d("UploadService","Indide upload Activity");

            Thread t=new Thread(runner);
            t.start();
        }

        //this will perform the uploading process
        runner=new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
            try
            {

                Log.d("UploadService","Indide upload Activity RIUNNER");


                String xml = createXml();

                RestClient client = new RestClient("http://3pixelart.com/complaint_process.php",xml);
                //Log.d("UploadService", xml);

                try {
                      client.Execute();
                      MyRunnable r = new MyRunnable("Complaint Uploaded Successfully");
                        uiHandler.post(r);
                }
                catch(Exception e)
                {
                    Log.e("UploadService", "Exception in uploading :"+e.getMessage());
                    MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage());
                    uiHandler.post(r);

                }

            }
            catch(Exception e)
            {
                Log.e("UploadService", "Exception:"+e.getMessage());
                MyRunnable r=new MyRunnable("Error in uploading the complaint..");
                uiHandler.post(r);
            }

            }



        };




    }

    public String createXml() {


         Log.d("UploadService","Indide upload Activity  create xml 1");


             Log.d("UploadService","Indide upload Activity  create xml 2");

            Date d = new Date();

            //SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");

            //String time = formatter.format(d);

             Log.d("UploadService","Indide upload Activity  create xml 3");
            String imageData = getBase64ImageData();

            SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");

             Log.d("UploadService","Indide upload Activity  create xml 5");

            String filename = "image"+fileNameFormatter.format(d)+".png";


            String finaldata="<?xml version=\"1.0\"?>";
            finaldata+="<ClientRequest><MobileNumber>"+phonenumber+"</MobileNumber><Longitude>";
            finaldata+=longi+"</Longitude><Lattitude>"+latti+"</Lattitude>";
            finaldata+="<Category>"+category+"</Category>";
            finaldata+="<Profilename>"+profile_name+"</Profilename><Email>"+email_id+"</Email>";
            finaldata+="<FileName>"+filename+"</FileName><Image>"+imageData+"</Image><Info>";
            finaldata+=info+"</Info></ClientRequest>";

            Log.d("UploadService","The DATA IS :  "+finaldata);
            return finaldata;

        }


    private String getBase64ImageData() {
        // TODO Auto-generated method stub

    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inSampleSize = 8; 
            Bitmap bitmapOrg = BitmapFactory.decodeFile(phot_loc,options);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte [] ba = bao.toByteArray();

            String encodedImage = Base64.encodeToString(ba, Base64.DEFAULT);
            //Log.d("UploadService", encodedImage);
            bitmapOrg=null;
            System.gc();
        return encodedImage;
    }


    //this is used to display the status of uploading for this u require UIHandler
    public class MyRunnable implements Runnable{
        private String message=null;

        public MyRunnable(String message) {
            // TODO Auto-generated constructor stub
            this.message=message;
        }
        public void run() {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        }
    };




}

这是我的活动,其中包含该服务

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
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.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ComplaintActivity extends Activity implements OnClickListener
{

    boolean pic_taken=false;
    Button bpicture,bregister;
    EditText description;
    ImageView iv1;
    int category=0;
    private static final int TAKE_PICTURE = 1;
    String Provider_name="";
    Location currentLocation;


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

        bpicture=(Button) findViewById(R.id.button1);
        bregister=(Button) findViewById(R.id.button2);
        iv1=(ImageView) findViewById(R.id.taken_pic);
        description=(EditText)findViewById(R.id.editText1);

        bpicture.setOnClickListener(ComplaintActivity.this);
        bregister.setOnClickListener(ComplaintActivity.this);

        LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        List <String> l1=manager.getProviders(true);
        if(l1.contains(LocationManager.GPS_PROVIDER))
        {
            Provider_name=LocationManager.GPS_PROVIDER;

        }
        if(l1.contains(LocationManager.NETWORK_PROVIDER))
        {
            Provider_name=LocationManager.NETWORK_PROVIDER;
        }

        currentLocation=manager.getLastKnownLocation(Provider_name);
        Toast.makeText(ComplaintActivity.this, "GPS PROVIDERS "+Provider_name+"Lattti:"+currentLocation.getLatitude()+"Long:"+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
        LocationListener listener=new MyLocationListener();
        manager.requestLocationUpdates(Provider_name, 0, 0, listener);




    }

    class MyLocationListener implements LocationListener
    {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            currentLocation=location;

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        if(arg0==bpicture)
            take_picture();
        if(arg0==bregister)
            register_complaint();

    }


    private void take_picture() {
        // TODO Auto-generated method stub
        Intent int_cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri Outputfile=Uri.parse("file:///sdcard/temppic.jpg");
        int_cam.putExtra(MediaStore.EXTRA_OUTPUT,Outputfile);
        startActivityForResult(int_cam,TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        //Log.d("BAKRA","INSIDE CAMEra Activity>>>>>>>>>>>");
        if(requestCode==1)
        {
            //Log.d("BAKRA","INSIDE FIRST IF  >>>>>>>>>>>");
            if(resultCode==RESULT_OK)
            {
            //  Log.d("BAKRA","INSIDE SECONG IF  >>>>>>>>>>>");
                if(data==null)
                {
                //  Log.d("BAKRA","INSIDE THIRD IF  >>>>>>>>>>>");
                    pic_taken=true;
                    BitmapFactory.Options opt=new BitmapFactory.Options();
                    opt.inSampleSize=8;
                    Bitmap bitorg=BitmapFactory.decodeFile("sdcard/temppic.jpg", opt);
                //  Log.d("BAKRA","INSIDE CAME>>>>>>>>>>>");
                    iv1.setImageBitmap(bitorg);

                }
            }

        }
    }

    private void register_complaint() {
        // TODO Auto-generated method stub

        if(!pic_taken)
        {
            Toast.makeText(ComplaintActivity.this, "Please Take the Picture Related to the Query", Toast.LENGTH_LONG).show();
            return;
        }
        if(description.getText().toString().equals(""))
        {
            Toast.makeText(ComplaintActivity.this, "Please Enter Details About the Complaint",Toast.LENGTH_LONG).show();
            return;
        }
        else
        {
            Intent up=new Intent(ComplaintActivity.this,Uploader.class);
            up.putExtra("category",getIntent().getIntExtra("Selected",1));
            up.putExtra("info", description.getText().toString());
            up.putExtra("photo_loc", "/sdcard/temppic.jpg");
            up.putExtra("latitude", currentLocation.getLatitude());
            up.putExtra("longitude", currentLocation.getLongitude());

            SQLiteDatabase db=openOrCreateDatabase("LBA", MODE_PRIVATE, null);
            Cursor c=db.rawQuery("select * from users", null);
            String phonenumber = null,profile_name=null,email_id=null;
            if(c.moveToFirst())
            {

                profile_name=c.getString(c.getColumnIndex("profilename"));
                email_id=c.getString(c.getColumnIndex("emailid"));
                phonenumber=c.getString(c.getColumnIndex("phonenumber"));
            }
            up.putExtra("phone_number", phonenumber);
            up.putExtra("profile_name", profile_name);
            up.putExtra("email_id", email_id);
            startService(up);
            Toast.makeText(ComplaintActivity.this, "Uploading to Server...",Toast.LENGTH_LONG).show();
            finish();
        }

    }





}
4

1 回答 1

0

onStartCommand 意图:

如果服务在其进程消失后重新启动,并且它之前返回了除 START_STICKY_COMPATIBILITY 之外的任何内容,则这可能为 null。

http://developer.android.com/reference/android/app/Service.html

所以尝试使用:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);

而不是finish();

于 2013-06-10T06:26:09.900 回答