2013-02-25 187 views
0

我正在处理我的IntentService,其中我在循环中生成值。在覆盖方法onStartCommand()onDestroy()中,可以使用Toast来显示消息。我想在onHandleIntent()中也使用Toast,但它不起作用。我知道有更好的方法(文件,属性等)来显示值,但是我在创建它们时立即需要这些值。不是最后(只有控制权,如果它正常工作)。请,你能帮我找出问题吗?提前致谢。如何从onHandleIntent(Android)获取信息

public class HelloIntentService extends IntentService { 

    public HelloIntentService() { 
     super("HelloIntentService"); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 
     return super.onStartCommand(intent,flags,startId); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

     long endTime = System.currentTimeMillis() + 5*1000; 
     while (System.currentTimeMillis() < endTime) { 
      synchronized (this) { 
       try { 
        wait(endTime - System.currentTimeMillis()); 
       } catch (Exception e) { 
       } 
      } 
     }} 

    @Override 
    public void onDestroy() 
    { 
     Toast.makeText(this, "Service is being destroyed now.", Toast.LENGTH_SHORT).show(); 
    } 
} 
+0

PLZ添加IntentService代码也 – 2013-02-25 23:07:28

+1

试图表明举杯为:'Toast.makeText(getApplicationContext(),“服务启动”,Toast.LENGTH_SHORT ).show();' – 2013-02-25 23:14:40

+0

它的工作原理。我发现只有当我把'Toast'放到onHandleIntent的代码中时才会出现这个问题。谢谢 – Tom11 2013-02-25 23:23:01

回答

0

onHandleIntent运行在每the source code后台一个单独的线程,因此没有任何更新UI的能力。我会建议使用记录语句,而不是祝酒词来显示你的信息:

Log.d("HelloIntentService","service starting");