正文
1、使用startService()在服务的oncreate()方法中实现该方法即可 (前提是你开启了服务)
//全局对话框 为service打造
public void define_cancel_service(final Context context, final Class cls) {
// 加载布局文件
View view = View.inflate(context, R.layout.dialog_customize, null);
TextView text = (TextView) view.findViewById(R.id.text);
TextView confirm = (TextView) view.findViewById(R.id.confirm);
TextView cancel = (TextView) view.findViewById(R.id.cancel);
// 创建Dialog
final AlertDialog dialog = new AlertDialog.Builder(context).create();
dialog.setCancelable(false);// 设置点击dialog以外区域不取消Dialog
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
dialog.show();
dialog.setContentView(view);
//todo 设置上下位置
dialog.getWindow().setGravity(Gravity.TOP);
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.y = 500;
dialog.getWindow().setLayout(MobileHardwareDataUtils.getScreenAttribute(context, MobileHardwareDataUtils.ScreenAttribute.width) / 4 * 3,
WindowManager.LayoutParams.WRAP_CONTENT);//设置弹出框宽度为屏幕宽度的三分之二
// 确定
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
context.stopService(new Intent(context,cls));
Toast.makeText(context, "确定", Toast.LENGTH_SHORT).show();
}
});
// 取消
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
context.stopService(new Intent(context,cls));
}
});
}
关键代码
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
注意stopService()方法
2、使用startService()在服务的onStartCommand()方法中实现该方法即可 (前提是你开启了服务) 也可以实现