【问题标题】:Android: Service Class without onCreate() methodAndroid:没有 onCreate() 方法的服务类
【发布时间】:2019-07-24 14:37:29
【问题描述】:

我是 Android Studio 的初学者。我最近挑选了一些用于管理 BLE 设备的演示应用程序,让它们单独工作,现在我正试图将其中两个加入到一个应用程序中。两个应用程序都使用了 BLE 服务,所以我必须将它们加入一个服务中(或者让它们一起工作)。 在查看代码时,我注意到其中一个 Service 类没有 onCreate() 方法。然后我查看了实现,发现服务是使用 Service 的嵌套类实例化的,该类扩展了 Binder 类。

这是服务类的相关代码:

@SuppressLint("NewApi")
public class BluetoothLeService extends Service {
private final String TAG = BluetoothLeService.class.getSimpleName();

private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private BluetoothGattCharacteristic mNotifyCharacteristic;

private static EncryptDecode encryptDecode = new EncryptDecode(); // Encryption and Decryption tool task
private IBleOperateCallback mBleOperateCallback;

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            mBleOperateCallback.bleData(SmctConstant.KEY_BLE_CONNECT_STATE, SmctConstant.VALUE_BLE_CONNECTED);

            Log.i(TAG, "Connected to GATT server.");
            mBluetoothGatt.discoverServices();

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            mBleOperateCallback.bleData(SmctConstant.KEY_BLE_CONNECT_STATE, SmctConstant.VALUE_BLE_DISCONNECTED);
            close();

            Log.i(TAG, "Disconnected from GATT server.");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            mBleOperateCallback.bleData(SmctConstant.KEY_BLE_CONNECT_STATE,
                    SmctConstant.VALUE_BLE_SERVICE_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

};
public class LocalBinder extends Binder {
    public BluetoothLeService getService() {
        return BluetoothLeService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    close();
    return super.onUnbind(intent);
}

private final IBinder mBinder = new LocalBinder();

/**
 * Initializes a reference to the local Bluetooth adapter.
 *
 * @return Return true if the initialization is successful.
 */
public boolean initialize() {
    // For API level 18 and above, get a reference to BluetoothAdapter
    // through
    // BluetoothManager.
    if (mBluetoothManager == null) {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Log.e(TAG, "Unable to initialize BluetoothManager.");
            return false;
        }
    }

    mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        return false;
    }

    return true;
}
...
SOME MORE FUNCTIONS...
...
}

这就是在使用它的 Activity 中声明 Service 实例的方式:

BluetoothLeService mBluetoothLeService;
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();

我试图理解:在没有 onCreate() 方法的情况下,类究竟是如何实例化的?我检查了 Service 类中的 onCreate() 方法,它只是抛出异常。我需要了解它,因为我正在使用的其他服务确实有这样的方法,我想加入它们。 另外:使用这个 LocalBinder 嵌套类和直接使用类构造函数有什么区别?

编辑:这是扩展类 Service 中的 onCreate() 方法。你可以看到它只是抛出了一个运行时异常。 onStart() 是相同的。

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package android.app;

import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
import java.io.FileDescriptor;
import java.io.PrintWriter;

public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
public static final int START_CONTINUATION_MASK = 15;
public static final int START_FLAG_REDELIVERY = 1;
public static final int START_FLAG_RETRY = 2;
public static final int START_NOT_STICKY = 2;
public static final int START_REDELIVER_INTENT = 3;
public static final int START_STICKY = 1;
public static final int START_STICKY_COMPATIBILITY = 0;
public static final int STOP_FOREGROUND_DETACH = 2;
public static final int STOP_FOREGROUND_REMOVE = 1;

public Service() {
    super((Context)null);
    throw new RuntimeException("Stub!");
}

public final Application getApplication() {
    throw new RuntimeException("Stub!");
}

public void onCreate() {
    throw new RuntimeException("Stub!");
}

/** @deprecated */
@Deprecated
public void onStart(Intent intent, int startId) {
    throw new RuntimeException("Stub!");
}

public int onStartCommand(Intent intent, int flags, int startId) {
    throw new RuntimeException("Stub!");
}

public void onDestroy() {
    throw new RuntimeException("Stub!");
}

public void onConfigurationChanged(Configuration newConfig) {
    throw new RuntimeException("Stub!");
}

public void onLowMemory() {
    throw new RuntimeException("Stub!");
}

public void onTrimMemory(int level) {
    throw new RuntimeException("Stub!");
}

public abstract IBinder onBind(Intent var1);

public boolean onUnbind(Intent intent) {
    throw new RuntimeException("Stub!");
}

public void onRebind(Intent intent) {
    throw new RuntimeException("Stub!");
}

public void onTaskRemoved(Intent rootIntent) {
    throw new RuntimeException("Stub!");
}

public final void stopSelf() {
    throw new RuntimeException("Stub!");
}

public final void stopSelf(int startId) {
    throw new RuntimeException("Stub!");
}

public final boolean stopSelfResult(int startId) {
    throw new RuntimeException("Stub!");
}

public final void startForeground(int id, Notification notification) {
    throw new RuntimeException("Stub!");
}

public final void stopForeground(boolean removeNotification) {
    throw new RuntimeException("Stub!");
}

public final void stopForeground(int flags) {
    throw new RuntimeException("Stub!");
}

protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
    throw new RuntimeException("Stub!");
}

}

EDIT2: 正如 Gabe 在他的回答中指出的那样:这只是来自服务的存根代码,而不是实际的实现。所以我对 Android Studio 向我展示的 onCreate() 方法感到困惑。

【问题讨论】:

    标签: java android service instantiation oncreate


    【解决方案1】:

    Service 类中有 onCreate 的默认实现。如果您不覆盖它,则只需使用该默认实现。如果您不需要额外的逻辑,这足以正确创建服务。

    您的其他问题应单独提出(每个帖子 1 个问题),但没有足够的代码让我回答 - 我不知道可变服务是什么。但是,您永远不会通过构造函数创建服务——它不会被正确初始化。您总是调用 startService 或 bindService 并让 Android 创建它。

    【讨论】:

    • 请查看我的编辑:Service 类上 onCreate() 的默认实现只会引发运行时异常。这不会是实例化的问题吗?
    • @ManuSisko 这不是真正的实现。您没有查看实际的 Android 源代码。 Google for AOSP Service 源代码,找到真正的代码。
    • 这是当我在服务扩展类上使用“转到 -> 声明”时显示的服务类。我已经复制了整个代码。我用谷歌搜索了你指出的那个,它显示一个空的 onCreate() ,所以这比我拥有的更有意义。你知道为什么 Android Studio 会打开这个版本的 Service 类吗?
    • 因为它不知道实际的代码(并且对于每种设备型号和操作系统更新版本都会有所不同)。所以它链接到存根实现。不要相信它显示的任何框架代码。
    • 非常感谢!所以我想实例是在调用 Binder .getService() 方法时创建的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多