作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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();
}
};
}
我想从服务中创建警报窗口。当我调用函数addView
时来自onCreate
服务的方法工作正常,没有任何错误。
onMessage
当我向套接字发送新数据时调用方法。所以我只想在从套接字收到消息时显示警报窗口,但如果我调用函数 addView
,它会给我一个错误来自onMessage
功能:
Can't create handler inside thread that has not called Looper.prepare()
但是如果我从 onCreate
调用它服务的工作方法。
最佳答案
public void call(Object... args)
不是从 UI 线程调用的。您可以通过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();
}
});
};
关于java - 无法在未调用 Looper 准备的线程内创建处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38087638/
我是一名优秀的程序员,十分优秀!