颤振 FCM 通知声音在发布时不起作用

时间:2021-01-11 09:24:25

标签: android firebase flutter push-notification firebase-cloud-messaging

我最近几天都在为此苦苦挣扎。我有flutter应用程序应该从firebase接收通知(使用FCM)并播放自定义声音。如果我使用 let url = URL(string: "https://midcdmz.nrel.gov/apps/spa.pl?syear=2020&smonth=1&sday=1&eyear=2020&emonth=1&eday=1&otype=0&step=60&stepunit=1&hr=12&min=0&sec=0&latitude=39.743&longitude=-105.178&timezone=-7.0&elev=1829&press=835&temp=10&dut1=0.0&deltat=64.797&azmrot=180&slope=0&refract=0.5667&field=0") struct ContentView: View { var html = try! String(contentsOf: url!, encoding: String.Encoding.ascii) let leftSideOfTheValue = "1/1/2020,0:00:00," let rightSideOfTheValue = "1/1/2020,1:00:00," guard let leftRange = html.range(of: leftSideOfTheValue) else { print("cant find left range") return } guard let rightRange = html.range(of: rightSideOfTheValue) else { print("cant find right range") return let rangeOfTheValue = leftRange.upperBound..<rightRange.lowerBound let elevationInfo = (html[rangeOfTheValue]) var body: some View { Text(elevationInfo) } 或使用 flutter run 运行应用程序,这可以正常工作,但是如果我使用 flutter run --release 构建应用程序并在我的手机上手动安装它,我仍然收到通知但没有声音,它赢了甚至不播放默认通知声音。

我检查了我的声音是否打开,以及应用设置中的通知渠道是否正确。

ma​​in.dart

flutter build apk --release

android/build.gradle

void main() async {
  // needed if you intend to initialize in the `main` function
  WidgetsFlutterBinding.ensureInitialized();

  fcm.getToken().then((value) {
    print("TOKEN:" + value);
  });

  fcm.configure(
    onResume: (Map<String, dynamic> message) async {},
    onLaunch: (Map<String, dynamic> message) async {},
    onMessage: (Map<String, dynamic> message) async {
       AudioCache _audioCache = AudioCache(
          prefix: "sounds/",
          fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP));

      _audioCache.play('merchant_notify.mp3');
    },
  );

  runApp(MyApp());
}

android/app/build.gradle

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
   
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

androidmanifest.xml

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "" 
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"    
   
}

MainActivity.kt

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
    package="">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label=""
        android:icon="@mipmap/launcher_icon">
        <activity
           android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize"
            android:showWhenLocked="true"
            android:turnScreenOn="true">

            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />

            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <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>
       
        <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

       
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
       <meta-data
            android:name="flutterEmbedding"
            android:value="2" /> 
    </application>
</manifest>

package com.example.merchant_delivery import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { } 中还有声音文件

这是我发送到 firebase FCM 的 json:

res\raw\sound.mp3

2 个答案:

答案 0 :(得分:1)

在你的 MainActivity.java 中试试这个

    import io.flutter.embedding.android.FlutterActivity;   
    import android.app.NotificationChannel;  
    import android.app.NotificationManager;  
    import android.media.AudioAttributes;  
    import android.net.Uri;  
    import android.os.Build;   
    import android.os.Bundle;   
    public class MainActivity extends FlutterActivity {  
@Override  
 protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);   
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  
  Uri soundUri=Uri.parse("android.resource://"+getApplicationContext()   
.getPackageName() + "/" +  R.raw.[soundName without extension]);  
AudioAttributes audioAttributes = new AudioAttributes.Builder()   
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)    
                .setUsage(AudioAttributes.USAGE_ALARM)   
                .build();   

        // Creating Channel   
        NotificationChannel channel = new NotificationChannel([ChannelId],[ChannelName], NotificationManager.IMPORTANCE_HIGH);
        channel.setSound(soundUri, audioAttributes);

        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
   // GeneratedPluginRegistrant.registerWith(this);
}

}

答案 1 :(得分:1)

好的,我想我找到了一种(希望)也适合您的解决方案:

就像您一样,一切都在 flutter run --releaseflutter run 中工作,但在我的手机上实际构建和安装 apk-release 时却无法工作(A5 2017)。

所以我想*:唯一的区别是缩小,对吧? Flutter 会自动缩小 apk(请参阅:flutter.dev),所以我使用了 --no-shrink 标志,现在一切正常,即使是构建应用程序也是如此。

*我认为我的意思是拉我的头发 3 小时,而不是远程考虑这个具体的差异。