IntentService不会显示吐司

IntentService不会显示吐司

本文介绍了IntentService不会显示吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此IntentService我创建将显示干杯在onStartCommand()和在的onDestroy(),但不是在onHandleIntent()。我失去了一些有关的IntentService的限制?

 公共类的MyService延伸IntentService {

私有静态最后字符串变量=为MyService;

公共则将MyService(){
    超(为MyService);
}

@覆盖
保护无效onHandleIntent(意向意图){
    周期();
}

@覆盖
公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
    Toast.makeText(这一点,服务启动,Toast.LENGTH_SHORT).show(); //出现这种情况!
    返回super.onStartCommand(意向,标志,startId);
}

@覆盖
公共无效的onCreate(){
    super.onCreate();

}

@覆盖
公共无效的onDestroy(){
    Toast.makeText(这一点,停止服务,Toast.LENGTH_SHORT).show(); //出现这种情况!
    super.onDestroy();
}

私人无效周期(){
      Toast.makeText(这一点,周期做,Toast.LENGTH_SHORT).show(); //这不会发生!
      Log.d(TAG,周期完成); //出现这种情况!
}
}
 

解决方案

onHandleIntent()从后台线程调用(这就是IntentService是所有关于),所以你不应该在那里做UI。

This IntentService I created will show Toasts in onStartCommand() and in onDestroy(), but not in onHandleIntent(). Am I missing something about the limitations of an IntentService?

public class MyService extends IntentService {

private static final String TAG = "MyService";

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

@Override
protected void onHandleIntent(Intent intent) {
    cycle();
}

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

@Override
public void onCreate() {
    super.onCreate();

}

@Override
public void onDestroy() {
    Toast.makeText(this, "service stopping", Toast.LENGTH_SHORT).show(); //This happens!
    super.onDestroy();
}

private void cycle(){
      Toast.makeText(this, "cycle done", Toast.LENGTH_SHORT).show();  //This DOESN'T happen!
      Log.d(TAG,"cycle completed"); //This happens!
}
}
解决方案

onHandleIntent() is called from a background thread (that is what IntentService is all about), so you shouldn't do UI from there.

这篇关于IntentService不会显示吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 23:46