参考网址:https://blog.youkuaiyun.com/cqx13763055264/article/details/79179731
在Service中使用Toast
private Handler handlerToast = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
Toast.makeText(getApplicationContext(), "显示的内容!",Toast.LENGTH_SHORT).show();
break;
}
}
};
注意:getApplicationContext()使用Toast时要使用全局的Context,如果在Activity中有公共方法可供使用,写法如下
public void showToast(String text){
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
这样是显示不出来的,必须使用的是全局的Context
本文介绍了在Android Service中正确使用Toast的方法。通常,在Service中直接使用Toast会遇到显示问题,因为Service没有界面。解决方法是使用Handler并通过getApplicationContext()获取全局Context来发送消息,从而实现在Service中显示Toast。
377

被折叠的 条评论
为什么被折叠?



