我们一般在Activity里面使用Toast和Dialog,使用比较简单,这里就不用讲了。有时候需要在服务里面使用Toast和Dialog,但是不知道怎么引入上下文Context ,下面介绍另种方式使用Toast和Dialog。
1. Toast在Service中使用 ,直接上代码
Handler handlerThree=new Handler(Looper.getMainLooper());
handlerThree.post(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext() ,"显示Toast在屏幕上!",Toast.LENGTH_LONG).show();
}
});
Toast应该得到主UI的Context才能显示,Google对Toast的说明中,有一句:“A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service,it appears in front of the Activity currently in focus.”
那么按照这句来看,service中创建的toast会在Acivity的UI前面聚焦显示。所以想要toast能够正常工作,需要在Activity的主线程上运行才行,那么如何得到主线程UI的Context呢?可以通过Handler将一个自定义的线程运行于主线程之上。
2. Dialog在Service中使用 ,直接上代码
Builder builder = new AlertDialog.Builder(getApplicationContext())
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("service中弹出Dialog了")
.setMessage("是否关闭dialog?")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
final AlertDialog dialog = builder.create();
dialog.getWindow().setType(
(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
dialog.show();
}
});
跟上面的Toast一样,在Service中使用Handler将Dialog运行在主UI线程上。