本文目录
本篇文章简单实现了如何在Service里面弹出Dialog。
1 创建AlertDialog
public void showDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppTheme));
builder.setTitle("设置标题"); //设置标题
builder.setMessage("设置内容"); //设置内容
builder.setIcon(R.mipmap.ic_launcher);//设置图标,图片id即可
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //关闭dialog
//编写确定后的操作...
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//编写取消后的操作...
}
});
builder.setNeutralButton("忽略", new DialogInterface.OnClickListener() {//设置忽略按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//编写忽略后的操作...
}
});
//参数都设置完成了,创建并显示出来
final AlertDialog dialog = builder.create();
// 将dialog类型设置为系统的弹窗
// 8.0系统加强后台管理,禁止在其他应用和窗口弹提醒弹窗,如果需要弹窗,必须使用TYPE_APPLICATION_OVERLAY
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY );
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
dialog.show();
}
2 注意事项
- 需要在创建的时候,给dialog添加Theme,否则程序执行会报错。
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppTheme));
- 需要设置窗口属性,8.0以上设置为TYPE_APPLICATION_OVERLAY,8.0以下设置为TYPE_TOAST。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY );
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
- 需要增加权限。
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
3 代码
public class TestService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static final String CHANNEL_ID_STRING = "id";
public static final String CHANNEL_NAME_STRING = "name";
private Notification notification;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//适配8.0service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(CHANNEL_ID_STRING, CHANNEL_NAME_STRING, NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(mChannel);
notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
startForeground(1, notification);
}
//其他初始化操作...
showDialog();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
public void showDialog(){
// ...
}
}
如何启动服务,可以详见本系列其他文章。