在Service中弹出Toast和Dialog

时间:2021-11-08 10:55:20

众所周知,Toast必须在UI主线程上才能正常显示,而在Service中是无法获得Acivity的Context的,在service中想显示出Toast只需将show的消息发送给主线程Looper就可以了

Handler handler = new Handler(Looper.getMainLooper());
			handler.post(new Runnable() {
				public void run() {
					Toast.makeText(getApplicationContext(), "存Service is runing!",
							Toast.LENGTH_SHORT).show();
				}
			});

此时便可显示Toast


Dialog的用法与此类似,但是要多加个权限

在manifest中添加此权限以弹出dialog

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

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) {

								}
							});
			final AlertDialog dialog = builder.create();
			dialog.getWindow().setType(
					(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
			Handler handler = new Handler(Looper.getMainLooper());
			handler.post(new Runnable() {
				public void run() {
					dialog.show();
				}
			});