service 後臺彈出提示
阿新 • • 發佈:2021-06-15
場景
服務在後臺監聽藍芽印表機的狀態,當印表機異常(缺紙)時,彈出提示
彈出 Toast
使用 hanlder 傳遞 Toast
hanlder.post(new Runnable() {
@Override
public void run() {
Toast.makeText(DialogService.this, "印表機缺紙", 1).show();
}
});
彈出 Dialog
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