Android 在线程内创建处理程序到服务中

1 android android-service

我正在编写简单的 android 服务,我想使用诸如ToastorNotification但我收到此错误:

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

我不能用runOnUiThread。我的服务不知道。例如,我尝试将其用于 : this, getBaseContect(), getApplication, mContextfor.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();
                }
            });

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

esh*_*yne 5

尝试在 onStartCommand 中创建一个处理程序(因此,从 UI 线程)。然后使用该处理程序触发 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(...);
        }
    });
Run Code Online (Sandbox Code Playgroud)