【发布时间】:2019-08-13 05:05:44
【问题描述】:
嘿,我正在开发提醒服务应用程序。我想在应用程序后台服务通知我时显示弹出窗口。在不干扰我的应用程序活动或打开活动显示弹出窗口的情况下,我可以取消/关闭弹出窗口。
不幸的是,我尝试了很多方法,但我无法执行此事件以显示非 Activity 类的对话框。现在我的代码没有任何错误。这是我发起视图的吐司。它显示消息等待前台,但我不想打开活动并显示弹出窗口。我怎么能做到这一点,请帮帮我。我在这里发布我的服务代码。
public class StartAlaramService extends Service {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mParams;
private View mRootView;
private Context mContext = null;
private LayoutInflater mInflater = null;
private View alertView = null;
@Override
public void onCreate() {
super.onCreate();
mContext=this;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try{
if (null != mWindowManager) {
if (null != alertView) {
mWindowManager.removeView(alertView);
}
mWindowManager = null;
mParams = null;
mInflater = null;
alertView = null;
}
} catch (Exception ex){
ex.printStackTrace();
Log.e("SERVICE ", " Code Error");
}
showView();
return StartAlaramService.START_NOT_STICKY;
}
private void initState() {
Log.e("SERVICE ", "Intiate View State");
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
LAYOUT_FLAG,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
if (null == mWindowManager) {
mWindowManager = ((WindowManager) mContext.getSystemService(WINDOW_SERVICE));
}
}
private void showView() {
try{
initState();
// Create the view
mRootView = initView();
// Show the view
mWindowManager.addView(mRootView, mParams);
// Do some extra stuff when the view's ready
} catch (Exception ex){
ex.printStackTrace();
Log.e("SERVICE ", " EXCEPTION " + ex.getMessage());
}
}
private View initView() {
mInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mWindowManager = (WindowManager) mContext.getSystemService(WINDOW_SERVICE);
LayoutInflater li = LayoutInflater.from(mContext);
setTheme(R.style.custom_dialog);
alertView = li.inflate(R.layout.custom_layout_notification, null);
return alertView;
}
}
SYSTEM ALERT PERMISSION 已在 Manifest 中定义。
【问题讨论】:
-
最好的办法是使用 ForegroundService 并显示通知而不是弹出窗口。
-
我该怎么做,你能提供一些参考。我不想打开活动并显示弹出窗口或对话框窗口是否可能?
-
您可以尝试一种 hack 方法,使活动看起来像一个具有透明背景和内容的对话框并启动它
-
恐怕我觉得不可能
-
当然......但我仍然有一些问题,对话框会在一段时间后自动关闭......完成后我会发布代码。
标签: android android-service android-alertdialog