java - Android:没有 onCreate() 方法的服务类

标签 java android service instantiation oncreate

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

以下是服务类的相关代码:

@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...
...
}

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

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!");
}

}

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

最佳答案

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

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

关于java - Android:没有 onCreate() 方法的服务类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185472/

相关文章:

android - 项目包含错误但未在源代码 Android 中显示

Java TCP连接

php - 检测服务器过载以限制 mysql 查询

android - Android 中 Service、Web 和 Activity 之间的来回通信

java - 使用Hadoop 3.0.0-alpha2无法正确添加/获取缓存文件

java - 计算中空三维几何物体的体积

java - 常量解释为 QueryDSL 中的表达式

android - 为什么 `TextInputLayout` 会使用样式颜色来绘制光标而不是下划线?

android - 应用程序关闭时线程是否会停止?

java - 如何调用内部类构造函数?