Android: 服务 Class 没有 onCreate() 方法

Android: Service Class without onCreate() method

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

这是来自服务 class 的相关代码:

@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 中声明服务实例的方式:

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

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

编辑: 这是来自扩展 class Service[=40 的 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() 方法感到困惑。

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

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