How to create a background service in .NET Maui - maui

I'm new to mobile app development and am learning .NET Maui. The app I'm creating needs to listen for Accelerometer events, and send a notification to a web service if the events meet certain criteria. The bit I'm struggling with is how to have the app run in the background, i.e. with no UI visible, without going to sleep, as I'd want the user to close the UI completely. So I'm thinking the app needs to run as some kind of service, with the option to show a UI when needed - how can this be done?

i know it's beign a while but will post an answer for future users!
First we need to understand that background services depends on which platform we use.(thanks Jason) And i will focus on ANDROID, based on Xamarin Documentation (thanks Eli), adapted to Maui.
Since we are working with ANDROID, on MauiProgram we will add the following:
/// Add dependecy injection to main page
builder.Services.AddSingleton<MainPage>();
#if ANDROID
builder.Services.AddTransient<IServiceTest, DemoServices>();
#endif
And we create our Interface for DI which provides us the methods to start and stop the foreground service
public interface IServiceTest
{
void Start();
void Stop();
}
Then, before platform code we need to add Android Permissions on AndroidManifest.xml:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Android Main Activity
public class MainActivity : MauiAppCompatActivity
{
//set an activity on main application to get the reference on the service
public static MainActivity ActivityCurrent { get; set; }
public MainActivity()
{
ActivityCurrent = this;
}
}
And Finally we create our Android foreground service. Check Comments Below. Also on xamarin docs, they show the different properties for notification Builder.
[Service]
public class DemoServices : Service, IServiceTest //we implement our service (IServiceTest) and use Android Native Service Class
{
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
[return: GeneratedEnum]//we catch the actions intents to know the state of the foreground service
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (intent.Action == "START_SERVICE")
{
RegisterNotification();//Proceed to notify
}
else if (intent.Action == "STOP_SERVICE")
{
StopForeground(true);//Stop the service
StopSelfResult(startId);
}
return StartCommandResult.NotSticky;
}
//Start and Stop Intents, set the actions for the MainActivity to get the state of the foreground service
//Setting one action to start and one action to stop the foreground service
public void Start()
{
Intent startService = new Intent(MainActivity.ActivityCurrent, typeof(DemoServices));
startService.SetAction("START_SERVICE");
MainActivity.ActivityCurrent.StartService(startService);
}
public void Stop()
{
Intent stopIntent = new Intent(MainActivity.ActivityCurrent, this.Class);
stopIntent.SetAction("STOP_SERVICE");
MainActivity.ActivityCurrent.StartService(stopIntent);
}
private void RegisterNotification()
{
NotificationChannel channel = new NotificationChannel("ServiceChannel", "ServiceDemo", NotificationImportance.Max);
NotificationManager manager = (NotificationManager)MainActivity.ActivityCurrent.GetSystemService(Context.NotificationService);
manager.CreateNotificationChannel(channel);
Notification notification = new Notification.Builder(this, "ServiceChannel")
.SetContentTitle("Service Working")
.SetSmallIcon(Resource.Drawable.abc_ab_share_pack_mtrl_alpha)
.SetOngoing(true)
.Build();
StartForeground(100, notification);
}
}
Now we have our foreground Service working on Android, that show a notification ("Service Working"). Every time it starts. I make a show message foreground service to see it better while testing, in your case it suppose to close the app if that's what you want, but the functioning it's the same.
So having our background service working only left a way to call it so on our main page (as example) i will do the following:
MainPage.xaml
<VerticalStackLayout>
<Label
Text="Welcome to .NET Multi-platform App UI"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="CounterBtn"
Text="start Services"
Clicked="OnServiceStartClicked"
HorizontalOptions="Center" />
<Button Text="Stop Service" Clicked="Button_Clicked"></Button>
</VerticalStackLayout>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
IServiceTest Services;
public MainPage(IServiceTest Services_)
{
InitializeComponent();
ToggleAccelerometer();
Services = Services_;
}
//method to start manually foreground service
private void OnServiceStartClicked(object sender, EventArgs e)
{
Services.Start();
}
//method to stop manually foreground service
private void Button_Clicked(object sender, EventArgs e)
{
Services.Stop();
}
//method to work with accelerometer
public void ToggleAccelerometer()
{
if (Accelerometer.Default.IsSupported)
{
if (!Accelerometer.Default.IsMonitoring)
{
Accelerometer.Default.ReadingChanged += Accelerometer_ReadingChanged;
Accelerometer.Default.Start(SensorSpeed.UI);
}
else
{
Accelerometer.Default.Stop();
Accelerometer.Default.ReadingChanged -= Accelerometer_ReadingChanged;
}
}
}
//on accelerometer property change we call our service and it would send a message
private void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
{
Services.Start(); //this will never stop until we made some logic here
}
}
It's a long Answer and it would be great to have more official documentation about this! Hope it helps! If anyone can provide more info about IOS, Windows, MacCatalyst would be awesome!

Related

Android 8.1 REALLY Persistent Foreground Service Notification

I'm updating my Android app to work with 8.1 from 7. It's not mass-market it's the main alerting app for managed devices - so it NEEDS to stay on.
I have a "persistent" notification for my Foreground service, BUT now in 8+ there's a slider to mute my app notifications.
I can see that android system notifications and other apps remove this slider and display message:
"Notifications from this app can't be turned off".
How do I replicate this pattern?
I've read through notification, service, and channel documentation.
I'm already creating a channel with IMPORTANCE_DEFAULT, using setOngoing(true), and calling startForeground() on the service with the persistent notification:
Here's my Service create and start and channel creation to give you the gist:
public static final String CHANNEL_ID = "ForegroundWebsocketNotificationsServiceChannel";
public static final String CHANNEL_NAME = "WCMobility Notifications";
public static final String CHANNEL_DESCRIPTION = "Required notification and update alerts for WCMobility";
#Override
public void onCreate() {
super.onCreate();
noteMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
createNotificationChannel(CHANNEL_ID);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
notificationBuilder.setContentTitle("Service Started");
notificationBuilder.setContentText("Not connected, not receiving messages! ");
int notificationIconID = getIconResId(ICON_FILENAME);
notificationBuilder.setSmallIcon(notificationIconID);
notificationBuilder.setOngoing(true);
notificationIntent = new Intent(this, MainActivity.class);
try{ notificationIntent.putExtras(intent.getExtras());
}catch (Exception e){}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
startForeground(NOTIFICATION_ID, notification);
return START_NOT_STICKY;
}
private void createNotificationChannel(String channelId) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, CHANNEL_NAME, importance);
channel.setDescription(CHANNEL_DESCRIPTION);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
noteMgr.createNotificationChannel(channel);
}
}
We learned that you can't fully block the user from turning off notifications, at least not on consumer devices. Our clients use MDMs and Managed Devices where they restrict access to settings pages etc for end users, plus since the app is primary app used on the phone, user base is not inclined to disable it. This has worked out for us. I did have to add a line to my ForegroundService class code to make the notification dismissable when there was no active session:
stopForeground(false);
stopSelf();
and make it persistant again when session resumed.
startForeground(notificationHelper.NOTIFICATION_ID, notification);
This has worked out for us so far.

Automatically open UWP app that launches on startup

I am working on a UWP app generated by Unity. Following the documentation on StartUpTasks here I have set the app to launch at startup, however when it does it launches minimized in the taskbar. I need the app to be open when it launches, but do not know what to call and where to make this happen.
This is the code generated by Unity:
namespace UnityToUWPApp
{
class App : IFrameworkView, IFrameworkViewSource
{
private WinRTBridge.WinRTBridge m_Bridge;
private AppCallbacks m_AppCallbacks;
public App()
{
SetupOrientation();
m_AppCallbacks = new AppCallbacks();
}
public virtual void Initialize(CoreApplicationView applicationView)
{
applicationView.Activated += ApplicationView_Activated;
CoreApplication.Suspending += CoreApplication_Suspending;
// Setup scripting bridge
m_Bridge = new WinRTBridge.WinRTBridge();
m_AppCallbacks.SetBridge(m_Bridge);
m_AppCallbacks.SetCoreApplicationViewEvents(applicationView);
}
private void CoreApplication_Suspending(object sender, SuspendingEventArgs e)
{
}
private void ApplicationView_Activated(CoreApplicationView sender, IActivatedEventArgs args)
{
CoreWindow.GetForCurrentThread().Activate();
}
public void SetWindow(CoreWindow coreWindow)
{
m_AppCallbacks.SetCoreWindowEvents(coreWindow);
m_AppCallbacks.InitializeD3DWindow();
}
public void Load(string entryPoint)
{
}
public void Run()
{
m_AppCallbacks.Run();
}
public void Uninitialize()
{
}
[MTAThread]
static void Main(string[] args)
{
var app = new App();
CoreApplication.Run(app);
}
public IFrameworkView CreateView()
{
return this;
}
private void SetupOrientation()
{
Unity.UnityGenerated.SetupDisplay();
}
}
}
How can I ensure that when the app starts it is open and active?
UWP apps that are set as Startup task get launched as minimized/suspended by design. This is to ensure a good user experience for Store app by default and avoid having a ton of apps launch into the user's face on boot.
Classic Win32 apps as well as desktop bridge apps can continue to start in the foreground for backwards compat/consistency reasons.
To accomplish your goal, you can include a simple launcher Win32 exe in your package and set that as startup task. Then when it starts you just launch the UWP from there into the foreground. Note that doing this will require you to declare the "runFullTrust" capability, which will require an additional onboard review for the Microsoft Store.
To declare the Win32 exe as startup task, follow the "desktop bridge" section from this doc topic:
https://learn.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.StartupTask

Android Wear: Listen to incoming notifications

Is it possible to listen for incoming notifications in an Wearable Android App? I have tried to implement a NotificationListenerService, but the service's onNotificationPosted() is never called:
public class MyListenerService extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
Log.d("NotificationListener", "This works....");
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i("NotificationListener", "... but this method won't be called.");
}
}
Try this:
adb shell settings put secure enabled_notification_listeners com.google.android.wearable.app/com.google.android.clockwork.stream.NotificationCollectorService:$YOUR_PACKAGE/$YOUR_PACKAGE.$YOUR_NOTIFICATION_LISTENER
It's not possible to use a NotificationListenerService in Android Wear as there is no screen for the user to allow this.
You have to do it in the device's app and to use the Wearable Data Layer API to perform the action on Wear's side.

Android Activity and Service communication: how to keep the UI up-to-date

I have an Activity A (not the main Activity) that launches a Service S that does some stuff in the background and, in the meanwhile, should made some changes to the UI of A.
Let's just say that S count from 0 to 100 and A should display this count in Real-Time. Since the real job of S is quite more complicated and CPU-consuming, I do not want to use AsyncTask for it (indeed "AsyncTasks should ideally be used for short operations (a few seconds at the most.) [...]") but just a regular Service started in a new Thread (an IntentService would be fine as well).
This is my Activity A:
public class A extends Activity {
private static final String TAG = "Activity";
private TextView countTextView; // TextView that shows the number
Button startButton; // Button to start the count
BResultReceiver resultReceiver;
/**
* Receive the result from the Service B.
*/
class BResultReceiver extends ResultReceiver {
public BResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
switch ( resultCode ) {
case B.RESULT_CODE_COUNT:
String curCount = resultData.getString(B.RESULT_KEY_COUNT);
Log.d(TAG, "ResultReceived: " + curCount + "\n");
runOnUiThread( new UpdateUI(curCount) ); // NOT WORKING AFTER onResume()!!!
break;
}
}
}
/**
* Runnable class to update the UI.
*/
class UpdateUI implements Runnable {
String updateString;
public UpdateUI(String updateString) {
this.updateString = updateString;
}
public void run() {
countTextView.setText(updateString);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter);
countTextView = (TextView) findViewById(R.id.countTextView);
startButton = (Button) findViewById(R.id.startButton);
resultReceiver = new BResultReceiver(null);
}
public void startCounting(View view) {
startButton.setEnabled(false);
//Start the B Service:
Intent intent = new Intent(this, B.class);
intent.putExtra("receiver", resultReceiver);
startService(intent);
}
}
And this is my Service B:
public class B extends Service {
private static final String TAG = "Service";
private Looper serviceLooper;
private ServiceHandler serviceHandler;
private ResultReceiver resultReceiver;
private Integer count;
static final int RESULT_CODE_COUNT = 100;
static final String RESULT_KEY_COUNT = "Count";
/**
* Handler that receives messages from the thread.
*/
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
while ( count < 100 ) {
count++;
//Sleep...
sendMessageToActivity(RESULT_CODE_COUNT, RESULT_KEY_COUNT, count.toString());
}
//Stop the service (using the startId to avoid stopping the service in the middle of handling another job...):
stopSelf(msg.arg1);
}
}
#Override
public void onCreate() {
//Start up the thread running the service:
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
this.count = 0;
//Get the HandlerThread's Looper and use it for our Handler
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.resultReceiver = intent.getParcelableExtra("receiver");
//For each start request, send a message to start a job and deliver the start ID so we know which request we're stopping when we finish the job:
Message msg = serviceHandler.obtainMessage();
msg.arg1 = startId;
serviceHandler.sendMessage(msg);
//If we get killed, after returning from here, restart:
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Send a message from to the activity.
*/
protected void sendMessageToActivity(Integer code, String name, String text) {
Bundle bundle = new Bundle();
bundle.putString(name, text);
//Send the message:
resultReceiver.send(code, bundle);
}
}
Everything works fine but if I click the back button (or the home button) and then I re-open the Activity A then the UI of A is not updated anymore (it just shows the initial configuration of A - i.e. the "startButton" is still clickable and the count is not showed - it seems runOnUiThread(...) is not working anymore). However, the Service B is still running in the background and the I can see the correct count is passed to the Activity A in the Log.d(...). Finally, if I click on the "startButton" again, the counting does not start from the beginning (0) but from where B has been arrived (I've double checked it by showing it in the notification bar).
How can I fix this behaviour? I would like that, when I re-open the Activity A, it automatically continues to receive and update the data from the Service B. Or, in other words, that the Service keeps the UI of the Activity A up-to-date.
Please give me some hints, links or piece of code. Thanks!
When you click back button your Activity is destroyed. When you start the Activity again you get a new Activity. That also happen when you rotate the device. This is Android lifecycle event
The Activity is not good for heavy Business Logic only to show stuff/control stuf.
What you have to do is create a simple MVC, Model View Controller. The view (Activity) should only be used for showing results and controlling the eventflow.
The Service can hold an Array of the count and when your Activity start it will onBind() your Service that is running (or if not running will start the Service since you bind to it) Let the Activity(View) get the Array of results and show it. This simple setup exclude the (M)Model Business Logic.
Update
Following up a bit read this it's Android official docs and perfect start since it do kind of what you asking. As you see in the example in the onStart() the Activity establish a connection with the service and in the onStop() the connection is removed. There's no point having a connection after on onStop(). Just like you asking for. I would go with this setup and not let the Service continuously sending data because that would drain resources and the Activity is not always listening because it will stop when in the background.
Here's an activity that binds to LocalService and calls getRandomNumber() when a button is clicked:

How to access an already-running Application Context from a Sync Adapter service in Android?

I have an app that consists of several activities, and I use the Application Context (entended from the Application Class, and I made it persistent) to share data and objects between all the activities. I use the Application Class instead of a background service for several good reasons, which I won't go into here.
I also recently added an custom contact sync adapter to my app. It's under the same package, in the same APK. So, I set it up to access the Application Context just like everything else in my app to give it access to all the shared data and objects. However, even though it works (mostly), it creates a new instance of the Application Context. So there are basically 2 separate instances of my application running, and the data isn't shared between them.
I think that the problem is that my Applicattion never starts the sync service, the OS does. All my other activities are either started by the application, or the main activity accesses the Application Context when it launches, and then the App Context controls everything else. Is there a way to have the sync service access the existing Application Context, instead of creating the new instance of it?
Here's the basic structure of my app:
The application
package com.mycomany.myapp;
public class MyApp extends Application{
...
}
Activity1
package com.mycomany.myapp;
public class MyActivity1 extends Activity{
MyApp a;
#Override
public void onCreate(Bundle savedInstanceState){
a = (MyApp) getApplicationContext();
...
}
}
SyncAdapterService
package com.mycomany.myapp;
public class SyncAdapterService extends Service {
private static SyncAdapterImpl sSyncAdapter = null;
private static final Object sSyncAdapterLock = new Object();
private static ContentResolver mContentResolver = null;
private static MyApp a;
public SyncAdapterService() {
super();
}
private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
private Context mContext;
public SyncAdapterImpl(Context context) {
super(context, true);
mContext = context;
}
#Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
try {
SyncAdapterService.performSync(mContext, account, extras, authority, provider, syncResult);
} catch (OperationCanceledException e) {}
}
}
#Override
public void onCreate() {
super.onCreate();
synchronized (sSyncAdapterLock) {
if(a == null){
a = (MyApp) getApplicationContext();
}
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapterImpl(getApplicationContext());
}
}
}
#Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
private static void performSync(Context context, Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
throws OperationCanceledException {
...
}
}
Have you copy&pasted this training for the SyncAdapter http://developer.android.com/training/sync-adapters/creating-sync-adapter.html?
At the end there is this XML Snippet:
<service
android:name="com.example.android.datasync.SyncService"
android:exported="true"
android:process=":sync">
<intent-filter>com.example.android.datasync.provider
<action android:name="android.content.SyncAdapter"/>
</intent-filter>
<meta-data android:name="android.content.SyncAdapter"
android:resource="#xml/syncadapter" />
</service>
With the attribute android:process=":sync" meaning you create a separate sync process. Remove it and you're good to go.
You might want to look into binding the service to your Application context. That way, if your application context does not exist, the service won't exist, as it runs in the same process (that of the Application) . See bindSerivce()
If your service is a remote one try using callbacks
Are you still having this problem?
If the service is declared in your manifest file without specifying a different android:process, isn't it supposed to run in the default process defined by your task?
Can't you in that case just use getApplicationContext to get what you need?
I have my sync adapter implemented in this way and it is working