I have an IntentService running in my app. I want to stop when user presses a cancel button, but onHandleIntent keeps running, even when onDestroy (IntentService) was called.
I tried stopSelf() in the middle of execution, stopSelf(int) and stopService(intent), but doesn't work.
class DownloadIntentService : IntentService("DownloadIntentService") {
val TAG: String = "DownloadIntentService"
val AVAILABLE_QUALITIES: Array<Int> = Array(5){240; 360; 480; 720; 1080}
// TODO Configurations
val PREFERED_LANGUAGE = "esLA"
val PREFERED_QUALITY = AVAILABLE_QUALITIES[0]
#Inject
lateinit var getVilosDataInteractor: GetVilosInteractor
#Inject
lateinit var getM3U8Interactor: GetM3U8Interactor
#Inject
lateinit var downloadDataSource: DownloadsRoomDataSource
companion object {
var startedId: Int = 0
}
override fun onCreate() {
super.onCreate()
(application as CrunchApplication).component.inject(this)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "onStartComand ${startId}")
startedId = startId
super.onStartCommand(intent, flags, startId)
return Service.START_NOT_STICKY
}
override fun onHandleIntent(intent: Intent?) {
Log.d(TAG, "starting download service")
val download = downloadDataSource.getDownloadById(intent?.getLongExtra(MEDIA_ID_EXTRA, 0) ?: 0)
Log.d(TAG, "A new download was found: ${download.id} ${download.serieName} ${download.collectionName} ${download.episodeName}")
val vilosResponse = getVilosDataInteractor(download.episodeUrl)
val stream: StreamData? = vilosResponse.streams.filter {
it.hardsubLang?.equals(PREFERED_LANGUAGE) ?: false
}.getOrNull(0)
if(stream == null) {
Log.d(TAG, "Stream not found with prefered language ($PREFERED_LANGUAGE)")
return
}
Log.d(TAG, "Best stream option: " + stream.url)
val m3u8Response = getM3U8Interactor(stream.url)
val m3u8Data: M3U8Data? = m3u8Response.playlist.filter { it.height == PREFERED_QUALITY }[0]
if(m3u8Data == null) {
Log.d("M3U8","Resolution ${PREFERED_QUALITY}p not found")
return
}
Log.d(TAG, m3u8Data.url)
val root = Environment.getExternalStorageDirectory().toString()
val myDir = File(root + "/episodes/");
if (!myDir.exists()) {
myDir.mkdirs()
}
val output = myDir.getAbsolutePath() + "EPISODENAME.mp4";
val cmd = "-y -i ${m3u8Data.url} ${output}"
when (val result: Int = FFmpeg.execute(cmd)) {
Config.RETURN_CODE_SUCCESS -> Log.d(TAG, "Success")
Config.RETURN_CODE_CANCEL -> Log.d(TAG, "Cancel")
else -> Log.d(TAG, "Default: $result")
}
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy")
}
}
I try to stop from a Fragment
val intent = Intent(requireContext(), DownloadIntentService::class.java)
requireContext().stopService(intent)
Thanks in advance
Basically you can not. OnHandleIntent run on worker thread. To stop it you have to do same thing which one can do with any another Thread i.e. have a boolean flag check inside onHandleIntent and before doing operation check of this flag is true. Now when you want to cancel update the flag to false.
It also depends on what you are doing. IF something is already in process tat will keep on running. Not you have to have state machine to make it stop.
Related
I'm trying to make an application for wearable in which I get various metrics from health services such as the heart rate for different sports. However I get the following error:: lateinit property healthServicesManager has not been initialized.
I have declared the lateinit as:
#Inject
lateinit var healthServicesManager: HealthServicesManagerTaekwondo
The complete code of the class:
#AndroidEntryPoint
class ExerciseServiceTaekwondo : LifecycleService() {
#Inject
lateinit var healthServicesManager: HealthServicesManagerTaekwondo
private val localBinder = LocalBinder()
private var isBound = false
private var isStarted = false
private var isForeground = false
private val _exerciseState = MutableStateFlow(ExerciseState.USER_ENDED)
val exerciseState: StateFlow<ExerciseState> = _exerciseState
private val _exerciseMetrics = MutableStateFlow(emptyMap<DataType, List<DataPoint>>())
val exerciseMetrics: StateFlow<Map<DataType, List<DataPoint>>> = _exerciseMetrics
private val _aggregateMetrics = MutableStateFlow(emptyMap<DataType, AggregateDataPoint>())
val aggregateMetrics: StateFlow<Map<DataType, AggregateDataPoint>> = _aggregateMetrics
private val _exerciseLaps = MutableStateFlow(0)
val exerciseLaps: StateFlow<Int> = _exerciseLaps
private val _exerciseDurationUpdate = MutableStateFlow(ActiveDurationUpdate())
val exerciseDurationUpdate: StateFlow<ActiveDurationUpdate> = _exerciseDurationUpdate
private val _locationAvailabilityState = MutableStateFlow(LocationAvailability.UNKNOWN)
val locationAvailabilityState: StateFlow<LocationAvailability> = _locationAvailabilityState
fun prepareExercise() {
lifecycleScope.launch {
healthServicesManager.prepareExercise()
}
}
fun startExercise() {
lifecycleScope.launch {
healthServicesManager.startExercise()
}
postOngoingActivityNotification()
}
fun pauseExercise() {
lifecycleScope.launch {
healthServicesManager.pauseExercise()
}
}
fun resumeExercise() {
lifecycleScope.launch {
healthServicesManager.resumeExercise()
}
}
/**
* End exercise in this service's coroutine context.
*/
fun endExercise() {
lifecycleScope.launch {
healthServicesManager.endExercise()
}
removeOngoingActivityNotification()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
Log.d(TAG, "onStartCommand")
if (!isStarted) {
isStarted = true
if (!isBound) {
// We may have been restarted by the system. Manage our lifetime accordingly.
stopSelfIfNotRunning()
}
// Start collecting exercise information. We might stop shortly (see above), in which
// case launchWhenStarted takes care of canceling this coroutine.
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
healthServicesManager.exerciseUpdateFlow.collect {
when (it) {
is ExerciseMessage.ExerciseUpdateMessage ->
processExerciseUpdate(it.exerciseUpdate)
is ExerciseMessage.LapSummaryMessage ->
_exerciseLaps.value = it.lapSummary.lapCount
is ExerciseMessage.LocationAvailabilityMessage ->
_locationAvailabilityState.value = it.locationAvailability
}
}
}
}
}
}
// If our process is stopped, we might have an active exercise. We want the system to
// recreate our service so that we can present the ongoing notification in that case.
return Service.START_STICKY
}
private fun stopSelfIfNotRunning() {
lifecycleScope.launch {
// We may have been restarted by the system. Check for an ongoing exercise.
if (!healthServicesManager.isExerciseInProgress()) {
// Need to cancel [prepareExercise()] to prevent battery drain.
if (_exerciseState.value == ExerciseState.PREPARING) {
lifecycleScope.launch {
healthServicesManager.endExercise()
}
}
// We have nothing to do, so we can stop.
stopSelf()
}
}
}
private fun processExerciseUpdate(exerciseUpdate: ExerciseUpdate) {
val oldState = _exerciseState.value
if (!oldState.isEnded && exerciseUpdate.state.isEnded) {
// Our exercise ended. Gracefully handle this termination be doing the following:
// TODO Save partial workout state, show workout summary, and let the user know why the exercise was ended.
// Dismiss any ongoing activity notification.
removeOngoingActivityNotification()
// Custom flow for the possible states captured by the isEnded boolean
when (exerciseUpdate.state) {
ExerciseState.TERMINATED -> {
// TODO Send the user a notification (another app ended their workout)
Log.i(
TAG,
"Your exercise was terminated because another app started tracking an exercise"
)
}
ExerciseState.AUTO_ENDED -> {
// TODO Send the user a notification
Log.i(
TAG,
"Your exercise was auto ended because there were no registered listeners"
)
}
ExerciseState.AUTO_ENDED_PERMISSION_LOST -> {
// TODO Send the user a notification
Log.w(
TAG,
"Your exercise was auto ended because it lost the required permissions"
)
}
else -> {
}
}
} else if (oldState.isEnded && exerciseUpdate.state == ExerciseState.ACTIVE) {
// Reset laps.
_exerciseLaps.value = 0
}
_exerciseState.value = exerciseUpdate.state
_exerciseMetrics.value = exerciseUpdate.latestMetrics
_aggregateMetrics.value = exerciseUpdate.latestAggregateMetrics
_exerciseDurationUpdate.value =
ActiveDurationUpdate(exerciseUpdate.activeDuration, Instant.now())
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
handleBind()
return localBinder
}
override fun onRebind(intent: Intent?) {
super.onRebind(intent)
handleBind()
}
private fun handleBind() {
if (!isBound) {
isBound = true
// Start ourself. This will begin collecting exercise state if we aren't already.
startService(Intent(this, this::class.java))
}
}
override fun onUnbind(intent: Intent?): Boolean {
isBound = false
lifecycleScope.launch {
// Client can unbind because it went through a configuration change, in which case it
// will be recreated and bind again shortly. Wait a few seconds, and if still not bound,
// manage our lifetime accordingly.
delay(UNBIND_DELAY_MILLIS)
if (!isBound) {
stopSelfIfNotRunning()
}
}
// Allow clients to re-bind. We will be informed of this in onRebind().
return true
}
private fun removeOngoingActivityNotification() {
if (isForeground) {
Log.d(TAG, "Removing ongoing activity notification")
isForeground = false
stopForeground(true)
}
}
private fun postOngoingActivityNotification() {
if (!isForeground) {
isForeground = true
Log.d(TAG, "Posting ongoing activity notification")
createNotificationChannel()
startForeground(NOTIFICATION_ID, buildNotification())
}
}
private fun createNotificationChannel() {
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL,
NOTIFICATION_CHANNEL_DISPLAY,
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
private fun buildNotification(): Notification {
// Make an intent that will take the user straight to the exercise UI.
val pendingIntent = NavDeepLinkBuilder(this)
.setGraph(R.navigation.nav_graph)
.setDestination(R.id.exerciseFragment)
.createPendingIntent()
// Build the notification.
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL)
.setContentTitle(NOTIFICATION_TITLE)
.setContentText(NOTIFICATION_TEXT)
.setSmallIcon(R.drawable.ic_run)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setCategory(NotificationCompat.CATEGORY_WORKOUT)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
// Ongoing Activity allows an ongoing Notification to appear on additional surfaces in the
// Wear OS user interface, so that users can stay more engaged with long running tasks.
val lastUpdate = exerciseDurationUpdate.value
val duration = lastUpdate.duration + Duration.between(lastUpdate.timestamp, Instant.now())
val startMillis = SystemClock.elapsedRealtime() - duration.toMillis()
val ongoingActivityStatus = Status.Builder()
.addTemplate(ONGOING_STATUS_TEMPLATE)
.addPart("duration", Status.StopwatchPart(startMillis))
.build()
val ongoingActivity =
OngoingActivity.Builder(applicationContext, NOTIFICATION_ID, notificationBuilder)
.setAnimatedIcon(R.drawable.ic_run)
.setStaticIcon(R.drawable.ic_run)
.setTouchIntent(pendingIntent)
.setStatus(ongoingActivityStatus)
.build()
ongoingActivity.apply(applicationContext)
return notificationBuilder.build()
}
/** Local clients will use this to access the service. */
inner class LocalBinder : Binder() {
fun getService() = this#ExerciseServiceTaekwondo
}
companion object {
private const val NOTIFICATION_ID = 1
private const val NOTIFICATION_CHANNEL = "com.example.exercise.ONGOING_EXERCISE"
private const val NOTIFICATION_CHANNEL_DISPLAY = "Ongoing Exercise"
private const val NOTIFICATION_TITLE = "Exercise Sample"
private const val NOTIFICATION_TEXT = "Ongoing Exercise"
private const val ONGOING_STATUS_TEMPLATE = "Ongoing Exercise #duration#"
private const val UNBIND_DELAY_MILLIS = 3_000L
fun bindService(context: Context, serviceConnection: ServiceConnection) {
val serviceIntent = Intent(context, ExerciseServiceTaekwondo::class.java)
context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
}
fun unbindService(context: Context, serviceConnection: ServiceConnection) {
context.unbindService(serviceConnection)
}
}
}
So I have an Android Job which handle network request.
This job can started in many ways, so it can run easily parralel, which is bad for me.
I would like to achive that, the job don't started twice, or if it started, than wait before the try catch block, until the first finishes.
So how can I to reach that, just only one object be/run at the same time.
I tried add TAG and setUpdateCurrent false, but it didn't do anything, so when I started twice the job, it rung parallel. After that I tried mutex lock, and unlock. But it did the same thing.
With mutex, I should have to create an atomic mutex, and call lock by uniq tag or uuid?
Ok, so I figured it out what is the problem with my mutex, the job create a new mutex object every time, so it never be the same, and it never will wait.
My Job:
class SendCertificatesJob #Inject constructor(
private val sendSync: SendSync,
private val sharedPreferences: SharedPreferences,
private val userLogger: UserLogger,
private val healthCheckApi: HealthCheckApi
) : Job(), CoroutineScope {
override val coroutineContext: CoroutineContext
get() = Dispatchers.IO
private val countDownLatch = CountDownLatch(1)
private val mutex = Mutex()
override fun onRunJob(params: Params): Result {
var jobResult = Result.SUCCESS
if (!CommonUtils.isApiEnabled(context))
return jobResult
val notificationHelper = NotificationHelper(context)
var nb: NotificationCompat.Builder? = null
if (!params.isPeriodic) {
nb = notificationHelper.defaultNotificationBuilder.apply {
setContentTitle(context.resources.getString(R.string.sending_certificates))
.setTicker(context.resources.getString(R.string.sending_certificates))
.setOngoing(true)
.setProgress(0, 0, true)
.setSmallIcon(android.R.drawable.stat_notify_sync)
.setLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher
)
)
}
notificationHelper.notify(NOTIFICATION_ID, nb)
jobCallback?.jobStart()
}
val failureCount = params.failureCount
if (failureCount >= 3) {
nb?.setOngoing(false)
?.setContentTitle(context.resources.getString(R.string.sending_certificates_failed))
?.setTicker(context.resources.getString(R.string.sending_certificates_failed))
?.setProgress(100, 100, false)
?.setSmallIcon(android.R.drawable.stat_sys_warning)
notificationHelper.notify(NOTIFICATION_ID, nb)
return Result.FAILURE
}
GlobalScope.launch(Dispatchers.IO) {
mutex.lock()
userLogger.writeLogToFile("SendCertificatesJob.onRunJob(), date:" + Calendar.getInstance().time)
try {
//Test
var doIt = true
var count =0
while (doIt){
Timber.d("SendSyncWorker: $count")
count++
delay(10000)
if(count == 12)
doIt = false
}
healthCheckApi.checkHealth(ApiModule.API_KEY).await()
try {
sendSync.syncRecordedClients()
} catch (e: Exception) {
e.printStackTrace()
}
val result = sendSync().forEachParallel2()
result.firstOrNull { it.second != null }?.let { throw Exception(it.second) }
val sb = StringBuilder()
if (nb != null) {
nb.setOngoing(false)
.setContentTitle(context.resources.getString(R.string.sending_certificates_succeeded))
.setTicker(context.resources.getString(R.string.sending_certificates_succeeded))
.setProgress(100, 100, false)
.setStyle(NotificationCompat.BigTextStyle().bigText(sb.toString()))
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
notificationHelper.notify(NOTIFICATION_ID, nb)
jobCallback?.jobEnd()
}
sharedPreferences.edit().putLong(KEY_LATEST_CERTIFICATES_SEND_DATE, Date().time)
.apply()
} catch (e: Exception) {
Timber.tag(TAG).e(e)
if (nb != null) {
nb.setOngoing(false)
.setContentTitle(context.resources.getString(R.string.sending_certificates_failed))
.setTicker(context.resources.getString(R.string.sending_certificates_failed))
.setProgress(100, 100, false)
.setSmallIcon(android.R.drawable.stat_sys_warning)
notificationHelper.notify(NOTIFICATION_ID, nb)
jobCallback?.jobEnd()
}
jobResult = Result.RESCHEDULE
} finally {
countDownLatch.countDown()
mutex.unlock()
}
}
countDownLatch.await()
return jobResult
}
Job schedule:
fun scheduleNowAsync(_jobCallback: JobCallback? = null) {
jobCallback = _jobCallback
JobRequest.Builder(TAG_NOW)
.setExecutionWindow(1, 1)
.setBackoffCriteria(30000, JobRequest.BackoffPolicy.LINEAR)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setUpdateCurrent(true)
.build()
.scheduleAsync()
}
fun schedulePeriodicAsync() {
jobCallback = null
JobRequest.Builder(TAG)
.setPeriodic(900000)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setUpdateCurrent(true)
.build()
.scheduleAsync()
}
I found the solution for my problem.
So because I use dagger, I provided a singleton Mutex object, and injected into the job. When the job starts call mutex.lock(), and beacuse there is only 1 object from the mutex, even if another job starts, the second job will waite until the firsjob is done.
I need to get the name of any Android app when it opens and launch a password window. I have searched everywhere how to find out the name of the app which the user has opened but I have found no working solution yet. I have a service which I'm running on the background, but it only returns my app's name or the home screen name, no matter which app I open.
Here is my service code:
package com.example.applock
import android.app.ActivityManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.provider.Settings
class BackAppListenerService : Service() {
private var isRunning = false
private var lastApp = ""
override fun onCreate() {
println(TAG + "Service onCreate")
isRunning = true
val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
println(TAG + "Service onStartCommand")
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
Thread(Runnable { //Your logic that service will perform will be placed here
//In this example we are just looping and waits for 1000 milliseconds in each loop.
while (true) {
try {
Thread.sleep(1000)
} catch (e: Exception) {
}
val mActivityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val mPackageName = mActivityManager.runningAppProcesses[0].processName
println(mPackageName)
}
}).start()
return START_STICKY
}
override fun onBind(arg0: Intent): IBinder? {
println(TAG + "Service onBind")
return null
}
override fun onDestroy() {
isRunning = false
println(TAG + "Service onDestroy")
}
companion object {
private const val TAG = "HelloService"
}
}
Ok, so I have figured it out.
First add this to your manifest.xml under the manifest tag:
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions"/>
Then go to apps permissions > Usage Stats go to your app and enable it. You can also make a pop up asking for the user to do it once the apps loads.
Now, to get name of the current foreground app:
fun getForegroundApp(): String {
var currentApp = "NULL"
// You can delete the if-else statement if you don't care about Android versions
// lower than 5.0. Just keep the code that is inside the if and delete the one
// inside the else statement.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val usm = this.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
val time = System.currentTimeMillis()
val appList =
usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time)
if (appList != null && appList.size > 0) {
val mySortedMap: SortedMap<Long, UsageStats> =
TreeMap<Long, UsageStats>()
for (usageStats in appList) {
mySortedMap.put(usageStats.lastTimeUsed, usageStats)
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey())!!.getPackageName()
}
}
} else {
val am = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val tasks = am.runningAppProcesses
currentApp = tasks[0].processName
}
// Get only the app name name
return currentApp.split(".").last()
}
Sometimes the app name isn't the one displayed, for example the "gmail" app has the name "gm" when I tested it. The home screen name also changes from device to device
The logic to call it every few milliseconds to get the current foreground app is simple:
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
Thread(Runnable {
while (true) {
try {
Thread.sleep(10)
} catch (e: Exception) {
}
val currentApp = getForegroundApp()
if (currentApp != lastApp) {
println(currentApp)
// New app on front
lastApp = currentApp
println(currentApp)
// Do whatever you wan
}
}
}).start()
return START_STICKY
}
And that's it.
I have a project using RecognitionListener written in Kotlin. The speech-to-text function was always a success and never presented any problems.
Since last week, it's onResult function started to be called twice. No changes were made on the project. I tested old versions of the project (from months ago) and those had the same problem.
There are three different cases:
Small text (1 to 8 words) and SpeechRecognizer being stopped automatically -> onResult() called twice;
Big text (9 words or more) and SpeechRecognizer being stopped automatically -> Normal behavior (onResult() called once);
Any text size and SpeechRecognizer stopListening() function called manually (from code) -> Normal behavior.
Here is the VoiceRecognition speech-to-text class code:
class VoiceRecognition(private val activity: Activity, language: String = "pt_BR") : RecognitionListener {
private val AudioLogTag = "AudioInput"
var voiceRecognitionIntentHandler: VoiceRecognitionIntentHandler? = null
var voiceRecognitionOnResultListener: VoiceRecognitionOnResultListener? = null //Must have this
var voiceRecognitionLayoutChanger: VoiceRecognitionLayoutChanger? = null
var isListening = false
private val intent: Intent
private var speech: SpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(activity)
init {
speech.setRecognitionListener(this)
intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
}
//It is important to put this function inside a clickListener
fun listen(): Boolean {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.RECORD_AUDIO), 1)
return false
}
speech.startListening(intent)
Log.i(AudioLogTag, "startListening")
return true
}
//Use this if you want to stop listening but still get recognition results
fun endListening(){
Log.i(AudioLogTag, "stopListening")
speech.stopListening()
isListening = false
}
fun cancelListening(){
Log.i(AudioLogTag, "cancelListening")
speech.cancel()
voiceRecognitionLayoutChanger?.endListeningChangeLayout()
isListening = false
}
override fun onReadyForSpeech(p0: Bundle?) {
Log.i(AudioLogTag, "onReadyForSpeech")
voiceRecognitionLayoutChanger?.startListeningChangeLayout()
isListening = true
}
override fun onRmsChanged(p0: Float) {
// Log.i(AudioLogTag, "onRmsChanged: $p0")
// progressBar.setProgress((Int) p0)
}
override fun onBufferReceived(p0: ByteArray?) {
Log.i(AudioLogTag, "onBufferReceived: $p0")
}
override fun onPartialResults(p0: Bundle?) {
Log.i(AudioLogTag, "onPartialResults")
}
override fun onEvent(p0: Int, p1: Bundle?) {
Log.i(AudioLogTag, "onEvent")
}
override fun onBeginningOfSpeech() {
Log.i(AudioLogTag, "onBeginningOfSpeech")
}
override fun onEndOfSpeech() {
Log.i(AudioLogTag, "onEndOfSpeech")
voiceRecognitionLayoutChanger?.endListeningChangeLayout()
isListening = false
}
override fun onError(p0: Int) {
speech.cancel()
val errorMessage = getErrorText(p0)
Log.d(AudioLogTag, "FAILED: $errorMessage")
voiceRecognitionLayoutChanger?.endListeningChangeLayout()
isListening = false
}
override fun onResults(p0: Bundle?) {
val results: ArrayList<String> = p0?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) as ArrayList<String>
Log.i(AudioLogTag, "onResults -> ${results.size}")
val voiceIntent: Int? = voiceRecognitionIntentHandler?.getIntent(results[0])
if (voiceIntent != null && voiceIntent != 0) {
voiceRecognitionIntentHandler?.handle(voiceIntent)
return
}
voiceRecognitionOnResultListener!!.onResult(results[0])
}
private fun getErrorText(errorCode: Int): String {
val message: String
when (errorCode) {
SpeechRecognizer.ERROR_AUDIO -> message = "Audio recording error"
SpeechRecognizer.ERROR_CLIENT -> message = "Client side error"
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> message = "Insufficient permissions"
SpeechRecognizer.ERROR_NETWORK -> message = "Network error"
SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> message = "Network timeout"
SpeechRecognizer.ERROR_NO_MATCH -> message = "No match"
SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> message = "RecognitionService busy"
SpeechRecognizer.ERROR_SERVER -> message = "Error from server"
SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> message = "No speech input"
else -> message = "Didn't understand, please try again."
}
return message
}
//Use it in your overriden onPause function.
fun onPause() {
voiceRecognitionLayoutChanger?.endListeningChangeLayout()
isListening = false
speech.cancel()
Log.i(AudioLogTag, "pause")
}
//Use it in your overriden onDestroy function.
fun onDestroy() {
speech.destroy()
}
listen(), endListening() and cancelListening() are all called from a button.
I found this open issue: https://issuetracker.google.com/issues/152628934
As I commented, I assume it is an issue with the "speech recognition service" and not with the Android RecognitionListener class.
this is my temporary workaround
singleResult=true;
#Override
public void onResults(Bundle results) {
Log.d(TAG, "onResults"); //$NON-NLS-1$
if (singleResult) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null && matches.size() > 0) {
Log.d("single Result", "" + matches.get(0));
}
singleResult=false;
}
getHandler().postDelayed(new Runnable() {
#Override
public void run() {
singleResult=true;
}
},100);
}
I had the same problem and I've just added a boolean flag in my code, but ofcourse it's a temporary solution and I don't know the source of this problem.
val recognizer = SpeechRecognizer.createSpeechRecognizer(context)
recognizer.setRecognitionListener(
object : RecognitionListener {
var singleResult = true
override fun onResults(results: Bundle?) {
if (singleResult) {
results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION).let {
// do something with result
}
// next result will be ignored
singleResult = false
}
}
}
This just started happening in one of my apps yesterday. I added a boolean to allow the code to execute only once, but I'd love an explanation as to why it suddenly started doing this. Any updates?
I use the the following code based on time differences, which should continue to work if Google ever gets around to fixing this bug.
long mStartTime = System.currentTimeMillis(); // Global Var
#Override
public void onResults(Bundle results)
{
long difference = System.currentTimeMillis() - mStartTime;
if (difference < 100)
{
return;
}
mStartTime = System.currentTimeMillis();
ArrayList<String> textMatchList =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Event_Handler(VOICE_DATA, textMatchList.get(0));
// process event
}
ya even I faced the same issue with my app but I fixed it with a custom logic that is using a flag means a variable let it be a temp variable and by default set it as a false.
what you need to do set the temp as true wherever you are starting listening voice.
Then in your handler what you need to do is just add a if condition on the basis of temp variable like
if (temp) {
do something
temp = false
}
so what will happen you handler will be called twice as usual but you will be able to handle this data only.
I have the following code for music recognition. I am using intent service to do all the music recognition in the service. I have done all the basic steps like adding all the permissions required and adding the ACRCloud android SDK in the project.
class SongIdentifyService(discoverPresenter : DiscoverPresenter? = null) : IACRCloudListener , IntentService("SongIdentifyService") {
private val callback : SongIdentificationCallback? = discoverPresenter
private val mClient : ACRCloudClient by lazy { ACRCloudClient() }
private val mConfig : ACRCloudConfig by lazy { ACRCloudConfig() }
private var initState : Boolean = false
private var mProcessing : Boolean = false
override fun onHandleIntent(intent: Intent?) {
Log.d("SongIdentifyService", "onHandeIntent called" )
setUpConfig()
addConfigToClient()
if (callback != null) {
startIdentification(callback)
}
}
public fun setUpConfig(){
Log.d("SongIdentifyService", "setupConfig called")
this.mConfig.acrcloudListener = this#SongIdentifyService
this.mConfig.host = "some-host"
this.mConfig.accessKey = "some-accesskey"
this.mConfig.accessSecret = "some-secret"
this.mConfig.protocol = ACRCloudConfig.ACRCloudNetworkProtocol.PROTOCOL_HTTP // PROTOCOL_HTTPS
this.mConfig.reqMode = ACRCloudConfig.ACRCloudRecMode.REC_MODE_REMOTE
}
// Called to start identifying/discovering the song that is currently playing
fun startIdentification(callback: SongIdentificationCallback)
{
Log.d("SongIdentifyService", "startIdentification called")
if(!initState)
{
Log.d("AcrCloudImplementation", "init error")
}
if(!mProcessing) {
mProcessing = true
if (!mClient.startRecognize()) {
mProcessing = false
Log.d("AcrCloudImplementation" , "start error")
}
}
}
// Called to stop identifying/discovering song
fun stopIdentification()
{
Log.d("SongIdentifyService", "stopIdentification called")
if(mProcessing)
{
mClient.stopRecordToRecognize()
}
mProcessing = false
}
fun cancelListeningToIdentifySong()
{
if(mProcessing)
{
mProcessing = false
mClient.cancel()
}
}
fun addConfigToClient(){
Log.d("SongIdentifyService", "addConfigToClient called")
this.initState = this.mClient.initWithConfig(this.mConfig)
if(this.initState)
{
this.mClient.startPreRecord(3000)
}
}
override fun onResult(result: String?) {
Log.d("SongIdentifyService", "onResult called")
Log.d("SongIdentifyService",result)
mClient.cancel()
mProcessing = false
val result = Gson().fromJson(result, SongIdentificationResult :: class.java)
if(result.status.code == 3000)
{
callback!!.onOfflineError()
}
else if(result.status.code == 1001)
{
callback!!.onSongNotFound()
}
else if(result.status.code == 0 )
{
callback!!.onSongFound(MusicDataMapper().convertFromDataModel(result))
//callback!!.onSongFound(Song("", "", ""))
}
else
{
callback!!.onGenericError()
}
}
override fun onVolumeChanged(p0: Double) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
interface SongIdentificationCallback {
// Called when the user is offline and music identification failed
fun onOfflineError()
// Called when a generic error occurs and music identification failed
fun onGenericError()
// Called when music identification completed but couldn't identify the song
fun onSongNotFound()
// Called when identification completed and a matching song was found
fun onSongFound(song: Song)
}
}
Now when I am starting the service I am getting the following error:
I checked the implementation of the ACRCloudClient and its extends android Activity. Also ACRCloudClient uses shared preferences(that's why I am getting a null pointer exception).
Since keeping a reference to an activity in a service is not a good Idea its best to Implement the above code in the activity. All the implementation of recognizing is being done in a separate thread anyway in the ACRCloudClient class so there is no point of creating another service for that.