Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

Xamarin Forms (Android) Notification Push

$
0
0

I'm writing an app following the article of https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-xamarin-forms-get-started-push

Ok, all is perfect. My app receives notifications but when my app is closed by the SO by inactivity then my device not receive nothing.

I look many examples, but I did can't to get to run the functionality.

In my MainActivity.cs I have the next code,

static MainActivity instance = null;
    // Return the current activity instance.
    public static MainActivity CurrentActivity
    {
        get
        {
            return instance;
        }
    }


    protected override void OnCreate(Bundle bundle)
    {

        instance = this;

        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());

        PushRegister();
    }

    private void PushRegister()
    {

        try
        {
            // Check to ensure everything's set up right
            GcmClient.CheckDevice(this);
            GcmClient.CheckManifest(this);

            GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
        }
        catch (Java.Net.MalformedURLException)
        {
            CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error");
        }
        catch (Exception e)
        {
            CreateAndShowDialog(e.Message, "Error");
        }
    }

    private void CreateAndShowDialog(String message, String title)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.SetMessage(message);
        builder.SetTitle(title);
        builder.Create().Show();
    }

And I have other file named GmcService.cs with the next code,

[assembly: Permission(Name = "company.samplepush.mobile.droid.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "company.samplepush.mobile.droid.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
[assembly: UsesPermission(Name = "android.permission.RECEIVE_BOOT_COMPLETED")]
namespace Adico.SamplePush.Mobile.Droid
{

[Service]
public class GcmService : GcmServiceBase
{
    public static string RegistrationID { get; private set; }

    public GcmService() : base(PushHandlerBroadcastReceiver.SENDER_IDS) { }

    protected override void OnRegistered(Context context, string registrationId)
    {
        Log.Verbose("PushHandlerBroadcastReceiver", "GCM Registered: " + registrationId);
        RegistrationID = registrationId;

        var push = App.AzurePushService.ServiceClient.GetPush();

        MainActivity.CurrentActivity.RunOnUiThread(() => Register(push, new List<string>()));
    }

    public async void Register(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable<string> tags)
    {
        try
        {

            const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";

            JObject templates = new JObject();
            templates["genericMessage"] = new JObject
            {
                { "body", templateBodyGCM }
            };

            await push.RegisterAsync(RegistrationID, templates);
            var data = App.AzurePushService.ServiceClient.InstallationId;

            Log.Info("Push Installation Id", push.InstallationId.ToString());
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
            Debugger.Break();
        }
    }

    protected override async void OnMessage(Context context, Intent intent)
    {
        Log.Info("PushHandlerBroadcastReceiver", "GCM Message Received!");

        await System.Threading.Tasks.Task.Delay(500);

        var msg = new StringBuilder();

        if (intent != null && intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
                msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
        }

        //Store the message
        var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private);
        var edit = prefs.Edit();
        edit.PutString("last_msg", msg.ToString());
        edit.Commit();

        string message = intent.Extras.GetString("message");
        if (!string.IsNullOrEmpty(message))
        {
            createNotification("New todo item!", "Todo item: " + message);
            return;
        }


        string msg2 = intent.Extras.GetString("name");

        createNotification("Unknown message details", msg.ToString());
    }

    void createNotification(string title, string desc)
    {
        //Create notification
        var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

        //Create an intent to show ui
        var uiIntent = new Intent(this, typeof(MainActivity));

        //Use Notification Builder
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        //Create the notification
        //we use the pending intent, passing our ui intent over which will get called
        //when the notification is tapped.
        var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, uiIntent, 0))
                .SetSmallIcon(Android.Resource.Drawable.SymActionEmail)
                .SetTicker(title)
                .SetContentTitle(title)
                .SetContentText(desc)
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                .SetAutoCancel(true).Build();

        //Show the notification
        notificationManager.Notify(1, notification);
    }

    protected async override void OnUnRegistered(Context context, string registrationId)
    {

        var push = App.AzurePushService.ServiceClient.GetPush();

        await push.UnregisterAsync();

        Log.Error("PushHandlerBroadcastReceiver", "Unregistered RegisterationId : " + registrationId);
    }

    protected override void OnError(Context context, string errorId)
    {
        Log.Error("PushHandlerBroadcastReceiver", "GCM Error: " + errorId);
    }
}

[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "company.samplepush.mobile.droid" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "company.samplepush.mobile.droid" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "company.samplepush.mobile.droid" })]
public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase<GcmService>
{
    public static string[] SENDER_IDS = new string[] { "XXXXXXXXXXXXX" };

    public override void OnReceive(Context context, Intent intent)
    {
        base.OnReceive(context, intent);
    }
}

}

All run good, but when my app is closed by the SO... The push notifications aren't received.

I have spent many hours in this trouble.. please, Can you help me to get receive the notifications always? Like whatsapp and other apps...


Viewing all articles
Browse latest Browse all 91519

Trending Articles