medo medo - 5 months ago 53
Android Question

Can't create handler inside thread that has not called Looper prepare

public class MyCustomService extends Service {

private WindowManager windowManager;
private ImageView chatHead;
WindowManager.LayoutParams params;
private static Context mContext;



IBinder mBinder = new LocalBinder();

public static Socket client;


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

public class LocalBinder extends Binder {
public MyCustomService getServerInstance() {
return MyCustomService.this;
}
}




// Fires when a service is first initialized
public void onCreate() {
super.onCreate();
this.mContext = this;

windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);



}


// Fires when a service is started up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {


IO.Options opts = new IO.Options();
opts.query = "auth_token=51";
try {
client = IO.socket("http://192.168.0.106:3000/",opts);
client.on("message", onMessage);

client.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}



return START_STICKY;
}



@Override
public void onDestroy() {

client.disconnect();
client.close();
if (chatHead != null) windowManager.removeView(chatHead);
}


public void addView()
{
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

chatHead = new ImageView(mContext);
chatHead.setImageResource(R.drawable.android_head);

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);

params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;

windowManager.addView(chatHead, params);
}


private Emitter.Listener onMessage = new Emitter.Listener() {
@Override
public void call(Object... args) {

addView();

}
};

}


i want to make ALERT WINDOW from service when i call function

addView


form
onCreat
of service its work without any error

but when i want call it from another function its

onMessage


this function called when i emit new data to socket so i just want to make the


Alert Window


when i got message from socket but its give an error if i call function
addView


form
onMessage
function
and the error its


Can't create handler inside thread that has not called Looper.prepare()


but if i call it from

onCreate


of service its work

Answer

public void call(Object... args) is not called from UI thread. You can do that via Handler.

Handler mHandler = new Handler(Looper.getMainLooper());
...
...
...
private Emitter.Listener onMessage = new Emitter.Listener() {

   @Override
   public void call(Object... args) {

      mHandler.post(new Runnable(){

         @Override
         public void run (){
         addView();
         }
     });
};