【发布时间】:2017-02-13 01:03:50
【问题描述】:
当我单击屏幕上的按钮或按下返回按钮时,我编写了活动(由服务调用)来制作弹出窗口并完成活动和服务。这是代码。
服务:
public class AlarmService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent popupIntent = new Intent(AlarmService.this, AlarmPopup.class);
popupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(popupIntent);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
活动:
public class AlarmPopup extends AppCompatActivity {
PopupWindow popup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
onShowPopup();
}
};
handler.postDelayed(r, 500);
}
public void onShowPopup() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alarm_popup, null);
popup = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, true);
popup.setBackgroundDrawable(new BitmapDrawable());
popup.showAtLocation(view, Gravity.CENTER, 0, 0);
view.findViewById(R.id.button).setOnClickListener(mClickListener);
}
Button.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(AlarmPopup.this, AlarmService.class);
stopService(i);
popup.dismiss();
finish();
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(AlarmPopup.this, AlarmService.class);
stopService(i);
popup.dismiss();
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
当我按下屏幕上的按钮时,一切都像我预期的那样顺利。但是当我按下后退按钮时,它只会关闭弹出窗口,并且服务和活动还没有完成。当我再次单击返回按钮时,服务和活动已完成,但我想通过一键完成所有这些。
我也试过这个而不是 onKeydown(),
@Override
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(AlarmPopup.this, AlarmService.class);
stopService(i);
popup.dismiss();
finish();
}
但它也不起作用。在这种情况下我需要做什么?
哦,还有一件事。日志“W/InputEventReceiver:已尝试完成输入事件,但输入事件接收器已被释放。”当我点击后退按钮时打印。这是造成这个问题的原因吗?
【问题讨论】:
标签: android android-activity service back-button