Change Android default notification sound based on time - android-notifications

I was wondering if it is possible to programmatically change the default notification sound on an Android phone based on what time it is. For instance, I would like the default notification sound to change to Silent after 11PM and then back to a sound at 8AM. I have a working knowledge of Java, but have never done any Android development. Thanks in advance for any help.

Without going too much into detail, I would approach this problem by first creating an AlarmService which will run periodically and change default Ringtone according to your desired time of the day via RingtoneManager
AlarmManager setting up periodical invocations of "RingToneChanger.class" , something like this:
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
Then within triggered RingToneChanger.class, ringtone can be changed like this:
if(isNoon) {
RingtoneManager.setActualDefaultRingtoneUri(Context context, RingtoneManager. TYPE_NOTIFICATION , Uri lunchtimeNotificationSound);
} else {
RingtoneManager.setActualDefaultRingtoneUri(Context context, RingtoneManager. TYPE_NOTIFICATION , Uri defaultNotificationsound);
}
Hope it helps. else please don't hesitate to ask.

Related

Xamarin Forms Prism DialogService takes some seconds to show up

My Dialog is a simple Frame with an Image, a label to display a question and two more labels (Yes / No) with TapCommand.
I've set up the container with the DialogPage.xaml and DialogPageViewModel and injected in the ViewModel I want to open the dialog.
Here is the code I'm using to call the Dialog:
public void ShowDialog()
{
_dialogService.ShowDialog("DiscardPopup", CloseDialogCallback);
}
void CloseDialogCallback(IDialogResult dialogResult)
{
var goBack = dialogResult.Parameters.GetValue<bool>("GoBack");
if (goBack)
NavigationService.GoBackAsync();
}
If the user taps over the "Yes label", I execute this command:
YesCommand = new DelegateCommand(() => YesTapped());
private void YesTapped()
{
IDialogParameters pa = new DialogParameters();
pa.Add("GoBack", true);
RequestClose(pa);
}
If the user taps over the "No label", I simply call:
NoCommand = new DelegateCommand(() => RequestClose(null));
The "problem" is when the ShowDialog is fired, the DiscardPopup is taking up to 3 seconds to show up.
Is there a way to make it faster?
The same happens with the TapCommands, 2 - 3 seconds when the RequestClose is invoked.
Without actual code telling you exactly what the issue is, is going to be best guess. Based on your feedback to my comments above I would suggest the following:
Try displaying the dialog on a test page that doesn't have a complex layout. My guess is that you won't see such a long load time. If that's the case this would point to your layout being overly complex and that the lag time is due to the device struggling to re-render the View
Try using Prism.Plugin.Popups. You'll need to initialize Rg.Plugins.Popup and register the DialogService. You can see docs on that at http://popups.prismplugins.com

alarm manager local notification - how to cancel specific notification?

i am scheduling my customer through alarm manager to get notification on time that i set. Now everything is working fine i get local notification, but i am not able to cancel that specific notification its keep coming after every minute.
here is my viewmodel code PCL
for cancel :
void Switch_Toggled()
{
if (NotificationONOFF == false)
{
MessageText = string.Empty;
SelectedTime = DateTime.Now.TimeOfDay;
SelectedDate = DateTime.Today;
DependencyService.Get<ILocalNotificationService>().Cancel(Convert.ToInt32(Settings.Customerid));
}
}
for save alarm
DependencyService.Get<ILocalNotificationService>().LocalNotification("Local Notification", MessageText, Convert.ToInt32(Settings.Customerid) , selectedDateTime);
code in xamarin.android
for canel:
public void Cancel(int id)
{
var intent = CreateIntent(id);
var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
var alarmManager = GetAlarmManager();
alarmManager.Cancel(pendingIntent);
var notificationManager = NotificationManagerCompat.From(Application.Context);
notificationManager.CancelAll();
notificationManager.Cancel(id);
}
i am sending customer id to cancel but its not working.
According to your description, you have xamarin.forms sample, sending Local Notification With A Repeat Interval using Alarm Manager, like this sample:
https://www.c-sharpcorner.com/article/how-to-send-local-notification-with-repeat-interval-in-xamarin-forms/
There are two solution, but I don't know what you are.
Solution 1:
When you run project and set one alarm Manager to send local notification with a repeat interval, this app is background now.
When time is up, you go into this background app, you find switch is unselect, but alarm still exist. So you want to cancel this alarm when you go into this app, am I right?
If yes, I suggest you can call Switch_Toggled() event in LocalNotificationPageViewModel constructor.
public LocalNotificationPageViewModel(){
SaveCommand = new Command(() => SaveLocalNotification());
Switch_Toggled();
}
Solution 2:
If you run project and set one alarm Manager to send local notification with a repeat interval, and this app still active, now time is up, you can unselect switch to cancel this alarm, it works fine.

Unity Time for calculating session length

Is there a way of registering time when you exit a Unity application (i.e. you press play and stop the app) or perhaps when you exit a standalone build?
Using the following simple line of code, I can write to the console when my start button was pressed, so I wonder if I could do the same when the app is quit, so that the difference would be the length of the session?
Debug.Log("Start Button pressed # " + DateTime.Now);
At the End of Application you can Save your Session Time. And In Start Method you can Load it From PlayerPrefsto use it.
Like This :
void OnApplicationQuit()
{
DateTime time = new DateTime();
time.AddSeconds(Time.realtimeSinceStartup);
PlayerPrefs.SetString("SessionTime",time.ToBinary().ToString());
}
void Start()
{
DateTime time = new DateTime();
string timeString = PlayerPrefs.SetString("SessionTime","");
if(timeString != "")
{
Convert.ToInt64(timeString);
time = DateTime.FromBinary(time);
Debug.Log("Previous Session Time : " + time.ToString());
}
}
You can also achieve this by using System.DateTime.Now and storing it in some variable at start. and getting Session Time at End by subtracting saved time from System.DateTime.Now. I hope its Helpful :)
You can use Time.realtimeSinceStartup to get the number of seconds since the application was start. Furthermore, OnApplicationQuit will be called (on any MonoBehaviour that implements it) when the application is closed. I am not completely sure it works in the editor but I think it would.
void OnApplicationQuit() {
Debug.Log(Time.realtimeSinceStartup);
}
I hope that helps!

Using Campaign Monitor's API

I am looking for a way to use Campaign Monitor's API in my ASP.NET/VB Web application.
I have not used any API before, thus reading their documentation is very difficult to understand.
If anyone has used it and is able to provide some instructions I would appreciate it; or if someone has some general usage instructions (if applied on any APi), be my guest! :)
I know this is not the typical "I have a problem and this is my problem and here's my effort so far" but any help would be much appreciated.
You can also use the Campaign Monitor API client library which is available on Nuget:
AuthenticationDetails auth = new ApiKeyAuthenticationDetails(apiKey);
var fields = new List<SubscriberCustomField>() {
new SubscriberCustomField() { Key = "MyCustomField", Value = myVal }
};
var subscriber = new Subscriber(auth, listId);
subscriber.Add(email, fullName, fields, false);
I use campaign monitor for populating subscriber lists.
There are two methods to post your subscribers to lists. I'm going to stick to the simplest one. Let's round up somethings you need first.
You'll need an API key (which I am sure you have).
You'll need to create a subscribers list and after you create this
list you'll need the list ID. To get the ID (which is wierd).You'll
need to click into your subscriber list. This look for this towards
the top. Single opt-in list (change name/type) Note: You are not
going to change the name or edit anything but you have to click in
here to get the ID. On the third section you will see this: API
Subscriber List ID. If you're using the API, you'll need this ID to
access this list. 000x0000xx0x0xx00x00xx (just an example.)
You'll need a form to capture Name and Email. You'll need your listid which
you got in the previous point.
Then you'll need to code a communication object.
If you are doing a straight forward call you'll need the name, email, and listid.
ListID ="000x0000xx0x0xx00x00xx";
Email ="JoeM#somethingemail.com";
Name = "Joe Middle";
APIKey = yourAPIKey;
APIURL = "http://api.createsend.com/";
ApiCall = variables.APIURL;
ApiCall &= "api/api.asmx/Subscriber.Add?ApiKey=" & variables.APIKey;
ApiCall &= "&ListID=" & URLEncodedFormat(arguments.ListID);
ApiCall &= "&Email=" & URLEncodedFormat(arguments.Email);
ApiCall &= "&Name=" & URLEncodedFormat(arguments.Name);
Once you have your url build you use whatever method .net uses to post http.
Then you'll want to code for success or fail and do something with that info. post to http and call the result. apiResult.
apiResult = xmlParse(apiResult.fileContent);
try {intCount = ArrayLen(apiResult.Result.XMLChildren);}
catch(Any e){intCount = 0;}
if (intCount gt 0){apiResult = apiResult.Result.xmlChildren;}
// Error handling
if ( apiResult[1].xmlName eq "Code" and apiResult[2].xmlName eq "Message" ){
returnStruct['blnSuccess'] = 0;
returnStruct['errorCode'] = apiResult[1].xmlText;
returnStruct['errorMessage'] = apiResult[2].xmlText;
}
// Success
else {
// Return str
returnStruct['blnSuccess'] = 1;
returnStruct['returnString'] = apiResult.Result.xmlText;
}
The code above was adapted from coldfusion and I didn't build it but it is cfscript which is not CFML and you can kind of interpret what is happening.
If you adapt this to .NET then all you are missing is your HTTP call stuff method.
To check log into Campaign Monitor and click on your list. You should see additions showing up, if not it is either you API key (not usually the case), your listID (could be the case), your code (most likely culprit).
This was hammered out in a hurry so apologies if the flow is weird.
Good luck!

How can I reliably wait for JavaScript alerts using Selenium2 / WebDriver?

I am currently assisting in a proof of concept using Selenium 2 / WebDriver with C# against an ASP.NET MVC application using the InternetExplorerDriver.
The application uses a standard pattern for notifying users that a record has saved. This works by settings TempData to include "Record saved successefully", and if TempData is present in the View, the view will alert the message.
Whilst working on Selenium tests for this functionality, we are receiving inconstitant behaviour from the below C# / Selenium test code:
_driver.Navigate().GoToUrl(_baseUrl + "/Amraam/List");
_driver.FindElement(By.LinkText("Create New")).Click();
_driver.FindElement(By.Id("txtAmraamSerialNumber")).SendKeys("CC12345");
var selectElement = new SelectElement(_driver.FindElement(By.Id("LocationId")));
selectElement.SelectByText("Tamworth");
_driver.FindElement(By.Id("btnSave")).Click();
var wait = new WebDriverWait(_driver, defaultTimeout);
IAlert alert = wait.Until(drv => drv.SwitchTo().Alert());
_alertText = alert.Text;
alert.Accept();
Assert.That(_alertText, Is.EqualTo("Record successfully saved"));
Approximately 50% of the time, Selinium will fail with a
OpenQA.Selenium.NoAlertPresentException : No alert is active
I struggle to find an exact way to replicate the issue, and worry regarding the inconsistency aspect. If it failed consistently, then we could debug and track the problem down.
The handling of alerts and prompts within Selenium 2 is pretty new and is still under active development.
Your failures are probably due to timing, so I would suggest writing a wrapper method around the call to SwitchTo().Alert() so that you catch the OpenQA.Selenium.NoAlertPresentException and ignore it until the timeout expires.
Something as simple as this should work:
private IAlert AlertIsPresent(IWebDriver drv)
{
try
{
// Attempt to switch to an alert
return drv.SwitchTo().Alert();
}
catch (OpenQA.Selenium.NoAlertPresentException)
{
// We ignore this execption, as it means there is no alert present...yet.
return null;
}
// Other exceptions will be ignored and up the stack
}
This line
IAlert alert = wait.Until(drv => drv.SwitchTo().Alert());
would then become
IAlert alert = wait.Until(drv => AlertIsPresent(drv));
Hope this will be helpful for waiting and click
WebDriverWait(driver,4).until(EC.alert_is_present())
driver.switch_to.alert.accept()

Resources