Я новичок в изучении флаттера. В моем приложении флаттера есть собственная фоновая служба Android на kotlin, где у меня работает сокет, и всякий раз, когда сокет что-то слушает, я генерирую уведомление с помощью NotificationCompat.Builder.

Но я не могу вернуть приложение Flutter на передний план, когда пользователь нажимает на уведомление.

Я попытался создать ожидающее намерение и передать его в сборщик уведомлений setContentIntent(), но при нажатии ничего не происходит.

Показана функция уведомления в собственной фоновой службе:

fun shownotification (){
   packageNamer = this.getPackageName()
   launchIntent = this.getPackageManager().getLaunchIntentForPackage(packageName)
   var className = launchIntent?.getComponent()!!.className.javaClass
   intent.action = "SELECT_NOTIFICATION"

   intent.setClass(this,className)
   pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    var builder = NotificationCompat.Builder(this, "notifications")
            .setOngoing(true)
            .setContentIntent(pendingIntent)
            .setFullScreenIntent(pendingIntent, true)
            .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
            .setContentTitle("My notification")
            .setContentText("Much longer text that cannot fit one line...")
            .setStyle(NotificationCompat.BigTextStyle()
            .bigText("Much longer text that cannot fit one line..."))
            .setPriority(NotificationCompat.PRIORITY_HIGH)

    manager?.notify(456,builder.build())

}

Файл AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

<!-- io.flutter.app.FlutterApplication is an android.app.Application that
     calls FlutterMain.startInitialization(this); in its onCreate method.
     In most cases you can leave this as-is, but you if you want to provide
     additional functionality it is fine to subclass or reimplement
     FlutterApplication and put your custom class here. -->
<application
    android:name=".MyApplication"
    android:label="bizzyb_demo"
    android:icon="@mipmap/ic_launcher">
    <service android:name=".MyService" android:exported="true" android:enabled="true"/>

    <activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <!-- This keeps the window background of the activity showing
             until Flutter renders its first frame. It can be removed if
             there is no splash screen (such as the default splash screen
             defined in @style/LaunchTheme). -->
        <meta-data
            android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
            android:value="true" />

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
        <intent-filter>
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

Что я делаю неправильно здесь. Я считаю, что мне не хватает чего-то очень очевидного, поскольку я новичок в разработке мобильных приложений.

Ваши экспертные отзывы будут оценены. Спасибо

0
Rafin Utshaw 25 Окт 2019 в 09:49

1 ответ

Вам необходимо включить click_action: FLUTTER_NOTIFICATION_CLICK в качестве пары "ключ-значение" "Пользовательские данные" в полезную нагрузку уведомления.

Bundle bundle = new Bundle();
bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));

var builder = NotificationCompat.Builder(this, "notifications")
            .setOngoing(true)
            .setContentIntent(pendingIntent)
            .setFullScreenIntent(pendingIntent, true)
            .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
            .setContentTitle("My notification")
            .setContentText("Much longer text that cannot fit one line...")
            .setStyle(NotificationCompat.BigTextStyle()
            .bigText("Much longer text that cannot fit one line..."))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setExtras(bundle) // Set the bundle

0
Vineet 25 Окт 2019 в 10:08
Я должен сказать вам, что я не использую push-уведомления, я прослушиваю события сокета и генерирую уведомления от них. Мне все еще нужно установить click_action: FLUTTER_NOTIFICATION_CLICK?
 – 
Rafin Utshaw
25 Окт 2019 в 12:27
Во всяком случае, я пытался добавить click_action: FLUTTER_NOTIFICATION_CLICK, используя пакеты, не работает.
var bundle:Bundle? = null <br/> bundle?.putString("click_action","FLUTTER_NOTIFICATION_CLICK ")
@Vineet
 – 
Rafin Utshaw
25 Окт 2019 в 12:54