i'm working on an android app at the moment that has the purpose of playing a particular song at exactly midnight. I know that there might already be apps in the appstore that serve that purpose, but I'm new to coding and wanted to try to program the app myself.
So now I reached the point where I don't know what to do anymore. I tried debugging the App on my LG H818P running Android 6.0. It posted, The Icon, the Name and everything were correct, but i didn't play the song, even when i set the time when it should've played it to two minutes after the start if the building.
So that's the code of the MainActivity.cs in Visual Studio 2017, can anyone find any errors?
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using Android.Media;
namespace Name of the App
{
[Activity(Label = "Name of the App", MainLauncher = true)]
public class MainActivity : Activity
{
string text = "status";
protected void onCreate(Bundle savedInstanceState)
{
}
public void main()
{
try
{
string systemtime = DateTime.Now.ToString();
for (int i = 0; i > 0; i++)
{
if (systemtime == "09:07:00 pm")
{
StartPlayer();
player.Start();
}
}
}
catch
{
text = "Error!";
}
}
protected MediaPlayer player;
public void StartPlayer()
{
if (player == null)
{
player = new MediaPlayer();
player.SetDataSource("Ressources.raw.file2beplayed.mp3");
player.Prepare();
player.Start();
text = "Playing!";
}
else
{
player.Reset();
player.SetDataSource("Ressources.raw.file2beplayed.mp3");
player.Prepare();
player.Start();
}
}
}
}
As I said, I'm a Noob in coding, so sorry for the maybe ugly code :)
Thanks for your replies!
The default format for ToString in a DateTime is MM/dd/yyyy, so your comparation systemtime == "09:07:00 pm" will never be true.
You can use a TimeSpan and the property TimeOfDay from DateTime;
if(DateTime.Now.TimeOfDay == new Timespan(21,7,0))
//...
Also, your loop will never be executed as you initialize i as 0, so at the first check i will not be greater than 0 so the loop isn't executed.
Finally, Android does not use the main function, is an special type of program, your initialization code should be in the OnCreate function, but if you create an infinite loop in that function Android will close the application as it will not finish it's initialization, you need to use a timer and check the condition each second.
Related
I was trying to change the brightness of my iOS app using a text entry box, and I found some stuff online which showed me how to create a dependency service and use UIScreen to set the brightness of the app so that is what I did.
Here is the interface:
public interface IBrightnessService
{
void SetBrightness(float factor);
}
Here is the code for actually calling the setBrightness, where I'm doing it based on a Xamarin Entry form(text is inputted, and when enter is pressed this method is called).
void Entry_Completed(object sender, EventArgs e) {
var text = ((Entry)sender).Text; //cast sender to access the properties of the Entry
float value = float.Parse(text);
var brightnessService = DependencyService.Get<IBrightnessService>();
brightnessService.SetBrightness((float)value);
}
Here is the implementation in iOS. I tested some stuff, and the value is being sent correctly and the method is being reached, but the line of code UIScreen.MainScreen.Brightness = brightness; doesn't actually change UIScreen.MainScreen.Brightness, and I can't seem to figure out why, so was looking for help for this.
using Xamarin.Forms;
using UIKit;
[assembly: Dependency(typeof (iOSBrightnessService))]
public class iOSBrightnessService : IBrightnessService
{
public void SetBrightness(float brightness)
{
UIScreen.MainScreen.Brightness = brightness;
}
}
The iPhone simulator brightness is not adjustable, you have to try in a real device!
I can't get OnNewIntent to fire. I've read dozens of articles on the issue and tried all combinations of code.
Regardless of whether I use LaunchMode.SingleTask or SingleTop it won't fire and always passes through the OnCreate method.
What am I doing wrong here? Am I missing something? What do I need to add to get it to work?
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using static MyApp.ClipboardMgr;
namespace MyApp.Droid
{
//[Activity(Label = "SplashActivity")]
[Activity(LaunchMode = LaunchMode.SingleTask, Theme = "#style/Theme.Splash",
MainLauncher = true, NoHistory = true)]
//Can't get this to work with LaunchMode.SingleTop or SingleTask. Always creates a new instance.
[IntentFilter(new[] { Intent.ActionProcessText },
Categories = new[] { Intent.CategoryDefault },
DataMimeType = #"text/plain", Icon = "#drawable/icon", Label = "MyApp")]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
//taking these out for readability
//AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
//TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
//AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
base.OnCreate(savedInstanceState);
// Create your application
StartActivity(typeof(MainActivity));
//don't want to do this here, better to do it in event
if (Intent.Action == Intent.ActionProcessText)
{
//always comes here
HandleProcessTextIntent();
}
}
catch(Exception e)
{
App.LogException(e);
throw;
}
}
/// <summary>
/// this is not firing!
/// </summary>
/// <param name="intent"></param>
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
HandleProcessTextIntent();
}
void HandleProcessTextIntent()
{
string input = Intent.GetStringExtra(Intent.ExtraProcessText).Trim();
if (input == string.Empty)
return;
ClipMgr.SetText(input);
}
}
}
You didn't miss anything since when I test with my own intent to start your activity, it works well and the OnNewIntent() is called when SingleTask or SingleTop used, here's how I call the activity from another project(I did this in native Android):
ComponentName component = new ComponentName("com.example.textHandlerDemo", "com.example.textHandlerDemo.TextHandlerActivity");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PROCESS_TEXT);
intent.setComponent(component);
startActivity(intent);
I did some research and find something that may explain why the OnNewIntent() never gets fired:
According to the guidance of ACTION_PROCESS_TEXT, it mentioned:
You can use this as a hint to offer the ability to return altered text to the sending app, replacing the selected text. This works as your Activity was actually started with startActivityForResult()
So, when you click your app's label in the floating text selection toolbar, Android will start your activity registered with ActionProcessText with startActivityForResult(), and by using startActivityForResult(), your activity will be started as a sub-activity of current activity(implied from Android doc of startActivityForResult), that is to say, rather than redirecting to your app which is already running, Android will put your activity into current app's stack.
This way, your target activity will still be called from OnCreate() since it's isolated from your running app.
Moreover, the floating text selection toolbar is used to provide a quick in-app experience for text operations like translation as mentioned in this blog, I didn't find any swich to enable/disable redirect to app, you may need to handle the intent in both OnCreate() and OnNewIntent() if you're using LaunchMode.SingleTask or SingleTop.
Im writing a Netduino 3 program that will control turn lights and other relays for hayrides. My program was written before I got the device, so Im not sure how well it will work, but Im already having a problem with one of the buttons (hazardButton). When applying 3.3v it doesn't cause the interrupt to trigger. Applying 5v does the same, however when applying GND it triggers the interrupt, but when re-applying GND it doesn't turn off the interrupt.
Here's my code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace Tractor_Mate
{
public class Program
{
static InterruptPort hazardButton = new InterruptPort(Pins.GPIO_PIN_D0, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
static OutputPort hazardLights = new OutputPort(Pins.ONBOARD_LED, false);
static bool hazardsActive = false;
public static void Main()
{
Debug.Print("Initializing Inputs... ");
hazardButton.OnInterrupt += new NativeEventHandler(hazardButton_OnInterrupt);
Thread.Sleep(Timeout.Infinite);
}
static void hazardButton_OnInterrupt(uint data1, uint data2, DateTime time)
{
while (data2 == 0)
{
hazardLights.Write(true);
Thread.Sleep(500);
hazardLights.Write(false);
Thread.Sleep(500);
hazardsActive = true;
}
hazardsActive = false;
}
}
}
Im getting the problem with the Hazard Lights and haven't tried any of the others yet. Im wiring the buttons up so that when the pin goes HIGH it will trigger, and then when LOW it turns it off.
public class Program
{
static InterruptPort hazardButton = new InterruptPort(Pins.GPIO_PIN_D0, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
static OutputPort hazardLights = new OutputPort(Pins.ONBOARD_LED, false);
static volatile bool hazardsActive = false;
public static void Main()
{
Debug.Print("Initializing Inputs... ");
hazardButton.OnInterrupt += new NativeEventHandler(hazardButton_OnInterrupt);
bool lightOn = true;
while (true)
{
if (!hazardsActive)
{
hazardLights.Write(false);
}
else
{
hazardLights.Write(lightOn);
lightOn = !lightOn;
}
Thread.Sleep(500);
}
}
static void hazardButton_OnInterrupt(uint data1, uint data2, DateTime time)
{
hazardsActive = !hazardsActive;
}
}
I'm unable to test this since I don't have the Netduino SDK installed (I have a NetDuino, but its been a while since I played with it). The principle is pretty easy:
The interrupt only toggles the hazards being on or off. The variable is marked volatile because it can be set from multiple threads and it needs to be read from the register not a thread cache, so volatile tells the compiler not to optimize it.
The main method has an infinite loop that examines if the hazards are on or off. When the hazards are off (first part of the if), it writes false to the output pin (presumably turning the lights off, unless the pin is inverted).
When the hazards are on (else part), it writes a value to the pin then inverts the value so the next time it turns it off, then on, then off, etc. The last part of the loop just waits 500ms before looping again.
Note
Depending on the "quality" of the contacts in the button you are using, you may need to add debouncing logic to the interrupt handler. "Bouncing" is a phenomenon with switch contacts (or any other mechanical contact) that can cause the contact to open/close many times very quickly when changing state. This is due to the electrical signal bridging the gap as the contacts are very close to each other (think static electricity jumping a gap). A lot of times this is handled on the hardware side by a capacitor, but I'm not sure for the Netduino how it handles it.
I am trying to have a Windows service run all the time in the background of my computer with no-one knowing. My Windows service downloads the content of my email inbox and puts it in my database.
My Windows service just seams to stop - it enters a log every 60 seconds and then stops about 10 mins in?
I have posted my code below. Can any one see or tell me a reason why?
Any help would be much appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace EmailWindowsService
{
public partial class MyEmailService : ServiceBase
{
private DateTime lastRun;
private bool flag = true;
private static System.Timers.Timer aTimer;
public MyEmailService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource")) // every thing the windows service does is logged in server explorer
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLogEmail.Source = "MySource";
eventLogEmail.Log = "MyNewLog";
// Timer Code
aTimer = new System.Timers.Timer(1 * 60 * 1000); // 60 seconds
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
// Timer Code
}
protected override void OnStart(string[] args)
{
flag = true;
lastRun = DateTime.Now;
eventLogEmail.WriteEntry("Started");
}
protected override void OnStop()
{
eventLogEmail.WriteEntry("Stopped");
}
protected override void OnPause()
{
eventLogEmail.WriteEntry("Paused");
}
protected override void OnContinue()
{
eventLogEmail.WriteEntry("Continuing");
}
protected override void OnShutdown()
{
eventLogEmail.WriteEntry("ShutDowned");
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
RetriveEmailClass Emails = new RetriveEmailClass();
if (flag == true)
{
eventLogEmail.WriteEntry("In getting Email Method");
Emails.ServiceEmailMethod();
lastRun = DateTime.Now;
flag = false;
}
else if (flag == false)
{
if (lastRun.Date < DateTime.Now.Date)
{
Emails.ServiceEmailMethod();
eventLogEmail.WriteEntry("In getting Email Method");
}
}
}
}
}
See that your class has no errors, an error there could throw you whole service out.
Also try putting your timer into a method and only call it, not have it in your service code.
A windows service should always be made as an empty shell that just call's methods.
Couple of reasons that your Windows services stops running.
1. Unhandled exception in your code. Looking from you code snippet, please add exception handling in the OnTimedEvent() method.
2. You service may crashed for some reason. In this case, you can go to event viewer to find out the reason for the failure.
Hope this helps.
You most likely have an unhandled exception. It's hidden since you use System.Timers.Timer. That timer eats all unhandled exceptions instead of letting them crash your app.
That means that your app might look like it's running OK while it's not. A try/catch in the timer callback will prove that.
I do recommend that you use System.Threading.Timer instead since it do not work in that way.
Your code is straightforward enough except the source for your Emails.ServiceEmailMethod method. Does the method generate any exceptions? If so, they have not been trapped in your timer method. Try:
try { Emails.ServiceEmailMethod(); }
catch (Exception ex) { eventLogEmail.WriteEntry(ex.Message); }
I'm working on setting up an alarm that pops up as a dialog with multiple sound file options the user can choose from. The problem I'm having is creating a sound player at the local level that I can close with a button. The problem I'm having is that the sound keeps looping when I close the form because the SoundPlayer doesn't exist within the button click event.
here's what I have:
void callsound()
{
if (SoundToggle == 0) // if sound enabled
{
if ((SoundFile == 0) && (File.Exists(#"attention.wav")))
{
System.Media.SoundPlayer alarm = new System.Media.SoundPlayer(#"attention.wav");
alarm.PlayLooping();
}
if ((SoundFile == 1) && (File.Exists(#"aahh.wav")))
{
System.Media.SoundPlayer alarm = new System.Media.SoundPlayer(#"aahh.wav");
alarm.PlayLooping();
}
}
private void button1_Click(object sender, EventArgs e)
{
//alarm.Stop(); Only works if SoundPlayer declared at class level
this.Close();
}
Is there a way I can do what I want to do by declaring the SoundPlayer instances where I am? Or is there a way to declare it at the class level, and still be able to change the sound file based on user settings?
Why is this a problem? SoundPlayer doesn't support playing more than one sound at the same time anyway. Move it to class scope, override OnFormClosing event, problem solved.
public partial class Form1 : Form {
private System.Media.SoundPlayer alarm;
protected override void OnFormClosing(CancelEventArgs e) {
if (alarm != null) alarm.Stop();
}
}
You can try:
SoundMixer.stopAll();
or
SoundMixer.soundTransform = new SoundTransform(0);
The SoundMixer class controls global sound, so it should stop everything in the same security sandbox.
Using Powershell, I was playing with playing .wav files and started a repeating loop using the following:
$Playwav = new-object ('Media.SoundPlayer') $playpath1
$Playwav.PlayLooping()
I stopped the loop inside Powershell IDE by Run Section (F8):
$Playwav = new-object ('Media.SoundPlayer') $playpath1
$Playwav.PlayLooping()
$Playwav.stop()
FWIW, the .wav in my example was FPS Doug takethatbitch.wav. So the runaway loop made me laugh.
Hope this helps.