简体   繁体   English

Android:不带onCreate()方法的服务类

[英]Android: Service Class without onCreate() method

I'm a beginner in Android Studio. 我是Android Studio的初学者。 I've recently picked up some Demo Apps for managing BLE devices, made them work separately, and am now trying to join two of them in a single App. 我最近挑选了一些用于管理BLE设备的演示应用程序,使它们可以单独工作,现在正尝试将其中的两个应用程序合并到一个应用程序中。 Both Apps used a BLE Service, so I have to join them into a single service (or have them work together). 这两个应用程序都使用了BLE服务,因此我必须将它们加入一个服务中(或让它们一起工作)。 While looking at the code I noticed that one of these Service classes has no onCreate() method. 在查看代码时,我注意到这些Service类之一没有onCreate()方法。 Then I looked into the implementation and found the Service is Instantiated using a nested class of the Service that extends the Binder class. 然后,我研究了实现,并使用扩展Binder类的Service的嵌套类实例化了Service

Here's the relevant code from the service 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...
...
}

And this is how the Service instance gets declared in the Activity that uses it: 这是在使用它的Activity中声明Service实例的方式:

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

I am trying to understand: how exactly is the Class instantiated without the onCreate() method? 我试图理解:如果没有onCreate()方法,如何精确地实例化Class? I've checked the onCreate() method from the Service class and it just throws and exception. 我已经检查了Service类中的onCreate()方法,它只是抛出异常。 I need to understand it because the other service I'm using does have such method and I want to join them. 我需要了解它,因为我正在使用的其他服务确实具有这种方法,并且我想加入它们。 Also: What is the difference between using this LocalBinder nested class and straight up using a class constructor? 另外:使用此LocalBinder嵌套类和直接使用类构造函数有什么区别?

EDIT: Here's the onCreate() method from the extended class Service . 编辑:这是来自扩展类ServiceonCreate()方法。 You can see it just throws a Runtime Exception. 您可以看到它只会引发运行时异常。 onStart() is identical. 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: As Gabe pointed out in his answer: This is just the stub code from the Service, not the actual implementation. EDIT2:正如Gabe在他的回答中指出的:这仅仅是Service中的存根代码,而不是实际的实现。 So I got confused by the onCreate() method that Android Studio showed me. 因此,我对Android Studio向我展示的onCreate()方法感到困惑。

There's a default implementation of onCreate in the Service class. Service类中有onCreate的默认实现。 If you don't override it, you just use that default implementation. 如果不覆盖它,则只使用该默认实现。 That's sufficient to create the Service correctly, if you don't need additional logic. 如果您不需要其他逻辑,则足以正确创建服务。

Your other question should be asked separately (1 question per post), but there's not enough code for me to answer it- I have no idea what the variable service is. 您的其他问题应单独提出(每个帖子一个问题),但是没有足够的代码让我回答—我不知道变量服务是什么。 However, you never create a service via constructor- it will not be initialized properly. 但是,您永远不会通过构造函数创建服务-该服务不会正确初始化。 You always call startService or bindService and let Android create it. 您总是调用startService或bindService并让Android创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM