feat: integrate the notification listener into the project

This commit is contained in:
2022-02-24 21:56:38 +02:00
parent a56a88efe4
commit add74ea848
8 changed files with 306 additions and 74 deletions
+1 -1
View File
@@ -27,7 +27,7 @@
</activity>
<service
android:label="Lyrics Grabbr Notifications Listener"
android:name="com.emilecode.android_notification_listener2.NotificationListener"
android:name=".NotificationListener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="false">
<intent-filter>
@@ -1,6 +1,55 @@
package com.illusionware.lyricsgrabbr.lyricsgrabbr
import android.content.Intent
import android.text.TextUtils
import androidx.core.app.NotificationManagerCompat
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
companion object {
private const val ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"
private const val EVENT_CHANNEL_NAME = "notifications.eventChannel"
private const val METHOD_CHANNEL_NAME = "notifications/method"
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, METHOD_CHANNEL_NAME)
methodChannel.setMethodCallHandler { call, result ->
when (call.method) {
"plugin.hasPermission" -> {
result.success(isPermissionGranted())
}
"plugin.openPermissionSettings" -> {
result.success(openPermissionSettings())
}
else -> result.notImplemented()
}
}
val eventChannel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL_NAME)
val streamHandler = NotificationStreamHandler(context)
eventChannel.setStreamHandler(streamHandler)
}
private fun isPermissionGranted(): Boolean {
val packageName = context.packageName
val pkgs = NotificationManagerCompat.getEnabledListenerPackages(context)
for (name in pkgs) {
if (TextUtils.equals(packageName, name)) {
return true
}
}
return false
}
private fun openPermissionSettings(): Boolean {
context.startActivity(Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
return true
}
}
@@ -0,0 +1,78 @@
package com.illusionware.lyricsgrabbr.lyricsgrabbr
import android.app.Notification
import android.content.Intent
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import org.json.JSONException
import org.json.JSONObject
import android.os.Bundle
/**
* Notification listening service. Intercepts notifications if permission is given to do so.
*/
class NotificationListener : NotificationListenerService() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
getCurrentNotifications()
return super.onStartCommand(intent, flags, startId)
}
override fun onListenerConnected() {
getCurrentNotifications()
}
override fun onNotificationPosted(sbn: StatusBarNotification) {
sendNotificationBroadcast(sbn)
}
private fun getCurrentNotifications() {
val sbns = activeNotifications
for (sbn in sbns) {
// TODO: remove this check and figure out a way to send a fucking list instead
if (sbn.packageName == "com.spotify.music") {
sendNotificationBroadcast(sbn)
}
}
}
private fun sendNotificationBroadcast(sbn: StatusBarNotification) {
// TODO: get specific media player notification data
// such as onPlay and onNextSong or whatever tf
// Retrieve package name to set as title.
val packageName = sbn.packageName
// Retrieve extra object from notification to extract payload.
val extras = sbn.notification.extras
val packageMessage = extras?.getCharSequence(Notification.EXTRA_TEXT).toString()
val packageText = extras?.getCharSequence("android.title").toString()
val packageExtra = convertBundleToJsonString(sbn.notification.extras)
// Pass data from one activity to another.
val intent = Intent(NOTIFICATION_INTENT)
intent.putExtra(NOTIFICATION_PACKAGE_NAME, packageName)
intent.putExtra(NOTIFICATION_PACKAGE_MESSAGE, packageMessage)
intent.putExtra(NOTIFICATION_PACKAGE_TEXT, packageText)
intent.putExtra(NOTIFICATION_PACKAGE_EXTRA, packageExtra)
sendBroadcast(intent)
}
companion object {
const val NOTIFICATION_INTENT = "notification_event"
const val NOTIFICATION_PACKAGE_NAME = "package_name"
const val NOTIFICATION_PACKAGE_MESSAGE = "package_message"
const val NOTIFICATION_PACKAGE_TEXT = "package_text"
const val NOTIFICATION_PACKAGE_EXTRA = "package_extra"
}
private fun convertBundleToJsonString(extra: Bundle): String {
val json = JSONObject()
val keys = extra.keySet()
for (key in keys) {
try {
json.put(key, JSONObject.wrap(extra.get(key)))
} catch (e: JSONException) {
//Handle exception here
}
}
return json.toString()
}
}
@@ -0,0 +1,46 @@
package com.illusionware.lyricsgrabbr.lyricsgrabbr
import io.flutter.plugin.common.EventChannel.StreamHandler
import io.flutter.plugin.common.EventChannel.EventSink
import android.content.*
class NotificationStreamHandler(private val context: Context) : StreamHandler {
private var eventSink: EventSink? = null
private var receiver: NotificationReceiver? = null
private val listenerIntent = Intent(context, NotificationListener::class.java)
// Called whenever the event channel is subscribed to in Flutter
override fun onListen(o: Any?, eventSink: EventSink?) {
this.eventSink = eventSink
receiver = NotificationReceiver()
val intentFilter = IntentFilter()
intentFilter.addAction(NotificationListener.NOTIFICATION_INTENT)
context.registerReceiver(receiver, intentFilter)
context.startService(listenerIntent)
}
// Called whenever the event channel subscription is cancelled in Flutter
override fun onCancel(o: Any?) {
eventSink = null
context.stopService(listenerIntent)
context.unregisterReceiver(receiver)
}
internal inner class NotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val packageName = intent.getStringExtra(NotificationListener.NOTIFICATION_PACKAGE_NAME)
val packageMessage = intent.getStringExtra(NotificationListener.NOTIFICATION_PACKAGE_MESSAGE)
val packageText = intent.getStringExtra(NotificationListener.NOTIFICATION_PACKAGE_TEXT)
val packageExtra = intent.getStringExtra(NotificationListener.NOTIFICATION_PACKAGE_EXTRA)
val map = HashMap<String, Any>()
map["packageName"] = packageName!!
map["packageMessage"] = packageMessage!!
map["packageText"] = packageText!!
map["packageExtra"] = packageExtra!!
eventSink?.success(map)
}
}
}