我创建的这个IntentService将在onStartCommand()和onDestroy()中显示Toasts,但不在onHandleIntent()中显示。我错过了一些关于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!
}
}
答案 0 :(得分:65)
接受的答案不正确。
以下是您如何通过onHandleIntent()
展示吐司:
public class DisplayToast implements Runnable {
private final Context mContext;
String mText;
public DisplayToast(Context mContext, String text){
this.mContext = mContext;
mText = text;
}
public void run(){
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
在服务的构造函数中实例化Handler
,并使用post
对象调用DisplayToast
方法。
public class MyService extends IntentService {
Handler mHandler;
public MyService(){
super("MyService");
mHandler = new Handler();
}
@Override
protected void onHandleIntent(Intent intent) {
mHandler.post(new DisplayToast(this, "Hello World!"));
}
}
答案 1 :(得分:23)
你应该在主线程上启动Toast:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
这是因为否则IntentService的线程在吐出之前退出,导致IllegalStateException:
java.lang.IllegalStateException:Handler(android.os.Handler){12345678}在死线程上向处理程序发送消息
答案 2 :(得分:19)
onHandleIntent()是从后台线程调用的(这就是IntentService的全部内容),所以你不应该从那里做UI。
答案 3 :(得分:2)
另一个选项是RxJava,例如:
private void showToast(final String text) {
Observable.just(text)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
});
}
警告:我是Android的新手。