1

I have a little problem using a Service and an AsyncTask inside it. I've coded a little class that does some HTTP stuff, and it executes an AsyncTask to do all the HTTP work on background, and when it finishes it calls a listener with the response data.

Now I need to use that class inside a service (remote service), and everytime the class tries to create an object from the AsyncTask class it crashes with the following messages in the log cat:

05-07 10:30:01.847: E/JavaBinder(1026): *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
05-07 10:30:01.847: E/JavaBinder(1026): java.lang.ExceptionInInitializerError
05-07 10:30:01.847: E/JavaBinder(1026):     at com.lowlevel.umusic.VK.getById(VK.java:46)
05-07 10:30:01.847: E/JavaBinder(1026):     at com.lowlevel.umusic.Song.requestUri(Song.java:109)
05-07 10:30:01.847: E/JavaBinder(1026):     at com.lowlevel.umusic.PlayService$1.playSong(PlayService.java:149)
05-07 10:30:01.847: E/JavaBinder(1026):     at com.lowlevel.umusic.IPlayService$Stub.onTransact(IPlayService.java:55)
05-07 10:30:01.847: E/JavaBinder(1026):     at android.os.Binder.execTransact(Binder.java:320)
05-07 10:30:01.847: E/JavaBinder(1026):     at dalvik.system.NativeStart.run(Native Method)
05-07 10:30:01.847: E/JavaBinder(1026): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-07 10:30:01.847: E/JavaBinder(1026):     at android.os.Handler.<init>(Handler.java:121)
05-07 10:30:01.847: E/JavaBinder(1026):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
05-07 10:30:01.847: E/JavaBinder(1026):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
05-07 10:30:01.847: E/JavaBinder(1026):     at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
05-07 10:30:01.847: E/JavaBinder(1026):     ... 6 more
05-07 10:30:01.847: W/dalvikvm(1026): threadid=8: thread exiting with uncaught exception (group=0x40015560)
05-07 10:30:01.847: E/AndroidRuntime(1026): FATAL EXCEPTION: Binder Thread #2
05-07 10:30:01.847: E/AndroidRuntime(1026): java.lang.ExceptionInInitializerError
05-07 10:30:01.847: E/AndroidRuntime(1026):     at com.lowlevel.umusic.VK.getById(VK.java:46)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at com.lowlevel.umusic.Song.requestUri(Song.java:109)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at com.lowlevel.umusic.PlayService$1.playSong(PlayService.java:149)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at com.lowlevel.umusic.IPlayService$Stub.onTransact(IPlayService.java:55)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at android.os.Binder.execTransact(Binder.java:320)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at dalvik.system.NativeStart.run(Native Method)
05-07 10:30:01.847: E/AndroidRuntime(1026): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-07 10:30:01.847: E/AndroidRuntime(1026):     at android.os.Handler.<init>(Handler.java:121)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
05-07 10:30:01.847: E/AndroidRuntime(1026):     at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
05-07 10:30:01.847: E/AndroidRuntime(1026):     ... 6 more

Any ideas or I'll have to modify my class to work synchronously?

Thanks!

Miguel Botón
  • 766
  • 5
  • 20
  • I can put some code, but I don't think it's necessary. Just imagine the most simple AsyncTask, a simple remote service, and the service (in the interface functions) trying to create a new instance of the AsyncTask. It crashes at that point. – Miguel Botón May 07 '12 at 11:38
  • there can be lot of reasons to crash application on that particular event, so if we have code then easily we can get the faulted point. – Sandeep May 07 '12 at 11:42
  • Found the answer here: http://stackoverflow.com/questions/2750664/is-it-possible-to-use-asynctask-in-a-service-class AsyncTask cannot be used in remote services. – Miguel Botón May 07 '12 at 12:01
  • what you found in there..there's clear written..its can be done..absolutely..by CW – MKJParekh May 07 '12 at 14:20

2 Answers2

1

I answer my own question hoping it can help other people that is experimenting the same problem and finds this message.

AsyncTask CAN be used in a service but it can NOT be used inside the stub. As simple as that.

There are several ways to get them working if you need to call them from the stub:

1. Example code:

public class MyService extends Service {
    private static final int MSG_CALLTASK = 0;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_CALLTASK:
                new MyAsyncTask().execute();
                break;
            }
        }
    };

    private IMyService.Stub mStub = new IMyService.Stub = {
        public void myFunction() {
            /* Call task */
            mHandler.sendMessage(mHandler.obtainMessage(MSG_CALLTASK));
        }
    };

    [...]
}

2. The second way is to avoid calling methods from the stub and just send an intent to the service and parse it in 'onStartCommand' method (it will be called when the intent is sent).

I hope this is helpful!

Miguel Botón
  • 766
  • 5
  • 20
0
public class LoginService_Service extends Service {
    NotificationManager mNM;
    static String stcode="";

    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        new DoLogin().execute(null);
    }
    @Override
    public void onDestroy() {
        mNM.cancel(R.string.notify_cancel);
        Log.i("Finish", "OnDestroy Called");
    }

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

    private final IBinder mBinder = new Binder() {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply,
                int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };
    public class DoLogin extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams
                    .setConnectionTimeout(client.getParams(), 10000); // Timeout
            try {
                HttpPost request = new HttpPost(
                        "myurl");
                JSONStringer jsonstr = new JSONStringer().object().key(
                "UserName").value(prefs.getString("unm", "")).key(
                "Password").value(prefs.getString("pwd", ""))
                .endObject();

                Log.i("JSONStringer", jsonstr.toString());
                StringEntity entity = new StringEntity(jsonstr.toString());
                entity.setContentType("application/json;charset=UTF-8");// text/plain;charset=UTF-8
                entity
                        .setContentEncoding(new BasicHeader(
                                HTTP.CONTENT_TYPE,
                                "application/json;charset=UTF-8"));
                request.setEntity(entity);
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse res = httpClient.execute(request);
                Log.i("Request", request.toString());
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Error", "Cannot Estabilish Connection");
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (stcode != null) {
                if (stcode.equalsIgnoreCase("0")) {
                    Log.i("ReLogin", "ReLogin Success");
                } else {
                    Log.i("ReLogin", "ReLogin Failed");
                }
            }
            LoginService_Service.this.stopSelf();
        }

    }
}
MKJParekh
  • 34,073
  • 11
  • 87
  • 98