How to create a Bound Service in an Android app? - c#

I am basically working on a Xamarin.Forms (cross platform) Project which uses Portable Class Library. And I know I cannot run background services from PCL, so I need to get into each platform individually for that. Now I'm stuck in android.
What I need to create is a bound service. So when my app starts, I have 2 buttons, Start and Stop (disabled). I click on start (start button becomes disabled and stop button enabled) it sends a message to my android platform using MessagingCenter to start the service using an Intent and Bind To it.
So I have this in my MainActivity.cs
MessagingCenter.Subscribe<StartAppBoundServiceMessage>(this,
"StartServiceMessage", message =>
{
Intent objXPathServiceIntent = new Intent(this, typeof(XPathService));
StartService(objXPathServiceIntent);
connection = new XPathServiceConnection(this);
BindService(objXPathServiceIntent, connection, Bind.AutoCreate);
});
StartAppBoundServiceMessage is a simple class in my PCL.
Now when I leave my app(using home button or back button or maybe a call comes), I want it to unbind from my service- but my service should still go on. That is why I have started my service using StartService(). But again when it is unbinding it should preserve somethings (like settings that are being used in the service) that had been set from my UI.
The next time when I come back my application should check if my service is running, if it is (it must bind to it again and let me make setting changes or stop the service by clicking on the stop button etc).
I have 2 questions:
I am confused on where I should UnBind when my app is leaving foreground, and where to Bind when coming back again. I know how to check if my service is running already, but i dont know where to check it. because back button calls onCreate and home button calls onResume.
How to preserve these settings in my service and put them back into my UI when I comeback.
PS: All my service methods will be called from my PCL project.
Note: The requirements are somewhat like a music player but the app is no where close to it.

Related

Why can't a windows service created in C# detect that a screen saver is currently running?

As part of some work I need to get done for Windows 10, I have written a code in C# that essentially detects every minute whether a PC is in screen saver mode or not, and it writes to a table in MySQL the relevant status ("PC in use" if the screen saver is off, "available PC" if the screen saver is on).
I did this using (full link if required - https://www.codeproject.com/Articles/17067/Controlling-The-Screen-Saver-With-C):
// Returns TRUE if the screen saver is actually running
public static bool GetScreenSaverRunning( )
{
bool isRunning = false;
SystemParametersInfo( SPI_GETSCREENSAVERRUNNING, 0,
ref isRunning, 0 );
return isRunning;
}
The code works flawlessly in console application mode (I made a loop to test it out over a minute with a check up on screen save status every 10 seconds), this means in MySQL the status was set correctly every time, depending on the screen save status at the moment of the check up.
The problem occurs when I use this code for a windows service. The service is installed correctly, the log on tab is set on Local System (I also tried with the logged in user instead, same results) and I allow the service to interact with the desktop, just in case, but the difference here is that no matter if the PC enters screen save or not, it always returns false on GetScreenSaverRunning(), thus setting the status of the PC in MySQL as "PC in use", even if the screen saver is on at the moment of check up.
I get the sense that the problem isn't in the code itself, since it works without any issues as a console application, but perhaps something behind the scenes. I tried to search here and on many other websites, haven't found anything related to such a problem.
Does anyone have any idea at all what might be the issue? Any help and/or suggestions will be greatly appreciated!
Thank you in advance.
(I could post the code if required, but it is pretty much straight forward and the main part of it, controlling the screen save detection, is taken from the website mentioned above, afterwards it's a simple if (GetScreenSaverRunning() == true) )
Ever since Vista, Services are barred from a Interactive Session. Even if they run under the same rights, they do not get a interactive Session. I would guess that is getting in the way here.
While you can overwrite this behavior in the Service settings, this is not adviseable for new code. Consider making this a Background Task started by the Task Sheduler instead.
Because the windows service runs in different session then the windows logon. You can't interact with the desktop related services unless you run the windows service in win logon session. There used to be an option in Windows service manager where you can set the properties to "Interact with desktop session" but I don't think that ever worked.
There's a work around to run the windows service using the win logo session.
See this helper class that can get the current logged on user session and interact with the desktop services. https://github.com/murrayju/CreateProcessAsUser/blob/master/ProcessExtensions/ProcessExtensions.cs

How to quit a unity app which is opened by URL SCHEME and go back to the main app?

I have a IOS app which show product details and for the AR section it opens another unity app.What I want to do is Quit the Unity app and go back to same page in the main app.I have used the following code.
public void BackHome()
{
Application.Quit();
}
The problem with this code is it quits like termination not smooth closing of app.Also it goes directly to the Home screen not to the app (that is main app page from where the Unity App opened up).What I want to do is open Unity app from the main app and after that while hitting a back button would like to close the unity app and return to the main app.
In player setting in Unity I have given Behaviour in BackGround - Exit.
Before Application.Quit, try open main app by URLSCHEME: Application.OpenURL("XXXXXX").

How to create a UWP application which only opens a specific url

I want to create a UWP application which only opens a specific url in the browser. So I mean that this app will have an icon in the start menu but when a user clicks this icon nothing happens but only my url is opened in the browser. Is it possible? How to implement such UWP application?
I created an App class and in OnLaunched method I wrote this code:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
var task = Windows.System.Launcher.LaunchUriAsync(new Uri("https://stackoverflow.com")).AsTask();
task.Wait();
CoreApplication.Exit();
}
This works fine. The only problem is that white window of my app is opened and closed after about 1 second.
Update 1:
The main purpose of my app is to work as an appservice. Another component of my system successfully communicates with it. If it is possible not to show the icon in the start menu at all it would be great solution. However, I don't know how to hide my app from the start menu. So another appropriate solution for me is just to open the url of my specific web site without showing a splash window once a user clicks the icon in the start menu.
I don't care about certification in the store.
Even if you can successfully implement such behavior, the app window and splash screen will still display (even if just for a while) and the app will definitely not pass Microsoft Store submission (because it exits during launch and it brings no additional value over the website itself)

How to resend args to an app if its already running and have it refresh with those args

I have an issue. I'd have a video player that takes in simple parameters as a c# form app. As an experiment to better understand programming, I'd like to have only one instance of the app running and have it refresh with the new args if the open command is given. I could program it so that when it gets the signal, to refreshVideo() or something like that.
Pseudo example:
//app is started from cmd line
//open app for first time
vidViewer.exe("lotr.avi", "44:44");
//keep instance open but have it refresh with new movie
vidViewer.exe("star_wars.avi", "22:32")
As it stands right now a new app with embedded video player will open, so I could have 100 open flicks if I passed it enough args. I'd just like to keep it at one.
Can provide more info if needed.
Thanks all,
Kevin
My suggestion would be to design your application such that, when launched, it would attempt to acquire a system resource that is mutually exclusive (meaning that only the first instance would succeed). Since, in your scenario, you will also require a means of interprocess communication (to transmit the name and start-time of new videos), you may use the same mechanism for achieving this.
You could, for example, use a self-hosted WCF service, bound to a fixed TCP port, that each application instance attempts to register upon being started. Due to the way ports work, only the first instance will succeed; subsequent instances would fail with a “port already in use” exception.
If an instance manages to register the WCF service, then you may assume it to be the “principal” instance and proceed to play the video on it. It should, however, listen for incoming messages from the WCF service and update the video being played accordingly (see below).
If an instance finds that the port is already in use, it should assume that another instance is already running. It would then initialize a WCF client that sends the name and start-time of the new video to be played to the WCF service. Finally, it should terminate itself without displaying any window, assuming that the principal instance will take care of playing its video.

how to test WPF forms?

I'm writing complex application where are server and client application, if i want to add some new window in my application i need to run server, then run client, then login click few buttons before i reach window which i right now developing, it's annoying and takes much time. So now i'm looking for some solution where i can run test which can run only my wpf form using mock for services (so i don't need running server and don't need to login), can click or fire events and check controls appear and act the way i want.
In this case i can save a lot of time because i dont need to waste time when i try to reach my form by running whole application where i need to use login, search bypass some validation forms and etc.
If there is already simple solution then it will be great.
Take a look at the MVVM pattern.
MVVM for WPF
Are you using any kind of dependency injection? It would be easy if so, you could simply create fake version of your heavy service using mocking framework with combination of #if-else directives. Somewhere in your application startup code:
ILoginService service;
#if DEBUG
service = A.Fake<ILoginService>();
// you could even set up your fakes to return logged user to
// automate logging in process:
var userFake = A.Fake<IUser>();
A.CallTo(() => service.LogIn(A<string>.Ignored)).Returns(userFake);
#else
service = new RealLoginService();
#endif
var myWindow = new MyWindow();
var viewModel = new ViewModel(service);
myWindow.DataContext = viewModel;
// ...
All you need is ViewModel (assuming you use such) being able to take ILoginService dependency. Then you can mock/fake it up to your liking.

Categories

Resources