为了账号安全,请及时绑定邮箱和手机立即绑定

从第二个活动绑定到服务

从第二个活动绑定到服务

暮色呼如 2021-10-06 10:53:21
我的理解是可以同时从多个活动绑定到同一个服务。但是,当我尝试从除 MainActivity.java 之外的第二个活动绑定到服务时,我遇到了一个反复出现的问题,从那里我用 startService 启动了服务。在这里,我尝试从我的新活动 (SensorDataDisplay.java) 绑定到服务 (BluetoothLeService.java)。这个服务最初是在我的 MainActivity.java 活动中启动的,然后绑定在 MainActivity 中。我已经编写了一些代码来检查绑定是否成功,并且它不断返回 false。从第二个活动绑定时,是否需要做一些不同的事情?SensorDataDisplay.java(第二个活动)package com.august.customtisensortagclient;import android.bluetooth.BluetoothGatt;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.IBinder;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.TextView;public class SensorDataDisplay extends AppCompatActivity {    private static final String TAG = "SensorDataDisplay";    TextView tester;    BluetoothLeServiceForLeft mBluetoothLeServiceForLeft;    boolean mBoundLeft = false;    BluetoothLeServiceForRight mBluetoothLeServiceForRight;    boolean mBoundRight;    BluetoothGatt bluetoothGattLeft;    BluetoothGatt bluetoothGattRight;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_sensor_data_display);        Intent intent = getIntent(); //From MainActivity.java        String value = intent.getStringExtra("key");//if it's a string you stored.        // Checker code (to see if successful bind)        tester = (TextView) findViewById(R.id.textView2);        tester.append(value);        }    };}BluetoothLeServiceForLeft.java(请原谅长度。我只是想包括这个以防有人想验证我对 LocalBinder 方法的使用。
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

由于您mBoundLeft在onCreate()方法内部进行测试并绑定服务onStart()并取消绑定onStop()(如果您的应用程序被终止,您也不会保存瞬态状态),您将永远不会看到是否mBoundLeft为真(检查活动生命周期)。您应该测试服务是否已在内部绑定onServiceConnected(),例如使用log.d. 你应该做这样的事情:


public void onServiceConnected(ComponentName className, IBinder service) {

    // Because we have bound to an explicit

    // service that is running in our own process, we can

    // cast its IBinder to a concrete class and directly access it.

    BluetoothLeServiceForLeft.LocalBinder binder = 

             (BluetoothLeServiceForLeft.LocalBinder) service;

    mBluetoothLeServiceForLeft = binder.getService();

    mBoundLeft = true;

    Log.d("ServiceConnection", "Service is connected");

}

我建议您学习Log在 Android 中使用类进行调试,它在 Android 开发中更好(并且是标准)。


查看完整回答
反对 回复 2021-10-06
  • 1 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信