Help me find the error in the code
My MainActivity:
string CHANNEL_ID = "MyChannel";
protected override void OnCreate(Bundle savedInstanceState)
{
....
...
CreateNotificationChannel();
LoadApplication(new App());
}
public void CreateNotification(string SetContentTitle, string SetContentText)
{
var builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetContentTitle(SetContentTitle)
.SetContentText(SetContentText)
.SetChannelId(CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.icon);
// Finally, publish the notification:
var notificationManager = NotificationManagerCompat.From(this);
// Get the notification manager:
// NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
int notificationId = 1000;
notificationManager.Notify(notificationId, builder.Build());
}
void CreateNotificationChannel(){
if (Build.VERSION.SdkInt<BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
string name = "MyName";
var description = "desc";
var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.High)
{
Description = description
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
and I have a class in which when I need I start displaying local notifications using the code below
var urlOb = new MainActivity();
urlOb.CreateNotification(titleback, textback);
I think I did everything right, but local notifications are not shown.
You can call the method in other activity
public static MainActivity instance;
In the method onCreate
//...
base.OnCreate(savedInstanceState);
instance = this;
And you can call it in other method
MainActivity.instance.CreateNotification(titleback, textback);
Related
Task: Create a background task to run when application is stopped/paused that periodically (3-7 seconds) performs HTTP requests and stores response information in mysqlite and displays local notifications when required.
I have create a background service like the following,
[Service(Enabled = true)]
public class MyRequestService : Service
That is started like an intent from MainActivity,
public void StartMyRequestService()
{
var serviceToStart = new Intent(this, typeof(MyRequestService));
StartService(serviceToStart);
}
public void StopMyRequestService()
{
var serviceToStart = new Intent(this, typeof(MyRequestService));
StopService(serviceToStart);
}
protected override void OnPause()
{
base.OnPause();
StartMyRequestService();
}
protected override void OnDestroy()
{
base.OnDestroy();
StartMyRequestService();
}
protected override void OnResume()
{
base.OnResume();
StopMyRequestService();
}
In my service I have the following features in use,
return STICKY in OnStartCommand
create a 'permanent' native
notification with channel
power manager lock
And the code looks like the following,
private Handler handler;
private Action runnable;
private bool isStarted
private WakeLock wakeLock;
public override void OnCreate()
{
base.OnCreate();
handler = new Handler();
runnable = new Action(() =>
{
DispatchNotificationThatAlarmIsGenerated("I'm running");
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
});
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if (isStarted)
{
// service is already started
}
else
{
CreateNotificationChannel();
DispatchNotificationThatServiceIsRunning();
handler.PostDelayed(runnable, DELAY_BETWEEN_LOG_MESSAGES);
isStarted = true;
PowerManager powerManager = (PowerManager)this.GetSystemService(Context.PowerService);
WakeLock wakeLock = powerManager.NewWakeLock(WakeLockFlags.Full, "Client Lock");
wakeLock.Acquire();
}
return StartCommandResult.Sticky;
}
public override void OnTaskRemoved(Intent rootIntent)
{
//base.OnTaskRemoved(rootIntent);
}
public override IBinder OnBind(Intent intent)
{
// Return null because this is a pure started service. A hybrid service would return a binder that would
// allow access to the GetFormattedStamp() method.
return null;
}
public override void OnDestroy()
{
// Stop the handler.
handler.RemoveCallbacks(runnable);
// Remove the notification from the status bar.
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Cancel(NOTIFICATION_SERVICE_ID);
isStarted = false;
wakeLock.Release();
base.OnDestroy();
}
private void CreateNotificationChannel()
{
//Notification Channel
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationImportance.Max);
notificationChannel.EnableLights(true);
notificationChannel.LightColor = Color.Red;
notificationChannel.EnableVibration(true);
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
NotificationManager notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);
notificationManager.CreateNotificationChannel(notificationChannel);
}
private void DispatchNotificationThatServiceIsRunning()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.SetDefaults((int)NotificationDefaults.All)
.SetSmallIcon(Resource.Drawable.icon)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetSound(null)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority(NotificationCompat.PriorityDefault)
.SetAutoCancel(false)
.SetContentTitle("Mobile")
.SetContentText("My service started")
.SetOngoing(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(NOTIFICATION_SERVICE_ID, builder.Build());
}
private void DispatchNotificationThatAlarmIsGenerated(string message)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
Notification.Builder notificationBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.icon_round)
.SetContentTitle("Alarm")
.SetContentText(message)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(App.NOTIFICATION_ALARM, notificationBuilder.Build());
}
This is just a sample, the code is not making any HTTP requests, nor works with entities, db connection etc, it just simply dispatches a new notification every X seconds. What I should see is, when application is closed, the service starts and native notification is created, which is what I see. Then for some time I see 'Alarm' notification is being generated and then my service notification is killed, service disposed and that is all. If I click the power button on my phone, to light up the screen, I see 'Alarm' notifications come to live again. I've checked on several mobile devices with different Android OS (6, 7 and 8) and with disabled power saving modes, no difference, the service notification is killed. What is the issue, what am I doing wrong?
Thanks in advance for any help or guidance!
I think you are using Foreground Services.
you should dispatch the service notification(foreground notification) by StartForeground method.
So try to change
private void DispatchNotificationThatServiceIsRunning()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.SetDefaults((int)NotificationDefaults.All)
.SetSmallIcon(Resource.Drawable.icon)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetSound(null)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority(NotificationCompat.PriorityDefault)
.SetAutoCancel(false)
.SetContentTitle("Mobile")
.SetContentText("My service started")
.SetOngoing(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(NOTIFICATION_SERVICE_ID, builder.Build());
}
to
private void DispatchNotificationThatServiceIsRunning()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.SetDefaults((int)NotificationDefaults.All)
.SetSmallIcon(Resource.Drawable.icon)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetSound(null)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority(NotificationCompat.PriorityDefault)
.SetAutoCancel(false)
.SetContentTitle("Mobile")
.SetContentText("My service started")
.SetOngoing(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
//dispatch foreground notification
StartForeground(NOTIFICATION_SERVICE_ID, builder.Build());
}
I already implement FCM notification on xamarin forms android.so I want,when user click on notification then it will open a Xamarin forms content page.
here is my code for receiving FCM notification:
Inside MyFireMessagingService class-
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);
}
public void SendNotificatios(string body, string Header)
{
Notification.Builder builder = new Notification.Builder(this);
builder.SetSmallIcon(Resource.Drawable.AppLauncher);
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
builder.SetContentIntent(pendingIntent);
builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.AppLauncher));
builder.SetContentTitle(Header);
builder.SetContentText(body);
builder.SetDefaults(NotificationDefaults.Sound);
builder.SetAutoCancel(true);
NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(1, builder.Build());
}
so How to open a content page after click on notification?
As the first thing I have replaced
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);
}
With
public override void HandleIntent(Intent intent)
{
CreateNotification(intent);
}
Then created a new method CreateNotification as follows,
private void CreateNotification(Object e)
{
try
{
string title = "";
string body = "";
var intent = new Intent(this, typeof(MainActivity));
var i = e as Intent;
var bundle = i.Extras;
title = bundle.GetString("gcm.notification.title");
body = bundle.GetString("gcm.notification.body");
intent.PutExtra("title", title);
intent.PutExtra("body", body);
intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop );
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.CancelCurrent | PendingIntentFlags.UpdateCurrent);
Notification.Builder builder = new Notification.Builder(this);
builder.SetSmallIcon(Resource.Drawable.AppLauncher);
builder.SetContentIntent(pendingIntent);
builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.AppLauncher));
builder.SetContentTitle(Header);
builder.SetContentText(body);
builder.SetDefaults(NotificationDefaults.Sound);
builder.SetAutoCancel(true);
NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(1, builder.Build());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Now we have to update the MainActivity.cs to handle the push notification click by overriding OnNewIntent method as follows
protected async override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
var title = intent.GetStringExtra("title");
//This method will get called while the app is launching from the app icon or from the notification
if (title != null)
{
//Means new Intent from push notification
//Code to open the page
}
}
Make sure you have kept LaunchMode = LaunchMode.SingleTask in the activity
I am trying to use Xamarin.Auth for a Facebook signin. It's all set up, but I am missing the last part. The Facebook signin is not my MainActivity, one has to click on a button in order to sign in. I don't know how to start the page for the signin. I have trying to follow this approach, but as my MainActivity isn't the Facebook signin page, it won't work. I have binded (I am following the MVVM pattern) the signin button and have implemented an interface in order to use DependencyService. My problem is when I have to implement the code of the platforms.
This is what I have tried on Android:
class LoginFBImpl : Activity, ILoginFB, IFacebookAuthenticationDelegate
{
public void LoginFB() //the method in the interface
{
var auth = new FacebookAuthenticator(FacebookAuthenticator.ClientId, FacebookAuthenticator.Scope, this);
var authenticator = auth.GetAuthenticator();
var intent = authenticator.GetUI(this);
StartActivity(intent); //Problem occurs here
}
public async void OnAuthenticationCompletedAsync(UserModel token)
{
var facebookService = new FacebookService();
var name = await facebookService.GetNameAsync(token.AccessToken);
var id = await facebookService.GetIdAsync(token.AccessToken);
var picture = await facebookService.GetPictureAsync(token.AccessToken);
}
public void OnAuthenticationCancelled()
{
}
public void OnAuthenticationFailed(string message, Exception exception)
{
}
}
iOS:
public class LoginFBImpl : UIViewController, ILoginFB, IFacebookAuthenticationDelegate
{
public void LoginFB()
{
var auth = new FacebookAuthenticator(FacebookAuthenticator.ClientId, FacebookAuthenticator.Scope, this);
var authenticator = auth.GetAuthenticator();
var viewController = authenticator.GetUI();
PresentViewController(viewController, true, null);
}
public async void OnAuthenticationCompletedAsync(UserModel token)
{
DismissViewController(true, null);
var facebookService = new FacebookService();
var name = await facebookService.GetNameAsync(token.AccessToken);
var id = await facebookService.GetIdAsync(token.AccessToken);
var picture = await facebookService.GetPictureAsync(token.AccessToken);
}
public void OnAuthenticationFailed(string message, Exception exception)
{
DismissViewController(true, null);
var alertController = new UIAlertController
{
Title = message,
Message = exception?.ToString()
};
PresentViewController(alertController, true, null);
}
public void OnAuthenticationCancelled()
{
DismissViewController(true, null);
var alertController = new UIAlertController
{
Title = "Authentication cancelled",
Message = "You didn't complete the authentication process"
};
PresentViewController(alertController, true, null);
}
}
I think it has something to do with the Activity/ViewController, but I don't know how to do it properly. When I run this I get: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference on Android, and I am expecting something similar on iOS - Haven't tested it yet as I am working on Windows.
This is going to be a long post! (grab a cup of coffee/popcorn)
I am using AltBeacon Xamarin sample in my code to show the beacons.
I have come across this example in creating Notifications in Xamarin.
Here there's an Application class where the core logic goes.
public class AltBeaconSampleApplication : Application, IBootstrapNotifier
{
private const string TAG = "AltBeaconSampleApplication";
BeaconManager _beaconManager;
private RegionBootstrap regionBootstrap;
private Region _backgroundRegion;
private BackgroundPowerSaver backgroundPowerSaver;
private bool haveDetectedBeaconsSinceBoot = false;
private string nearbyMessageString = "A beacon is nearby.";
private string nearbyTitleString = "AltBeacon Reference Application";
private MainActivity mainActivity = null;
public MainActivity MainActivity
{
get { return mainActivity; }
set { mainActivity = value; }
}
private NotificationActivity notificationActivity = null;
public NotificationActivity NotificationActivity
{
get { return notificationActivity; }
set { notificationActivity = value; }
}
public AltBeaconSampleApplication() : base() { }
public AltBeaconSampleApplication(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer) { }
public override void OnCreate()
{
base.OnCreate();
_beaconManager = BeaconManager.GetInstanceForApplication(this);
var iBeaconParser = new BeaconParser();
// Estimote > 2013
iBeaconParser.SetBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
_beaconManager.BeaconParsers.Add(iBeaconParser);
Log.Debug(TAG, "setting up background monitoring for beacons and power saving");
// wake up the app when a beacon is seen
_backgroundRegion = new Region("backgroundRegion", null, null, null);
regionBootstrap = new RegionBootstrap(this, _backgroundRegion);
// simply constructing this class and holding a reference to it in your custom Application
// class will automatically cause the BeaconLibrary to save battery whenever the application
// is not visible. This reduces bluetooth power usage by about 60%
backgroundPowerSaver = new BackgroundPowerSaver(this);
PerformHttpRequest();
}
public void DidDetermineStateForRegion(int state, AltBeaconOrg.BoundBeacon.Region region)
{
}
public async void PerformHttpRequest()
{
try
{
using (var client = new HttpClient())
{
var uri = "http://exampleuri";
var result = await client.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<BeaconURL>(result);
SendNotificationFromBeacon(response);
}
}
catch(Exception ex)
{
throw ex;
}
}
private void SendNotificationFromBeacon(BeaconURL receivedNotification)
{
// Setup an intent for SecondActivity:
Intent notificationIntent = new Intent(this, typeof(NotificationActivity));
// Pass some information to SecondActivity:
notificationIntent.PutExtra("CompaignUrl", receivedNotification.CompaignUrl);
notificationIntent.PutExtra("MediaUrl", receivedNotification.MediaUrl);
notificationIntent.PutExtra("titleText", receivedNotification.Title);
notificationIntent.SetFlags(ActivityFlags.NewTask);
// Create a task stack builder to manage the back stack:
Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
// Add all parents of SecondActivity to the stack:
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(NotificationActivity)));
// Push the intent that starts SecondActivity onto the stack:
stackBuilder.AddNextIntent(notificationIntent);
// Obtain the PendingIntent for launching the task constructed by
// stackbuilder. The pending intent can be used only once (one shot):
const int pendingIntentId = 0;
PendingIntent pendingIntent =
stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot);
// Instantiate the builder and set notification elements, including
// the pending intent:
var builder =
new NotificationCompat.Builder(this)
.SetContentTitle(receivedNotification.Title)
.SetContentText(receivedNotification.Text)
.SetSmallIcon(Android.Resource.Drawable.IcDialogInfo);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager =
GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
}
BeaconURL is a POCO class
NotificationActivity is a basic Activity class.
I perform the HttpClient request and get data. I create a notification and present it on my screen. It goes like this
Now when I tap on the notification, I dont go to the NotificationActivity. I am trying to invoke an activity from an ApplicationClass. Is this the right way to perform such stuff. Kindly provide details.
Thanks.
Edit: Added NotificationActivity Class
[Activity(Label = "NotificationActivity")]
public class NotificationActivity : MainActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.NotificationLayout);
TextView titleTextView = FindViewById<TextView>(Resource.Id.txtTitle);
titleTextView.Text = Intent.Extras.GetString("titleText", "");
ImageView mediaImage = FindViewById<ImageView>(Resource.Id.imgViewMedia);
mediaImage.SetImageBitmap(GetImageBitmapFromUrl(Intent.Extras.GetString("MediaUrl", "")));
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
}
First thing you need to do is to set the your pending intent within the notification builder, it will get your NotificationActivity launching:
var builder =
new NotificationCompat.Builder(this)
.SetContentTitle("receivedNotification.Title")
.SetContentText("receivedNotification.Text")
.SetSmallIcon(Android.Resource.Drawable.IcDialogInfo)
.SetContentIntent(pendingIntent);
The second will be to get your back stack setup, from what you posted I'm not sure what the flow should be as the user will exit the app if they use the back button.
If you want the user to go back to the MainActivity when that press the back button, then you can add a ParentActivity to your NotificationActivity activity attribute, i.e.:
[Activity(Label = "NotificationActivity", ParentActivity = typeof(MainActivity))]
And thus the line:
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(NotificationActivity)));
Would add the MainActivity to the back stack.
I am trying to integrate Push notifications to the application.
The behaviour i am trying to implement is waking up the app from background and resuming to previous state.
But the control always come to protected override void OnCreate (Bundle bundle)
initially and then to OnResume upon tapping the notification message instead of coming
to protected async override void OnResume().
Because of this the app is always relaunching instead of waking up.
How can i just wake the app instead of relaunching when tapped on notification.?
Here is how the notification is created.
private void CreateNotification(string title, string desc, string type)
{
Random random = new Random();
int id = random.Next(9999 - 1000) + 1000;
const int pendingIntentId = id;
const int notificationId = id;
var startupIntent = new Intent(this, typeof(MainActivity));
var stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
stackBuilder.AddNextIntent(startupIntent);
var pendingIntent =
stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot);
var builder = new Notification.Builder(this)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(desc)
.SetSmallIcon(Resource.Drawable.appicon);
var notification = builder.Build();
notification.Flags = NotificationFlags.AutoCancel;
var notificationManager =
GetSystemService(NotificationService) as NotificationManager;
notificationManager.Notify(notificationId, notification);
}
Other scenarios like when the app is not running and in foreground are working as expected.