Android在线程内部创建处理程序到Service

时间:2014-09-29 11:58:15

标签: android android-service

我正在编写简单的Android服务,我想使用ToastNotification,但我收到此错误:

 FATAL EXCEPTION: Thread-17116
    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我无法使用runOnUiThread。我的服务不知道。例如,我尝试将其用于:thisgetBaseContect()getApplicationmContext .runOnUiThread(new Runnable() {}

我遇到问题,我无法解决问题。

这是我的代码:

public class TsmsService extends Service {

    private Timer smsThread;
    private DatabaseHandler db;
    private SQLiteDatabase dbHelper;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        smsThread = new Timer();
        GetSMSThread getSMSThread = new GetSMSThread(getBaseContext());
        smsThread.scheduleAtFixedRate(getSMSThread, 0, 1000); //(timertask,delay,period)
        return super.onStartCommand(intent, flags, startId);
    }

    public class GetSMSThread extends TimerTask {
        private Context mContext;

        public GetSMSThread(Context context) {
            mContext = context;
        }

        @Override
        public void run() {

            this.runOnUiThread(new  Runnable() {
                public  void  run() {
                    Toast.makeText(getApplication() , "Service is Running ... " , Toast.LENGTH_SHORT).show();
                }
            });

        }
    }
}

2 个答案:

答案 0 :(得分:4)

尝试在onStartCommand中创建一个Handler(因此,从UI线程)。然后使用该Handler触发Toast。例如:

private Handler mToastHandler = null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ...
    mToastHandler = new Handler();
    ...
}

...

    // from inside your child thread
    mToastHandler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(...);
        }
    });

答案 1 :(得分:1)

在这里,您可以使用ResultReceiver用于接收某人的回调结果。在你的情况下是Service

您可以查看complete example of Service with TimerTask using ResultReceiver以更新活动

中的用户界面