Search code examples
androidserviceuploadbroadcastreceiverhttpserver

Android Service :upload image to a http server


I'm trying to upload image from my android phone to a http server, in a service. Well i have a brodcastreceiver in an activity ,and every time there is data ,it send it to the service to do the upload. But ,my code just do only one upload (i cheks it in the server ) then crashes (withote any error message ).

I hope someone can tell me the reason of the crash ,and thank you in advance.

PS:my doubts are in the Looper.prepare(); and Looper.loop(); i'm not very familiar to them ,even after reading about them.

This my onStartCommand of my Service :

     public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getBaseContext(), "Service started 2", Toast.LENGTH_LONG).show();
        int rssi1 = intent.getIntExtra("key1", 0);
        int rssi2 = intent.getIntExtra("key2", 0);
        int rssi3 = intent.getIntExtra("key3", 0);
        Toast.makeText(getBaseContext(), "Service started 2" + rssi1 +" "+ rssi2 + " " + rssi3, Toast.LENGTH_LONG).show();

         Toast.makeText(getBaseContext(), "Service Appel 2", Toast.LENGTH_LONG).show();
            upLoadServerUri = "http://192.168.1.150:8080/UploadToServer.php";
            mContext = getApplicationContext();
          folder = new File("/storage/sdcard");
          new Thread(new Runnable()
            {
                @Override
                public void run() 
                {   Looper.prepare();
                    imagepath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile1.jpg";
                    uploadFile(imagepath);

                }
            }).start();
          Looper.loop();
        return START_STICKY;
    }

Solution

  • You don't need to call the Looper.prepare(); and Looper.loop();. You can use AsyncTask to do the upload task in a worker thread. Like this:

    class UploadTask extends AsyncTask<String, Object, Object> {
    
        @Override
        protected Object doInBackground(String... content) {
            uploadFile(content[0]);
            return null;
        }
    }
    

    And in the service:

    public int onStartCommand(Intent intent, int flags, int startId) {
        imagepath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile1.jpg";
        new UploadTask().execute(imagepath, null, null);
    }
    

    PS: You can refer to this to get yourself familiar with Looper and Handler stuff.