服务在后台监听蓝牙打印机的状态,当打印机异常(缺纸)时,弹出提示
使用 hanlder 传递 Toast
hanlder.post(new Runnable() {
@Override
public void run() {
Toast.makeText(DialogService.this, "打印机缺纸", 1).show();
}
});
Dialog的显示是需要依附于一个Activity,如果需要在 Servcie 中显示需要把 Dialog 设置成一个系统级 Dialog(TYPE_SYSTEM_ALERT),即全局性质的提示框.
在安卓8及以上版本,需要 使用 TYPE_APPLICATION_OVERLAY 权限才能在 后台 或者 其他窗口 弹出。
private Handler mHandler;
//在 Service 生命周期方法 onCreate() 中初始化 mHandler
mHandler = new Handler(Looper.getMainLooper());
//在子线程中想要 Toast 的地方添加如下
mHandler.post(new Runnable() {
@Override
public void run() {
//show dialog
justShowDialog();
}
});
private void justShowDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext())
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("service中弹出Dialog了")
.setMessage("是否关闭dialog?")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
//下面这行代码放到子线程中会 Can‘t create handler inside thread that has not called Looper.prepare()
AlertDialog dialog = builder.create();
//设置点击其他地方不可取消此 Dialog
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
//8.0系统加强后台管理,禁止在其他应用和窗口弹提醒弹窗,如果要弹,必须使用TYPE_APPLICATION_OVERLAY,否则弹不出
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
}else {
dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
}
dialog.show();
}
参考
https://www.jb51.net/article/172238.htm
错误 Can‘t create handler inside thread that has not called Looper.prepare()
new Thread(new Runnable() {
@Override
public void run() {
Looper.perpare();//增加部分
timer = new Timer(mTotalTime, TimeSetted.SECOND_TO_MILL);
timer.start();
Log.d(TAG,"Countdown start");
Looper.loop();//增加部分
}
}).start();
//版权声明:本文为CSDN博主「雷霆管理层」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
//原文链接:https://blog.csdn.net/weixin_42694582/article/details/81535083
原文:https://www.cnblogs.com/sinjin/p/14885431.html