我有一个服务。我使用WindowManager在服务运行时显示一些UI。同时,在此服务的生命周期内,我也会显示通知。
下面是我的Service类:
public class DemoService extends Service implements View.OnClickListener {
private static final int mLayoutParamFlags = WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
// Views
private View mDemoView;
private ImageButton mEndButton
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
mDemoView = layoutInflater.inflate(R.layout.windowmanager_demo, null);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
mLayoutParamFlags,
PixelFormat.TRANSLUCENT);
mEndButton = (Button) view.findViewById(R.id.end_button);
mEndButton.setOnClickListener(this);
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(mDemoView, params);
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove notification
stopForeground(true);
// Remove WindowManager
if(mDemoView != null){
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.removeView(mDemoView);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.end_button:
endService();
break;
}
}
/**
* Show notification
*/
private void showNotification() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.demoicon)
.setContentTitle("Demo App")
.setContentText("Demo Message");
startForeground(R.string.demo_string, notificationBuilder.build());
}
private void endService() {
// Stop demo service
stopSelf();
}
以下是我想实现但不知道如何实现的事情:
- 当服务正在运行且WindowManager的UI可见时,如果我按下硬件返回/主页键,则WindowManager的UI应该消失,同时服务应继续运行。我不知道如何在服务中捕获返回键。
- 当我点击通知时,WindowManager的UI应该变为可见状态。