当前位置: 移动技术网 > IT编程>移动开发>Android > Android Service中使用Toast无法正常显示问题的解决方法

Android Service中使用Toast无法正常显示问题的解决方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

67式重机枪,历届河南省委书记,3dmax不锈钢材质

本文实例讲述了android service中使用toast无法正常显示问题的解决方法。分享给大家供大家参考,具体如下:

在做service简单练习时,在service中的oncreate、onstart、ondestroy三个方法中都像在activity中同样的方法调用了toast.maketext,并在acitivy中通过两个按钮来调用该服务的onstart和ondestroy方法:

demoservice代码如下:

@override
public void oncreate()
{
    super.oncreate();
    toast.maketext(getapplicationcontext(), "service is created!", toast.length_long).show();
}
@override
public void onstart(intent intent,int startid)
{
    super.onstart(intent, startid);
    toast.maketext(getapplicationcontext(), "service is on!", toast.length_long).show();
}
@override
public void ondestroy(){
    super.ondestroy();
    toast.maketext(getapplicationcontext(), "service is off!", toast.length_long).show();
}

运行之后,demoservice中的信息都没有显示出来。

刚开始以为所得到的context不正确,在service直接调用getapplicationcontext()得到的是service的context,但是细究来看,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.”
(http://developer.android.com/guide/topics/ui/notifiers/toasts.html)

那么按照这句来看,service中创建的toast会在acivity的ui前面聚焦显示。但为什么运行没有效果呢?再来查看一下maketext方法。

果然还是context的问题,所以想要toast能够正常工作,需要在activity的主线程上运行才行,那么如何得到主线程ui的context呢?可以通过handler将一个自定义的线程运行于主线程之上。

再来看一下toast.show方法的src:

public void show() {
    ...
    service.enqueuetoast(pkg, tn, mduration);  //将该toast插入到一个消息队列中
    ...
}

原理上看,android中大致上是消息队列和消息循环,主线程从消息队列中取得消息并处理。而handler看作是一个工具类,用来向消息队列中插入消息。所以我们重构原来的代码:

@override
public void oncreate()
{
    super.oncreate();
    handler=new handler(looper.getmainlooper());
    handler.post(new runnable(){
      public void run(){
        toast.maketext(getapplicationcontext(), "service is created!", toast.length_long).show();
      }
    });
}
@override
public void onstart(intent intent,int startid)
{
    super.onstart(intent, startid);
    handler=new handler(looper.getmainlooper());
    handler.post(new runnable(){
      public void run(){
        toast.maketext(getapplicationcontext(), "service is on!", toast.length_long).show();
      }
    });
}
@override
public void ondestroy(){
    super.ondestroy();
    handler=new handler(looper.getmainlooper());
    handler.post(new runnable(){
      public void run(){
        toast.maketext(getapplicationcontext(), "service is off!", toast.length_long).show();
      }
    });
}

运行之后的效果如下:

总结:在android的framework中使用toast,要将toast添加到主线程里才能正常工作。

更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android视图view技巧总结》、《android编程之activity操作技巧总结》、《android操作sqlite数据库技巧总结》、《android操作json格式数据技巧总结》、《android数据库操作技巧总结》、《android文件操作技巧汇总》、《android编程开发之sd卡操作方法汇总》、《android资源操作技巧汇总》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网