Xamarin wakelock - xamarin

I use PowerManager.WakeLock in my project to keep running my app in sleep mode, it is working great but this consumes a lot of energy and the device gets hot. What else should I do to keep my app running without a lot of energy?
My codes
PowerManager.WakeLock wakelock = default;
PowerManager pmanager = (PowerManager)GetSystemService("Power");
wakelock = pmanager.NewWakeLock(WakeLockFlags.Partial, "test");
wakelock.SetReferenceCounted(false);
wakelock.Acquire();

Related

Cannot run cmd.exe through service. No commands appear to be working [duplicate]

Hey, I am trying to get a service to start my program but it isn't showing the GUI. The process starts but nothing is shown. I have tried enabling 'Allow service to interact with desktop' but that still isn't working.
My program is a computer locking device to stop unauthorised users from accessing the computer. I am running windows 7 with a 64 bit OS.
Here is the code for my service:
protected override void OnStart(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "notepad.exe";
p.Start();
FileStream fs = new FileStream(#"C:\Users\David\Documents\Visual Studio 2010\Projects\LockPCService\LockPCService\bin\Debug\ServiceLog.dj",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" LockPCService: Service Started " + DateTime.Now + "\n" + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
FileStream fs = new FileStream(#"C:\Users\David\Documents\Visual Studio 2010\Projects\LockPCService\LockPCService\bin\Debug\ServiceLog.dj",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" LockPCService: Service Stopped " + DateTime.Now + "\n"); m_streamWriter.Flush();
m_streamWriter.Close();
}
To try and get the service working I am using notepad.exe. When I look at the processes notepad is running but there is no GUI. Also the ServiceLog is there and working each time I run it.
Any ideas on why this isn't working?
Thanks.
This article explains Session 0 Isolation which among other things disallows services from creating a UI in Windows Vista/7. In your service starts another process, it starts in Session 0 and also will not show any UI. (By the way, the UI is created, it's just that Session 0 is never displayed). This article on CodeProject can help you create a process from a service on the user's desktop and show its UI.
Also, please consider wrapping you stream objects in a using statement so that they are properly disposed.
Services run under different account so notepad is run by another user and on another desktop so that's why you cannot see it. 'Allow service to interact with desktop' is not supported anymore starting from Vista.
I know this is a late post, but I found that this article was very helpful to me. I am running Windows 7 and the solution provided in this article works great.
If you download the code, there is a class called ApplicationLoader. Include that class in your project and then it's as simple as this:
// the name of the application to launch
String applicationName = "cmd.exe";
// launch the application
ApplicationLoader.PROCESS_INFORMATION procInfo;
ApplicationLoader.StartProcessAndBypassUAC(applicationName, out procInfo);
Services run in a different logon session and have a different window station from the user. That means that all GUI activity is segregated from the user's programs, not that the service can't display a GUI. Actually, this design makes it much easier to temporarily block access to the user's programs.
You'll need to call SwitchDesktop.

Pusher/Laravel Echo stops working on Ionic 3.9.2 intermittently

Normally it works.
When I create an appointment on the Laravel webapp, the Ionic mobile app's listview updates in real-time with the new appointment (thru Laravel Echo and Pusher).
...
#Injectable()
export class UpdateService {
private echoStarted: boolean;
private channel: string = null;
private dataChanged = new Subject<void>();
public dataChanged$ = this.dataChanged.asObservable();
constructor(private auth: AuthService) {
window.Pusher = require("pusher-js");
if (this.auth.isLoggedIn()) {
this.startEcho();
}
this.auth.authenticated$.subscribe(status => {
if (status) {
if (!this.echoStarted) {
this.startEcho();
}
} else {
this.stopEcho();
}
});
}
...
But at some point the real-time listener just stops completely and continues to not work until I hard-refresh the mobile page or reset the mobile app. In other words, when I create a new appointment, the mobile app listview just sits there with no automatic update.
This problem seems to be reproduced when switching to another mobile app then coming back, or when putting the mobile app in background mode (pressing phone power button then coming back in). Happens on both Android and iOS.
This problem does not occur with the real-time updates on the webapp's front-end Pusher implementation.
So I'm suspecting this is a mobile app code issue, and hopefully not a fundamental stability problem with Ionic and Pusher.
Maybe something to do with the OnResume trigger where the real-time listener/process is getting doubled up and failing? Or maybe the listener/process fails as it was receiving some new data but going into background mode? The intermittent failure is what makes this issue thorny to think about.
Wondering if you've experienced a similar issue. Any illumination is greatly appreciated.

Implement service on Firefox OS

I'm quite new to Firefox OS. At the moment I'm struggling with implementing some kind of service that listens for geolocation updates in the background.
If there are lots of apps running at the same time mine seems to be killed. While debugging with App Manager it disconnects silently.
I tried requestWakeLock('cpu') and the use of a Worker (as proposed in this thread) but without success.
Background services API isn't implemented, yet and will be available for certified apps only.
I know that there are non-certified apps like ConnectA2 that stay alive all the time so there has to be a way.
Could anybody give me a hint?
Firefox OS doesn't provide a way for you to run a service in the background intentionally, since the classes of the devices that we target (for example, the 128MB device) won't be able to support running apps constantly in the background.
There are alternate ways of implementing these kinds of services though. For example you can use the mozAlarm API in order to wake up your application at specific intervals, or you can use the SimplePush API which allows you to notify your app when a remote server initiates an event.
You can use Alarm API to prevent your app to be killed in the background.
Alarms wakes up the app at fixed intervals.
var alarmId = 0;
function setAlarm() {
function onAlarmAdded() {
alarmId = request.result;
}
var alarmDate = new Date(Date.now() + (60 * 1000)); // 60 seconds later
var request = navigator.mozAlarms.add(alarmDate, "ignoreTimezone");
request.onsuccess = onAlarmAdded;
}
function setHandler() {
function onAlarm(mozAlarm) {
// set next alarm
setAlarm();
}
navigator.mozSetMessageHandler("alarm", onAlarm);
}
function startAlarm() {
setHandler();
setAlarm();
}
function stopAlarm() {
navigator.mozAlarms.remove(alarmId);
}

Background worker blocking UI when using web service call

For some reason when i put a long running web service call (doesn't matter if its a legacy one or WCF) in a background thread it seems to be locking up the UI main thread.
I cant see anything wrong with the code im putting in.
workerThreadInitialNotify = new BackgroundWorker();
workerThreadInitialNotify.WorkerSupportsCancellation = true;
workerThreadInitialNotify.DoWork += new DoWorkEventHandler(workerThreadInitialNotify_DoWork);
workerThreadInitialNotify.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerThreadInitialNotify_RunWorkerCompleted);
workerThreadInitialNotify.RunWorkerAsync();
Then in my do work i have a webservice call like:
void workerThreadInitialNotify_DoWork(object sender, DoWorkEventArgs e)
{
if (!(sender as BackgroundWorker).CancellationPending)
{
try
{
TestWebService service = new TestWebService();
service.RunLongRunningMethod();
}
catch(Exception ex)
{
}
}
}
When this thread is called, it occasionally locks up the UI thread, now i have setup the RunLongRunningMethod to purposely run slow and timeout (for testing purposes), but technically this shouldn't lockup the UI thread at all as its in a seperate thread.
Here is what the method contains:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["customConnection"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("TestDelay", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ee)
{
}
}
}
and TestDelay stored proc just contains this to simulate a delay so that the web service times out:
ALTER PROCEDURE [dbo].[TestDelay]
AS
WAITFOR DELAY '00:05:20';
The strange thing is that if i replace the web service call with a Thread.Sleep(20000); in the dowork, it runs perfectly, or even if i put a long running while loop it runs perfectly also.
I have no idea why specifically the webservice makes it lock up the UI.
ps: if i set up the webservice to be hosted locally to the Win Forms app, it runs ok, only when the webservice is running on another service, the strange lockup occurs.
ps (2): i am using devexpress library for ui controls of forms while the background thread runs in the background, not sure if this is related. I cant imagine why, if this is run in a seperate thread correctly
This ended up being a maxconnection .net setting in the App.config (its defaulted to a very low 2 by microsoft)
<system.net>
<connectionManagement>
<add address="*" maxconnection="40"/>
</connectionManagement>
</system.net>
Its now set to 40 and the issue has gone away.
There was multiple threads running at the same time, each calling web services, each of them were blocking each other.
There is more information in these links:
http://blogs.msdn.com/b/adarshk/archive/2005/01/02/345411.aspx
What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?
http://msdn.microsoft.com/en-us/library/fb6y0fyc.aspx

Can Visual Studio Test projects cope with events and delegates?

I am working on new functionality for a large C# project which is mostly legacy code.
The area that I'm working on handles XML schema messages, creates a schedule for their transmission and places them into some legacy timer code which notifies me when they should be sent.
Although I am new to them, Visual Studio test projects are proving useful in that I can test my code without trying to get the full system up and running (which can take upto 30 minutes on the test hardware!).
I have statically tested my event handling code, but would now like to do so dynamically.
Is this possible? If so how do I go about getting the test project to wait for the event without timing out?
If I understand you correctly, you could use a wait handle to signal the event and have your test project wait for the event handle to be signaled.
void Foo()
{
var eventSource = ...;
var waitHandle = new ManualResetEvent(false);
eventSource.SomeEvent += (sender, e) => waitHandle.Set();
...
// Wait for the event to be fired.
waitHandle.WaitOne();
}

Resources