我在 android 应用程序中使用 HMS ML Kit 来分析来自后台服务的人脸检测。我无法初始化 MLFaceAnalyzer。下面是服务类代码片段
@Suppress("未使用") 类 TestService : Service() {
private val TAG: String = "FaceDetectionPresenterHw"
private var faceDetectionPresenterhw: FaceDetectionPresenterHw? = null
private var isNotificationCalled = false
private fun createNotification() {
isNotificationCalled = true
val notificationIntent = Intent(this, MyActivity::class.java)
notificationIntent.putExtra(Constants.INTENT_EXTRA_TYPE, "Background Service")
notificationIntent.putExtra(Constants.INTENT_EXTRA_CHILD_ID, childId)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT)
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = getString(R.string.default_notification_channel_id)
val channelName = getString(R.string.channel_name)// The user-visible name of the channel.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(
channelId, channelName, importance
)
mChannel.setSound(null, null)
mChannel.enableVibration(false)
notificationManager.createNotificationChannel(mChannel)
}
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(“MyApp”)
.setDefaults(0)
.setContentText("MyApp is running")
.setContentIntent(pendingIntent).build()
startForeground(1337, notification)
}
override fun onCreate() {
super.onCreate()
if (!isNotificationCalled) {
createNotification()
}
faceDetectionPresenterhw = FaceDetectionPresenterHw(this@TestService)
}
@SuppressLint("MissingPermission")
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG,"Service started")
if (!isNotificationCalled) {
createNotification()
}
if (Utils.permissionCheck(this@TestService)) {
faceDetectionPresenterhw!!.startCamera()
} else {
stopSelf()
}
return START_STICKY
}
override fun onDestroy() {
isNotificationCalled = false
isDestroyCalled = true
faceDetectionPresenterhw!!.stopCamera()
super.onDestroy()
}
override fun onBind(intent: Intent): IBinder? {
return null
}
}
FaceDetectionPresenter 类代码片段如下
class FaceDetectionPresenterHw(private val context: Context) : FaceDetectionInterface, KoinComponent {
private var cameraConfiguration: CameraConfiguration? = null
private var lensEngine: LensEngine? = null
private var preview: LensEnginePreview? = null
init {
faceDetectorCreate(false)
}
override fun faceDetectorCreate(orientation: Boolean) {
Log.d(TAG, "faceDetectorCreate()")
cameraConfiguration = CameraConfiguration()
createCameraSource()
}
private fun createCameraSource() {
if (lensEngine == null) {
Log.d(TAG, "createCameraSource() ${context ==null} ${cameraConfiguration ==null} ")
lensEngine = LensEngine(context, this.cameraConfiguration)
}
setDetectorOptions()
}
private fun setDetectorOptions() {
Log.d(TAG, "Option 1")
val options: MLFaceAnalyzerSetting = MLFaceAnalyzerSetting.Factory()
.setPerformanceType(MLFaceAnalyzerSetting.TYPE_SPEED)
.setFeatureType(MLFaceAnalyzerSetting.TYPE_FEATURES)
.setShapeType(MLFaceAnalyzerSetting.TYPE_SHAPES)
.setKeyPointType(MLFaceAnalyzerSetting.TYPE_KEYPOINTS)
.setTracingAllowed(true, MLFaceAnalyzerSetting.MODE_TRACING_FAST)
.allowTracing(MLFaceAnalyzerSetting.MODE_TRACING_FAST)
.create()
Log.d(TAG, "Option ${lensEngine != null} -- ${context==null} ")
lensEngine?.setMachineLearningFrameTransactor(LocalFaceTransactor(options, context))
}
override fun startCamera() {
Log.d(TAG, "Start Camera")
if (lensEngine != null) {
try {
Log.d(TAG, "Start Camera inside")
preview = LensEnginePreview(context)
preview!!.start(lensEngine, true)
} catch (e: IOException) {
Log.e("FaceDetectionPr", "Unable to start lensEngine.", e)
lensEngine!!.release()
lensEngine = null
}
}
}
private inner class LocalFaceTransactor(options: MLFaceAnalyzerSetting?, context: Context) : BaseTransactor<List<MLFace?>?>() {
init {
detector = MLAnalyzerFactory.getInstance().getFaceAnalyzer(options)
}
}
}
下面的问题来了
android.content.Context com.huawei.agconnect.AGConnectInstance.getContext()' on a null object reference
日志猫
2021-07-07 13:20:28.051 16868-16868/? E/AndroidRuntime: FATAL EXCEPTION: main
facedetection.FaceDetectionPresenterHw.(FaceDetectionPresenterHw.kt:43) 在 co.sample.services.sampleService.onCreate(sampleService.kt:81) 在 android.app.ActivityThread.handleCreateService(ActivityThread.java:4150) 在 android.app.ActivityThread。在 android.os.Handler.dispatchMessage(Handler.java:112) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2055) 在 android.os.Looper.loop( Looper.java:216) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run( RuntimeInit.java:524) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 2021-07-07 13:20:28.078 1486-7158/?I/chatty: uid=1000(system) Binder:1486_1D expire 1 line 2021-07-07 13:20:28.091 1486-6494/? 我/健谈:uid=1000(system) Binder:1486_1C expire 6 lines 2021-07-07 13:20:28.095 1915-4243/? I/BoosterSwitchP:notifyUidState 什么都不做 2021-07-07 13:20:28.095 1915-4243/? I/DeepNoDisturbP: notifyUidState 2021-07-07 13:20:28.095 1915-4243/? I/BrowserChrP: notifyUidState 2021-07-07 13:20:29.423 16932-16932/? D/ActivityThread:将线程附加到应用程序 2021-07-07 13:20:30.122 16932-16932/?E/AndroidRuntime:致命异常:主进程:co.sample:sampleService,PID:16932 java.lang.RuntimeException:无法创建服务 co.sample.services.sampleService:java.lang.NullPointerException:尝试调用虚拟方法'android .content.Context com.huawei.agconnect.AGConnectInstance.getContext()' 在 android.app.ActivityThread 的 android.app.ActivityThread.handleCreateService(ActivityThread.java:4169) 的空对象引用上。
这里有什么问题?