将远程服务绑定到线程

时间:2013-04-15 15:52:17

标签: java android service

我可以将远程服务绑定到我在另一个远程服务中创建的线程吗?

当我尝试使用bindService(Intent, ServiceConnection, int)时,Eclipse显示错误:

The method bindService(Intent, AcquisitionThread.GPSServiceConnection, int) is undefined for the type AcquisitionThread

如果你需要,这是我的课程:

public class AcquisitionThread extends Thread {
private static final int VALUES_FROM_THREAD = 1;
private static final int SLEEP_ACQUISITION = 50;
private BluetoothDevice _dev = null;
private BluetoothSocket _sock = null;
private String rawData = null;
private String myText;
private int currentPosition;
private boolean moveLeft;
private AtomicBoolean isMonitoringThread = new AtomicBoolean();
private AtomicBoolean stopMonitoringThread = new AtomicBoolean();

private InputStream inBluetooth;
private OutputStream outBluetooth;
private IMyGPSService GPSService;
private GPSServiceConnection conn = null;

Message messageToMainService = new Message();
Bundle messageData = new Bundle();
Timer timer;

// reference to mainHandler from the mainThread
private Handler mainServiceHandler;

private Handler myThreadHandler = new Handler() {
    public void handleMessage(Message msg) {
        if (msg.what == 0) {
            isMonitoringThread.set(true);
            stopMonitoringThread.set(false);
        }
        if (msg.what == 1) {
            isMonitoringThread.set(false);
            stopMonitoringThread.set(true);
        }
    }
};

//constructor
public AcquisitionThread(Handler serviceHandler,InputStream inBt, OutputStream outBt) {
    // initialize instance vars
    this.mainServiceHandler = serviceHandler;
    this.inBluetooth = inBt;
    this.outBluetooth = outBt;
    isMonitoringThread.set(false);
    stopMonitoringThread.set(false);
}

@Override
public void run() {
    super.run();
    bindGPSService();
    double rpmCalcule = -1;
    double consoCalcule = -1;
    double consoInstantCalcule = -1;
    long totalTime = 0;
    float moyTime;
    int nbIteration = 50;
    try {
        // Thread loop
        while (!stopMonitoringThread.get()) {
            // prepare a message with the updated text              
            if (isMonitoringThread.get()) {
                // // Faire un traitement
                // Thread.sleep(100);
                long startTime = SystemClock.elapsedRealtime();
                write("00f0041"); // Requête au PGN 61444, pour RPM
                try {
                    readResult(inBluetooth);
                    rpmCalcule = calcRpm(rawData);
                    Log.d("rpmCalcule", String.valueOf(rpmCalcule));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                write("00fef21"); // Requête au PGN 65266 pour consommation Fuel
                try {
                    readResult(inBluetooth);
                    consoCalcule = calcConso(rawData);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                long ellapseTime = SystemClock.elapsedRealtime() - startTime + SLEEP_ACQUISITION;
                Log.d("TimeEllapsed", String.valueOf(ellapseTime));

                // send message to mainThread

                messageToMainService.what = VALUES_FROM_THREAD;

                messageData.putDouble("consoValue", consoCalcule);
                messageData.putDouble("rpmValue", rpmCalcule);

                messageData.putLong("timerBoucle", ellapseTime);
                messageToMainService.setData(messageData);
                Log.d("messageData", String.valueOf(messageData));
                mainServiceHandler.dispatchMessage(messageToMainService);


                // update currentPosition value for moving text 
                // ternary if form used
                //                  if (moveLeft)
                //                      currentPosition = (currentPosition == myText
                //                              .length()) ? 0
                //                              : currentPosition + 1;
                //                  else
                //                      currentPosition = (currentPosition == 0) ? myText
                //                              .length()
                //                              : currentPosition - 1;
                //
                //                  sleep(100);
                Thread.sleep(SLEEP_ACQUISITION);
            } else {
                Log.d("Thread while if", "else");
                Thread.sleep(500);
            }
        }
    } catch (Exception e) {
        // Logging exception
        Log.e("TestingAreaLOG", "Erreur, acquisition impossible (clé non connectée?)");
    }
}

// getter for local Handler
public Handler getHandler() {
    return myThreadHandler;
}

// updates the text based on the currentPosition
private String updateText(String text) {
    return text.substring(currentPosition) + text.substring(0, currentPosition);
}

public void write(String cmd) {

    cmd += "\r";
    try {
        outBluetooth.write(cmd.getBytes());
        outBluetooth.flush();
         try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
        // } catch (InterruptedException e) {
        // e.printStackTrace();
    }
}

protected void readResult(InputStream in) throws IOException {

    // Log.d("LECTURE",in.toString());
    byte b = 0;
    StringBuilder res = new StringBuilder();
    timer = new Timer(true);
    // read until '>' arrives
    while ((char) (b = (byte) in.read()) != '>')
        if ((char) b != ' ')
            res.append((char) b);
    // timer.get

    rawData = res.toString().trim();
    // Log.d("RAWDATA",rawData);
}

private double calcRpm(String frame) {
    double rpmFloat = -1;
    String rpm1 = frame.substring(6, 8); // On récupère les digits 7 et 8, qui forment le byte 4
    String rpm2 = frame.substring(8, 10); // On récupère les bytes 9 et 10, qui forment le byte 5
    String rpm = rpm2 + rpm1;
    if (isHex(rpm) == true) {
        BigInteger bi = new BigInteger(rpm, 16);
        rpmFloat = bi.doubleValue() / 8;
    }
    return rpmFloat;
}

private double calcConso(String frame) {
    double consoFloat = -1;
    String conso1 = frame.substring(0, 2); // On récupère les digits 1 et 2, qui forment le byte 1
    String conso2 = frame.substring(2, 4); // On récupère les bytes 3 et 4, qui forment le byte 2
    String conso = conso1 + conso2;
    Log.d("CONSO_BYTES", conso);
    if (isHex(conso) == true) {
        BigInteger bi = new BigInteger(conso, 16);
        consoFloat = bi.doubleValue() / 20;
    }
    return consoFloat;
}

private double calcConsoInstant(String frame) {
    double consoInstantFloat = -1;
    String conso1 = frame.substring(4, 6); // On récupère les digits 5 et 6, qui forment le byte 3
    String conso2 = frame.substring(6, 8); // On récupère les bytes 7 et 8, qui forment le byte 4
    String conso = conso1 + conso2;
    Log.d("CONSO_INSTANT_BYTES", conso);
    if (isHex(conso) == true) {
        BigInteger bi = new BigInteger(conso, 16);
        consoInstantFloat = bi.doubleValue() / 512;
    }
    return consoInstantFloat;
}

private static boolean isHex(String s) {
    return s.matches("[0-9a-fA-F]+");
}

class GPSServiceConnection implements ServiceConnection {
    public void onServiceConnected(ComponentName className,
            IBinder boundService) {
        GPSService = IMyGPSService.Stub.asInterface((IBinder) boundService);
        Log.d(getClass().getSimpleName(), "onServiceConnected()");
    }

    public void onServiceDisconnected(ComponentName className) {
        GPSService = null;
        Log.d(getClass().getSimpleName(), "onServiceDisconnected");
    }
};

private void bindGPSService() {
    if (conn == null) {
        conn = new GPSServiceConnection();
        Intent i = new Intent();
        i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.GPSService");
        bindService(i, conn, Context.BIND_AUTO_CREATE);
        Log.d(getClass().getSimpleName(), "bindService()");
    } else {
        Log.d("ONBIND", "conn non null");
    }
}

private void releaseGPSService() {
    if (conn != null) {
        unbindService(conn);
        conn = null;
        Log.d(getClass().getSimpleName(), "releaseService()");
    }
}

}

我在bindService and unbindService

上收到错误

我还添加了这个文本,因为StackOverFlow发现与“详细信息”相比代码太多了。

2 个答案:

答案 0 :(得分:0)

在您的班级AcquisitionThread中,您没有定义/声明两个方法

bindService(i, conn, Context.BIND_AUTO_CREATE);

 unbindService(conn);

但您仍然在调用GPSServiceConnection#bindGPSService()GPSServiceConnection#releaseGPSService()方法

编辑: 解决方案是在AcquisitionThreadGPSServiceConnection

中声明这些方法

(您可以使用Eclipse功能,CTRL + 1快速建议您的源代码中的错误)

答案 1 :(得分:0)

好像你无法将远程服务绑定到线程,但这没关系。

事实上,在我的情况下,我可以将远程服务GPS绑定到创建AcquisitionThreah的远程服务BlueTooth。

绑定2个服务使线程可以访问GPS远程服务中需要的方法。

如果您需要更明确的解释,请问我,如果没有人阅读,我不想写所有内容; - )

相关问题