在android服务中使用处理程序时出现问题

时间:2016-04-09 15:14:43

标签: java android android-service android-handler linegraph

我是android的新手并试图了解android服务。我正在制作有关更新Temperature上的Line Graph读数的教程。

以下是我的服务代码

    public class Temperature extends Service {
    private static final String TAG = "HelloService";
    private static final int PROCESS_SENSOR_DATA_ON_UI = 801;
    private boolean isRunning  = false;
    public static ArrayList<Float> tempValueC=new ArrayList<Float>();
    private Handler mUiHandler2;

    @Override
    public void onCreate() {
        Log.i(TAG, "Service onCreate");
        isRunning = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(TAG, "Service onStartCommand");
        new Thread(new Runnable() {
        @Override
        public void run() {
            mUiHandler2 = new Handler(new UiHandlerCallback2());}
            class UiHandlerCallback2 implements Handler.Callback {

                @Override
                public boolean handleMessage(Message msg) {
                    switch (msg.what) {
                        case COMPLETE_INIT:

                            break;
                        case PROCESS_EVENT_DEVICE_UNSUPPORTED:
                            Toast.makeText(getApplicationContext(), R.string.error_unsupported_device,
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case PROCESS_CONNECTION_STATE_CHANGE_UI:
                            //updateConnectionStateWidgets();
                            break;
                        case PROCESS_BATTERY_STATUS_UI:
                            //   updateBatteryLevelWidget(msg.arg1);
                            break;

                        case PROCESS_SENSOR_DATA_ON_UI:
                            processSensorData((byte[]) msg.obj);
                             break;
                    }
                    return true;
                }
             private void processSensorData(byte[] sensorData) {
             //code for temperature update
            }
         }
    }


    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "Service onBind");
        return null;
    }

我收到如下错误:

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

UiHandlerCallback2检查是否有任何消息。

我在创建处理程序mUiHandler2 = new Handler(new UiHandlerCallback2());

时收到错误

我想知道我哪里出错了。我仍然从基础开始,所以任何一种帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

查看Otto。它是一个可以轻松地在应用程序组件之间发送数据的库。

http://square.github.io/otto/