Intentserviceからトーストを作成する方法は?画面に貼り付けられます
-
08-10-2019 - |
質問
Intentserviceにトーストメッセージを表示させようとしていますが、Onhandleintentメッセージから送信すると、トーストが表示されますが、画面が立ち往生して去りませんでした。 Onhandleintentメソッドがメインサービススレッドでは発生しないため、どうすれば動かすことができますか?
誰かがこの問題を抱えていて、それを解決しましたか?
解決
の onCreate()
初期化a Handler
そして、あなたのスレッドからそれに投稿します。
private class DisplayToast implements Runnable{
String mText;
public DisplayToast(String text){
mText = text;
}
public void run(){
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
protected void onHandleIntent(Intent intent){
...
mHandler.post(new DisplayToast("did something"));
}
他のヒント
これが私を助けたトーストを示す完全なIntentserviceクラスコードです:
package mypackage;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
public class MyService extends IntentService {
public MyService() { super("MyService"); }
public void showToast(String message) {
final String msg = message;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onHandleIntent(Intent intent) {
showToast("MyService is handling intent.");
}
}
ハンドルを使用して、操作をコンテンツする実行可能なものを投稿してください
protected void onHandleIntent(Intent intent){
Handler handler=new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
public void run(){
//your operation...
Toast.makeText(getApplicationContext(), "hello world", Toast.LENGTH_SHORT).show();
}
});
所属していません StackOverflow