Xamarin Android应用程序在收到远程通知时自动打开

时间:2018-08-24 07:36:28

标签: android firebase xamarin xamarin.android firebase-cloud-messaging

更新3:已解决!

问题未与FirebaseService,设置或有效负载连接。问题出在应用程序代码中...我们的代码有这样的东西(来自应用程序的继承):

 ParentDroidApplication : Application

在OnCreate方法的该类中,选择要使用的活动,然后调用“ StartActivity”。我将此开关移至MainActivity并解决了问题。

更新2:

Android清单(已删除的服务标签):

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.visma.vfsmobileparentapp" android:versionName="1.0" android:installLocation="internalOnly" android:versionCode="46">
    <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="26" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:allowBackup="true" android:theme="@style/Theme.AppCompat.Light" android:label="Min skole" android:icon="@drawable/ic_launcher" android:name="Min skole">
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
        <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_launcher" />
    </application>
</manifest>

有效负载(添加了content_available和优先级):

{
 "to" : "token",
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "First Notification",
     "title": "Collapsing A"
 },
 "data" : {
     "body" : "First Notification",
     "title": "Collapsing A"
 },
 "content_available": true,
 "priority": "high"
}

结果相同:远程通知后,应用会自动打开:(

更新:

我在OnMessaggeReceive方法中将主要活动,默认声音和毫秒数的意图添加为通知编号的int(您可以在下面的代码中看到)。 我试图删除

<service android:name=".MyFirebaseMessagingService" android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

我没有收到任何通知,但应用程序仍在打开。似乎Firebase正在正常运行。但是应用程序可以自己做魔术

我试图将Firebase降级到42.1021.1版本。结果是一样的

问题

我们正在使用Xamarin开发手机应用程序。我们需要通知,我们开始使用Firebase Cloud消息传递。 iOS中的所有消息(通知)都可以正常工作,接收甚至更新徽章,但是... Android的一个问题:

如果应用程序已关闭(从应用程序列表中清除)并收到远程通知,它将自动打开。我想避免这种情况。背景或前景模式按预期工作。

我的Andoroid清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app" android:versionName="1.0" android:installLocation="internalOnly" android:versionCode="46">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:theme="@style/Theme.AppCompat.Light" android:label="App" android:icon="@drawable/ic_launcher" android:name="App">
  <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
  <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
      <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
      <category android:name="${applicationId}" />
    </intent-filter>
  </receiver>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_launcher" />
</application>
<service android:name=".MyFirebaseMessagingService" android:stopWithTask="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</manifest>

我的FirebaseMessagingService.cs:

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
    public override void OnMessageReceived(RemoteMessage message)
    {
        SendNotification("title", "body"); //just for testing
    }

    public void SendNotification(string title, string body)
    {
         var intent = new Intent(this, typeof(LoginActivity));

        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
        var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

        var style = new Android.Support.V4.App.NotificationCompat.BigTextStyle();
        style.BigText(body);

        Bitmap largeIcon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher);
        var notificationBuilder =
            new Android.Support.V4.App.NotificationCompat.Builder(this)
                .SetLargeIcon(largeIcon)
                .SetSmallIcon(Resource.Drawable.ic_launcher)
                .SetContentTitle(title)
                .SetContentText(body)
                .SetStyle(style)
                .SetAutoCancel(true)
                .SetSound(defaultSoundUri)
                .SetContentIntent(pendingIntent)
                .SetVisibility((int)NotificationVisibility.Public);

        var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(DateTime.Now.Millisecond, notificationBuilder.Build());
    }
}

我尝试了更改清单值,尝试了模拟器,设备,并发送了不同的有效载荷:

通知和数据:

{
"to" : "token",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
}
}

仅通知:

{
"to" : "token",
"notification" : { 
"body" : "First Notification", 
"title": "Collapsing A" 
}
}

仅数据:

{
"to" : "token", 
"data" : {
"body" : "First Notification",
"title": "Collapsing A"
}
}

在所有情况下,关闭应用程序时,通知都会自动接收并打开应用程序。如何避免自动打开?我只需要通知。有什么想法我可以做什么?

裸包:

Xamaring.Firebase.Messaging - 60.1142.1
Xamarin.Firebase.Code - 60.1142.1
Xamarin.Firebase.Common - 60.1142.1

在Android 6和Android 7设备(三星)上进行了测试

2 个答案:

答案 0 :(得分:0)

您需要在此处定义“活动”,在点击通知时必须将其打开。

    var intent = new Intent(this, typeof(YourActivity));
    intent.AddFlags(ActivityFlags.ClearTop);
    //sent RemoteMessage message data to your activity if you need
    //intent.PutExtra("User", JsonConvert.SerializeObject(user));
    var pendingIntent = PendingIntent.GetActivity(this, GenerateRandom(), intent, PendingIntentFlags.OneShot);
    var notificationBuilder = new Notification.Builder(this)
            .SetSmallIcon(Resource.Drawable.myIcon)
            .SetContentTitle(user.Organization)
            .SetSubText(myModuleName)
            .SetContentText(BodyText)
            .SetAutoCancel(true)
            .SetContentIntent(pendingIntent)
            .Build();
    var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
    var notification = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
   //this is for sound of notification
    var mp = MediaPlayer.Create(ApplicationContext, notification);
    mp.Start();
    notificationManager.Notify(GenerateRandom(), notificationBuilder);

只给通知赋予唯一的ID,以使它们不会重叠

private int GenerateRandom()
{
    var rn = new Java.Util.Random();
    int n = 1000 - 1233 + 1;
    int i = rn.NextInt() % n;
    return 1000 + i;
}

答案 1 :(得分:0)

我对情况的了解告诉我,由于您没有给通知以待定的意向,因此它将直接打开您的应用程序:

解决此问题的方法:

 Intent intent = new Intent(this, typeof(MainAcitivity)); //Activity you want to open
 intent.AddFlags(ActivityFlags.ClearTop);
 var pendingIntent = PendingIntent.GetActivity(this, RandomGenerator(), intent, PendingIntentFlags.OneShot);

如果您想要默认声音:

 Notification notify = new Notification();
 notify.Defaults = NotificationDefaults.Sound;
 notify.Defaults = NotificationDefaults.Vibrate;

使用NotificationCompat推送通知(用于向后兼容)

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
             .SetSmallIcon(Resource.Drawable.Icon)
             .SetContentTitle(messageTitle)
             .SetContentText(messageBody)
             .SetSound(Settings.System.DefaultNotificationUri)
             .SetVibrate(new long[] { 1000, 1000 })
             .SetLights(Color.AliceBlue, 3000, 3000)
             .SetAutoCancel(true)
             .SetContentIntent(pendingIntent);

然后通知系统您的应用程序发出了通知:

  NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(RandomGenerator(), notificationBuilder.Build());

此外,还使用随机数,以便在引发新通知时通知不会切换位置:

private int RandomGenerator() 
{
 return new Random().Next( int.MinValue, int.MaxValue );
}

要实现Android Oreo频道兼容性(如您所见,official docs,则需要在AndroidManifest.xml中的应用程序组件中添加以下元数据元素:

<meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>

当通知消息中没有指定通道,或者应用尚未创建提供的通道时,将使用此默认通道。