Keeping Tizen wearable device application running in background mode

Long-running application can be interrupted by falling asleep on Samsung Wearable device in a timeout. In this article you will find the way I could find to keep application working in background mode in any amount of time.

The way is fair for C# applications running on Samsung Galaxy Watches Active 2 with Tizen Wearable 4.0 SDK.

Request privileges

At first you need to be sure your app has all required privileges. Go to tizen-manifest.zml file and add the marked code:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.yourapp" version="1.0.0" api-version="4" xmlns="http://tizen.org/ns/packages">
    <profile name="wearable" />
    <ui-application appid="com.example.yourapp" exec="yourapp.dll" multiple="false" nodisplay="false" taskmanage="true" type="dotnet" launch_mode="single">
        .....
        <background-category value="sensor" />
    </ui-application>
    <shortcut-list />
    <privileges>
        .....
        <privilege>http://tizen.org/privilege/power</privilege>
        <privilege>http://tizen.org/privilege/display</privilege>
        <privilege>http://tizen.org/privilege/haptic</privilege>
     <privilege>http://tizen.org/privilege/appmanager.launch</privilege>
    </privileges>
    <dependencies />
    <provides-appdefined-privileges />
</manifest>

Add CPU-locking code

To allow your app running in background mode you need to add CPU-locking instructions.

private static bool _IsCpuLocked = false;

 public static bool IsCpuLocked
{
	get
	{
		return _IsCpuLocked;
	}
	private set
	{
		_IsCpuLocked = value;
	}
}

public static void LocCpu()
{
	if (!IsCpuLocked)
	{
		try
		{
			Tizen.System.Power.RequestCpuLock(0);
			IsCpuLocked = true;
		}
		catch (Exception e)
		{
			.....
		}
	}
}

public static void ReleaseCpu()
{
	if (IsCpuLocked)
	{
		try
		{
			Tizen.System.Power.ReleaseCpuLock();
			IsCpuLocked = false;
		}
		catch (Exception e)
		{
			.....
		}
	}
}

Now you need to wrap your long-running job with CPU-locking instructions.

private void StartLongJob()
{
	try
	{
		LocCpu();
		// Long job starting code
	}
	catch (Exception e)
	{
		......
	}
}

private void StopLongJob()
{
	try
	{
		ReleaseCpu();
		// Long job stopping code
	}
	catch (Exception e)
	{
		....
	}
}