IntentService不会显示吐司吐司、IntentService

2023-09-07 04:51:31 作者:瘾与深巷

此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.