It is possible background works for every 1 minutes in ios? - xamarin

Hello firstly I am so sorry about my bad english level.
I have an application.
Basically my application works for every 1 minutes use get method for getting some json data from server.
It is possible in android side and i created with foreground service.
But for xamarin.ios side how i can create?
actually my question is it is possible for in ios?

Before doing that , you can have a research with backgrond tasks in iOS .
The biggest change in iOS 7 with regard to background tasks is not how the tasks are implemented, but when they run.
Recall that pre-iOS 7, a task running in the background had 600 seconds to complete. One reason for this limit is that a task running in the background would keep the device awake for the duration of the task:
iOS 7 background processing is optimized for longer battery life. In iOS 7, backgrounding becomes opportunistic: instead of keeping the device awake, tasks respect when the device goes to sleep, and instead do their processing in chunks when the device wakes up to handle phone calls, notifications, incoming emails, and other common interruptions. The following diagram provides insight into how a task might be broken up:
Because the task run time is not longer continuous, tasks that perform network transfers must be handled differently in iOS 7. Developers are encouraged to use the NSURlSession API to handle network transfers. The next section is an overview of background transfers.
If you can keep the device not be killed , you can have a try with using System.Threading.Timer class to use Timer to implement what your want:
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static Timer timer;
static void Main(string[] args)
{
var timerState = new TimerState { Counter = 0 };
timer = new Timer(
callback: new TimerCallback(TimerTask),
state: timerState,
dueTime: 1000,
period: 2000);
while (timerState.Counter <= 10)
{
Task.Delay(1000).Wait();
}
timer.Dispose();
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: done.");
}
private static void TimerTask(object timerState)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: starting a new callback.");
var state = timerState as TimerState;
Interlocked.Increment(ref state.Counter);
}
class TimerState
{
public int Counter;
}
}
In addition , the first doc share the Background Transfers notes .The backbone of background transfers in iOS 7 is the new NSURLSession API.

Related

Android Room + AsyncTask

My team have developed a new Android app which makes extensive use of Room.
I am unsure whether we are using AsyncTask correctly.
We have had to wrap all calls to insert/update/delete in AsyncTasks which results in a huge number of AsyncTasks. All the calls into Room are from background services. There is no direct Room access from activities or fragments - they get everything via LiveData.
An example call to insert a row:
AsyncTask.execute(() -> myModelDAO.insertInstance(myModel));
With this in the DAO:
#Insert
void insertInstance(MyModel model);
To complete #CommonsWare answer, you can use the Executor class to execute Room queries into a background thread.
Executor myExecutor = Executors.newSingleThreadExecutor();
myExecutor.execute(() -> {
myModelDAO.insertInstance(myModel)
});
Google showed an example on their Android Architecture Components guide.
All the calls into Room are from background services
Then you should not be using AsyncTask. AsyncTask is only for when you want to do work on the main application thread after doing background work, and that is almost never the case with a service. Use something else (thread, thread pool, RxJava, etc.). This has nothing specific to do with Room.
AsyncTask.execute(() -> myModelDAO.insertInstance(myModel));
Looking like incorrect you can use Simple Thread/Threadpool/Schedulers etc
You can use a callback like Consumer<List<object>>callback.
For example:
roomManger.getAllUsertById(user.getId(), this, new Consumer<List<User>>() {
#Override
public void accept(List<Product> listOfUser) {
users.addAll(listOfUser)}

Reminder on windowphone

I write a application use notifycation on winphone 8. My application require send URI continuous to server every 30 seconds. My problem, i used reminder of winphone, but it can't use webbrowser call request in reminder.
My code:
public MainPage()
{
InitializeComponent();
var reminder = new Reminder("MyReminder")
{
Content = "Sending uri to server...",
BeginTime = DateTime.Now.AddSeconds(30),
webBrowser1.Navigate(new Uri("http://nhomxe.vn/device_register?uri="http://...", UriKind.Absolute));
};
ScheduledActionService.Add(reminder);
}
I think you're misunderstanding what the Reminder class is for and how to use it.
The Reminder class will display a prompt to the user with a piece of shell UI and allow them to tap on it to open your app. (Similar to an Alarm which also displays UI and allows you to customize the sound that is played but doesn't support a direct link to the app.)
The code you have written doesn't compile because you are writing the code to execute inside the object initializer which won't work. You also appear to have a string concatenation issue but this may just be a spurious quote(").
If you just want to make a request to a URL endpoint you also don't need to load it in a browser.
Assuming that you're wanting to send a message to your server every 30 seconds while the app is running then you could just do this with a Timer.
Like this:
var timer = new Timer(
state => new WebClient().DownloadStringAsync(new Uri("http://blah.blah/")),
null,
TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(30));
Obviously add error handling, etc.
It is not possible to have your code run every 30 seconds when your app is not running. If you want to do something when your app is not in the foreground then you need to look at using Background Agents.
You can use periodic task if you want to fetch information every 30 mins.

WP7 Emulator VS Device. download performance

I developed WP7 application using the emulator. Everything was great. To communicate with the server I used WebClient and RestClient. But to test the application on a real device - I threw a shock.
1)
private void LoadData()
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += DownloadStringCompleted;
webClient.DownloadStringAsync(new Uri(Constants.Url1));
//Point_1
}
private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Point_2
}
On emulator between Point_1 and Point_2 0.8-1.2 seconds.
On real device (HTC Radar WP7.8) between Point_1 and Point_2 15-20 seconds.
2)
var request = new RestRequest(url) {Method = Method.POST};
//Point_3
RestClient.ExecuteAsync(request, response =>
{
//Point_4
}
On emulator between Point_3 and Point_4 0.3-0.5 seconds.
On real device (HTC Radar WP7.8) between Point_3 and Point_4 18-22 seconds.
My computer and phone in same wi-fi network.
I have three questions:
First: It's normal?
Second: Why it's happening?
Third: How can I solved it?
There are many factors however its worth remembering that emulator performance is usually lot better than device and that you should try on device.
Having said that, you should consider alternate models of data display,
e.g. make a call and then populating data as it arrives in chunks using something like ObservableCollection.
You could also implement downloading the data using background task and having it already available.
In the end, it depends on what you can and cannot do.
Like Hermit says: "There are many factors however its worth remembering that emulator performance is usually lot better than device and that you should try on device."
My solution is - do not use debug mode, when you test network performance on real device. Just create XAP file and load it on device.

Eclipse RCP: Display.getDefault().asyncExec still blocking my GUI

I have a simple viewPart offering some text fields to enter parameters for a selenium test. After filling out these fields the user may start the test which approx. needs 30-45 minutes to run. I want my GUI to be alive during this test giving users the chance to do other things. I need a progress monitor.
I tried to put the selenium test in a job containing Display.getDefault().asyncExec to run it. But my GUI freezes after some seconds giving the busyindicator. The selenium does not update any other view but the progress monitor.
Is there another way to ensure that the job wont block my GUI?
Best,
Mirco
Everything executed in (a)syncExec is using the display thread and therefore blocking your UI until it returns. I suggest you use Eclipse Jobs. This will use the progress indicator that the workbench already offers out of the box.
I would suggest to split your code into code that updates the UI and the code that executes other business. Execute all of it in a separate thread, and when you need to retrieve or set some action to the UI then use the "Display.getDefault().asyncExec".
Thread thread = new Thread("Testing") {
// some shared members
public void run() {
someBusiness();
// or use syncExec if you need your thread
// to wait for the action to finish
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
// UI stuff here
// data retrieval
// values setting
// actions trigging
// but no business
}
});
someBusiness();
};
thread.start();

How to monitor process/program execution in windows?

We are trying to develop a small application that can monitor the programs/processes that are executing in a windows machine.
If the program/process is not supposed to run, it should be blocked. It works similar to an antivirus.
This is the basic idea.
I want to know the ways to hook into the OS to get notified about every single program/process trying to run in the machine.
The easiest way is to use WMI. Specifically monitor the Win32_ProcessStartTrace. This is better than Win32_Process, because it is setup to use events whereas Win32_Process requires polling which is more CPU intensive. Below is how to do it in C#. First make sure that System.Management is setup as a reference for your project.
public System.Management.ManagementEventWatcher mgmtWtch;
public Form1()
{
InitializeComponent();
mgmtWtch = new System.Management.ManagementEventWatcher("Select * From Win32_ProcessStartTrace");
mgmtWtch.EventArrived += new System.Management.EventArrivedEventHandler(mgmtWtch_EventArrived);
mgmtWtch.Start();
}
void mgmtWtch_EventArrived(object sender, System.Management.EventArrivedEventArgs e)
{
MessageBox.Show((string)e.NewEvent["ProcessName"]);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mgmtWtch.Stop();
}
The code will generate a messagebox everytime you launch a new process. From there you can check a whitelist/blacklist and act appropriately.
I havn't tried geting real-time notification. How ever, Here is how to get running processes in C#
using System.Diagnostics;
//Somewhere in your method
Process[] runningList = Process.GetProcesses();
foreach(Process p in runningList){
Console.WriteLine("Process: {0} ID: {1}", p.ProcessName, p.Id);
}
You can also use the following props of a process
StartTime - Shows the time the process started
TotalProcessorTime - Shows the amount of CPU time the process has taken
Threads - gives access to the collection of threads in the process
I would check up the Win32-api SetWindowsHookEx with the constant WH_GETMESSAGE to add a callback to your program when a new window is being created.
http://pinvoke.net/default.aspx/user32.SetWindowsHookEx
Google that API and WH_GETMESSAGE to find out more.
Also check out the following articles/code librarys:
http://www.vbaccelerator.com/home/Vb/Code/Libraries/Hooks/vbAccelerator_Hook_Library/article.asp
http://www.codeproject.com/KB/DLL/hooks.aspx?fid=2061&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=76&select=726975

Resources