使用ScheduledExecutorService延时关闭一个全屏的对话框

自定义style,设置全屏属性

<resources>  
  
    <style name="AppTheme" parent="android:Theme.Black"/>  
    <style name="processDialog" >  
        <item name="android:windowIsFloating">true</item><!--是否浮现在activity之上-->   
        <item name="android:windowFullscreen">true</item>    
        <item name="android:windowIsTranslucent">false</item><!--半透明-->    
        <item name="android:windowNoTitle">true</item><!--无标题-->    
        <item name="android:windowBackground">@android:color/transparent</item><!--背景透明-->    
        <item name="android:backgroundDimEnabled">true</item><!--模糊-->    
        <item name="android:backgroundDimAmount">0.5</item>   
        <item name="android:alpha">0.3</item>   
    </style>    
  
</resources>

代码中加载这个view并把viewset到dialog上,这样全屏的dialog就完成了

mView = LayoutInflater.from(this).inflate(R.layout.process_dialog, null);  
processDialog = new Dialog(context, R.style.processDialog);  
processDialog.setCancelable(false);
processDialog.setContentView(mView);  
mAutoCloseDialog = new AutoCloseDialog(processDialog);
mAutoCloseDialog.show(Prefs.DIALOG_DISPLAY_TIME);

接下来用一个封装好的类,做一个延时关闭的效果

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Dialog;

public class AutoCloseDialog{  
    
    private Dialog dialog;  
    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();  
      
    public AutoCloseDialog(Dialog dialog){  
        this.dialog = dialog;  
    }  
      
    public void show(long duration){  
    	
        Runnable runner = new Runnable() {  
            public void run() {  
                dialog.dismiss();  
            }  
        };  
        executor.schedule(runner, duration, TimeUnit.MILLISECONDS);
        dialog.show();
    }  
      
}

其他用法示例:

HereisaclasswithamethodthatsetsupaScheduledExecutorServicetobeepeverytensecondsforanhour:

import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }

ScheduledExecutorService执行周期性或定时任务

相关推荐