How to calculate App Idle Time in MVVMCross Xamarin.iOS? - c#

I am developing iOS Universal Application in Xamarin.iOS using MVVMCross. I want to calculate App Idle time I found the following useful help
iOS:Convert ObjC code to C#, How to know the time app has been idle
But there is an issue when i try to use this with MVVMCross which is that
AppDelegate.cs in MvvmCross is inherited from MvxApplicationDelegate.cs
I am unable to override the following event in AppDelegate because it is not overriding UIApplication
public override void SendEvent (UIEvent uievent)
{
base.SendEvent (uievent);
var allTouches = uievent.AllTouches;
if (allTouches.Count > 0) {
var phase = ((UITouch)allTouches.AnyObject).Phase;
if (phase == UITouchPhase.Began || phase == UITouchPhase.Ended)
ResetIdleTimer ();
}
}

You were close to the answer.
In a default MvvMCross project, there is a Main.cs, that contains a Application class.
You just have to replace the null in following line with your UIApplication's child class name
UIApplication.Main(args, null, "AppDelegate");
e.g If your class name is MyApplication which is inherited from UIApplication then it should be like
UIApplication.Main(args, "MyApplication", "AppDelegate");
and add a class MyApplication
[Register("MyApplication")]
public class MyApplication : UIApplication
{
public override void SendEvent(UIEvent uievent)
{
base.SendEvent(uievent);
var allTouches = uievent.AllTouches;
if (allTouches.Count > 0)
{
var phase = ((UITouch)allTouches.AnyObject).Phase;
if (phase == UITouchPhase.Began || phase == UITouchPhase.Ended)
ResetIdleTimer();
}
}
}

Related

Android 8 receive of stop receiving media buttons events

I have a service that listens to media buttons, but I only want to listen to those when my service is running since I have a button on the UI to start/stop the service.
How can I achieve the following two actions:
On MyService start-up, start receiving media button events to com.myApp/MyService.
On MyService end, stop receiving media button events in com.myApp/MyService.
The related logs are the following:
D MediaSessionService: Sending KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_HEADSETHOOK, scanCode=226, metaState=0, flags=0x8, repeatCount=0, eventTime=13258317, downTime=13258317, deviceId=4, source=0x101 } to com.myApp/MyService (userId=0)
Note:
I found out that I can start receiving media events after my app started to play audio. This is however not ideal, since I don't want to play audio in my app. (I am only using media events in order to trigger voice recognition)
After I played audio, my service is apparently the default media receiver. This means that when a media button is pressed, my service get instantiated, does nothing, and get destroyed. This is not an idea behavior for the end user since my app ends up 'stealing' these events that could potentially be handled by something else.
Overriding OnStartCommand() in my service does not help
Calling SetMediaButtonReceiver on the MediaSession does not help either
Using a BroadcastReceiver with the intent "android.intent.action.MEDIA_BUTTON" registered in the AudioManager does not work either
Relevant code (in C#, I am on Xamarin.Forms, but that should not have any impact on the way to achieve this)
public class MediaSessionCompatCallback : MediaSessionCompat.Callback
{
public Func<Intent, bool> MediaButtonEvent { get; set; }
public override bool OnMediaButtonEvent(Intent mediaButtonEvent) => MediaButtonEvent?.Invoke(mediaButtonEvent) ?? false;
}
[Service(Exported = true, Enabled = true)]
[IntentFilter(new[] { ServiceInterface })]
public class MediaBrowserService : MediaBrowserServiceCompat, AudioManager.IOnAudioFocusChangeListener
{
private MediaSessionCompat mediaSession;
private MediaSessionCompatCallback mediaSessionCallback;
private void CreateMediaSessionCallback()
{
mediaSessionCallback = new MediaSessionCompatCallback()
{
MediaButtonEvent = OnMediaButtonEvent
};
}
private void SetupMediaSession()
{
CreateMediaSessionCallback();
var stateBuilder = new PlaybackStateCompat.Builder().SetActions(PlaybackStateCompat.ActionPlay | PlaybackStateCompat.ActionPlayPause);
mediaSession = new MediaSessionCompat(this, nameof(MediaBrowserService));
mediaSession.SetFlags(MediaSessionCompat.FlagHandlesMediaButtons | MediaSessionCompat.FlagHandlesTransportControls);
mediaSession.SetPlaybackState(stateBuilder.Build());
mediaSession.SetCallback(mediaSessionCallback);
mediaSession.Active = true;
SessionToken = mediaSession.SessionToken;
}
private void BuildNotification() { [...] }
public override void OnCreate()
{
base.OnCreate();
SetupMediaSession();
StartForeground(135, BuildNotification());
ContextCompat.StartForegroundService(ApplicationContext, new Intent(ApplicationContext, Java.Lang.Class.FromType(typeof(MediaBrowserService))));
}
public override void OnDestroy()
{
base.OnDestroy();
if (mediaSession != null)
{
mediaSession.Active = false;
mediaSession.SetCallback(null);
mediaSession.Release();
mediaSession.Dispose();
mediaSession = null;
}
if (mediaSessionCallback != null)
{
mediaSessionCallback.Dispose();
mediaSessionCallback = null;
}
StopForeground(true);
StopSelf();
}
}

Android Xamarin detect started from task manager

I am currently developing an android xamarin app (android 6 and above) and I have got a problem.
Our customer wants to secure the app by a pinpad. Whenever the app is started the user has to enter a four digit pin.
We have created an activity for the pinpad. This works pretty fine, but the problem is the following:
The pinpad just opens if the app was completely killed (e.g. by the task manager ) -> cold started.
How can I achive that the pinpad opens if the app was in the background and reopend by the task manager for example (user pressed home button and then wants to start app again) -> warm started.
I've tried to do this by OnResume(), OnStart(),. But unfortunately they trigger every time an another activity (e.g. open detail view of list item) is opened.
use IActivityLifecycleCallbacks to listen the status.
Application registration ActivityLifecycleCallbacks, such, when each activity in the app lifecycle occurs, the Application can be listening to. The number of public void onActivityStarted(activity activity) and public void onActivityStopped(activity activity) of an activity can be used to determine whether the app is in the foreground. Because when the app is in the foreground, an activity must have started onActivityStarted but not onActivityStopped, so the statistics of the number of activities opened in the app must be 1. When the app switches to the background, activityStartCount will be 0.
so write a Helper classes :
public class AppFrontBackHelper
{
public static OnAppStatusListener mOnAppStatusListener;
private LifecycleCallBack lifecycleCallBack;
public AppFrontBackHelper()
{
}
/**
* Register status listener, only used in Application
* #param application
* #param listener
*/
public void register(Application application, OnAppStatusListener listener)
{
mOnAppStatusListener = listener;
lifecycleCallBack = new LifecycleCallBack();
application.RegisterActivityLifecycleCallbacks(lifecycleCallBack);
}
public void unRegister(Application application) => application.UnregisterActivityLifecycleCallbacks(lifecycleCallBack);
public interface OnAppStatusListener
{
void onFront();
void onBack();
}
public class LifecycleCallBack : Java.Lang.Object, Application.IActivityLifecycleCallbacks
{
public int activityStartCount { get; private set; }
public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
{
}
public void OnActivityDestroyed(Activity activity)
{
}
public void OnActivityPaused(Activity activity)
{
}
public void OnActivityResumed(Activity activity)
{
}
public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
{
}
public void OnActivityStarted(Activity activity)
{
activityStartCount++;
//A value from 1 to 0 indicates cutting from the background to the foreground
if (activityStartCount == 1)
{
if (mOnAppStatusListener != null)
{
mOnAppStatusListener.onFront();
}
}
}
public void OnActivityStopped(Activity activity)
{
activityStartCount--;
//A value from 1 to 0 indicates cutting from the foreground to the background
if (activityStartCount == 0)
{
//从前台切到后台
if (mOnAppStatusListener != null)
{
mOnAppStatusListener.onBack();
}
}
}
}
}
then custom an Application and regist the listener :
[Application]
public class MyApplication : Application,AppFrontBackHelper.OnAppStatusListener
{
protected MyApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void OnCreate()
{
base.OnCreate();
AppFrontBackHelper appFrontBackHelper = new AppFrontBackHelper();
appFrontBackHelper.register(this, this);
}
public void onBack()
{
Toast.MakeText(this, "from front to back", ToastLength.Short).Show();
}
public void onFront()
{
Toast.MakeText(this, "from back to front", ToastLength.Short).Show();
}
}
you could do something in the onFront() callback.

How to play music from url in Xamarin.Forms?

I am gonna build Xamarin.Forms app which play music from url.
I used dependency service for each platform implementation.
[assembly: Dependency(typeof(AudioSerivce))]
namespace xxx.Droid
{
public class AudioSerivce : IAudio
{
int clicks = 0;
MediaPlayer player;
public AudioSerivce()
{
}
public bool Play_Pause (string url)
{
if (clicks == 0) {
this.player = new MediaPlayer();
this.player.SetDataSource(url);
this.player.SetAudioStreamType(Stream.Music);
this.player.PrepareAsync();
this.player.Prepared += (sender, args) =>
{
this.player.Start();
};
clicks++;
} else if (clicks % 2 != 0) {
this.player.Pause();
clicks++;
} else {
this.player.Start();
clicks++;
}
return true;
}
public bool Stop (bool val)
{
this.player.Stop();
clicks = 0;
return true;
}
}
}
and calling it
DependencyService.Get<IAudio>().Play_Pause("https://www.searchgurbani.com/audio/sggs/1.mp3");
If I check log, it seems everything is ok.
But I can't hear sound on android phone.
If anyone has some suggestion, please let me know.
Thanks
From:
https://forums.xamarin.com/discussion/64218/no-video-player-really
I suspect that there may be a problem related to an incompatibility between Octane Video player and Android Emulator, are you using a emulator/simulator?
Also another suggestion is to add this permissions:
INTERNET
WRITE_EXTERNAL_STORAGE
READ_EXTERNAL_STORAGE
To your Android app.
If that does not work try to use another url and compare if it working with other url's.

DismissViewController sometimes causes the program to freeze or crash

I have the following MonoTouch program:
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System;
namespace Experiment
{
// This is just for the example, I use a singleton in my app to do this.
public class AppSettings
{
public static bool IsLoggedIn = false;
}
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
UIWindow window;
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
UIViewController baseViewController = new RootViewController();
window = new UIWindow(UIScreen.MainScreen.Bounds);
window.AddSubview(baseViewController.View);
window.MakeKeyAndVisible();
return true;
}
static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
}
public class RootViewController : UITableViewController
{
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (!AppSettings.IsLoggedIn) {
this.PresentViewController(new LoginPopupController(), false, () => {});
}
}
}
public class LoginPopupController : UIViewController
{
public override void LoadView()
{
View = new UIView(UIScreen.MainScreen.ApplicationFrame);
View.BackgroundColor = UIColor.White;
UIButton button = new UIButton();
button.SetTitle("press me", UIControlState.Normal);
button.Frame = new RectangleF(50, 50, 80, 80);
button.TouchUpInside += delegate {
LoginSucceeded();
};
button.BackgroundColor = UIColor.Purple;
View.AddSubview(button);
}
public void LoginSucceeded()
{
AppSettings.IsLoggedIn = true;
Console.WriteLine("This line causes multiple problems at random");
DismissViewController(true, () => {});
}
}
}
It has two controllers the RootViewController and the LoginPopupController. The FinishedLoading method adds the RootViewController to the window. The RootViewController in the ViewDidAppear method checks if the app is logged in. If not, it will present the LoginPopupController.
The LoginPopupController has a button, which when pressed will set IsLoggedIn to true, and dismiss itself.
Basically, I want a login window to appear if the user isn't logged in, and then dismiss itself after it has entered login details into a singleton settings object.
However, the app is very unreliable at the moment. Pressing the "press me" button can cause the following to happen at random:
Work as expected
Freeze the app
Crash the app
Do nothing on first press, crash the app on the second press
The Console.WriteLine line has a big effect on this - if you remove it the code succeeds more often (but not always).
Can anyone figure out what is causing this problem? It seems like a race condition (as the results change between runs), however I can't figure out what could be causing that.
I'm running the code on the simulator using iOS 5.1. I have MonoTouch version 5.2.10 installed with Mono 2.10.8.
I have done two changes in your code and it never crashed, at least for my number of tries.
First, move the UIButton declaration to the class:
UIButton button;
public override LoadView()
{
//...
}
Second, initialize the button with the UIButton.FromType(UIButtonType) static method:
button = UIButton.FromType(UIButtonType.Custom);
The UIButton() constructor had problems in previous versions of MonoTouch. In some versions it was not even available. I could not find anything specific for its current state, however creating buttons with the static method is the normal way to go, according to Apple docs.

How do I create a real-time Excel automation add-in in C# using RtdServer?

I was tasked with writing a real-time Excel automation add-in in C# using RtdServer for work. I relied heavily on the knowledge that I came across in Stack Overflow. I have decide to express my thanks by writing up a how to document that ties together all that I have learned. Kenny Kerr's Excel RTD Servers: Minimal C# Implementation article helped me get started. I found comments by Mike Rosenblum and Govert especially helpful.
(As an alternative to the approach described below you should consider using Excel-DNA. Excel-DNA allows you to build a registration-free RTD server. COM registration requires administrative privileges which may lead to installation headaches. That being said, the code below works fine.)
To create a real-time Excel automation add-in in C# using RtdServer:
1) Create a C# class library project in Visual Studio and enter the following:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace StackOverflow
{
public class Countdown
{
public int CurrentValue { get; set; }
}
[Guid("EBD9B4A9-3E17-45F0-A1C9-E134043923D3")]
[ProgId("StackOverflow.RtdServer.ProgId")]
public class RtdServer : IRtdServer
{
private readonly Dictionary<int, Countdown> _topics = new Dictionary<int, Countdown>();
private Timer _timer;
public int ServerStart(IRTDUpdateEvent rtdUpdateEvent)
{
_timer = new Timer(delegate { rtdUpdateEvent.UpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return 1;
}
public object ConnectData(int topicId, ref Array strings, ref bool getNewValues)
{
var start = Convert.ToInt32(strings.GetValue(0).ToString());
getNewValues = true;
_topics[topicId] = new Countdown { CurrentValue = start };
return start;
}
public Array RefreshData(ref int topicCount)
{
var data = new object[2, _topics.Count];
var index = 0;
foreach (var entry in _topics)
{
--entry.Value.CurrentValue;
data[0, index] = entry.Key;
data[1, index] = entry.Value.CurrentValue;
++index;
}
topicCount = _topics.Count;
return data;
}
public void DisconnectData(int topicId)
{
_topics.Remove(topicId);
}
public int Heartbeat() { return 1; }
public void ServerTerminate() { _timer.Dispose(); }
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(#"CLSID\{" + t.GUID.ToString().ToUpper() + #"}\Programmable");
var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(#"CLSID\{" + t.GUID.ToString().ToUpper() + #"}\InprocServer32", true);
if (key != null)
key.SetValue("", System.Environment.SystemDirectory + #"\mscoree.dll", Microsoft.Win32.RegistryValueKind.String);
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(#"CLSID\{" + t.GUID.ToString().ToUpper() + #"}\Programmable");
}
}
}
2) Right click on the project and Add > New Item... > Installer Class. Switch to code view and enter the following:
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace StackOverflow
{
[RunInstaller(true)]
public partial class RtdServerInstaller : System.Configuration.Install.Installer
{
public RtdServerInstaller()
{
InitializeComponent();
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
var registrationServices = new RegistrationServices();
if (registrationServices.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
Trace.TraceInformation("Types registered successfully");
else
Trace.TraceError("Unable to register types");
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
var registrationServices = new RegistrationServices();
if (registrationServices.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
Trace.TraceInformation("Types registered successfully");
else
Trace.TraceError("Unable to register types");
}
public override void Uninstall(IDictionary savedState)
{
var registrationServices = new RegistrationServices();
if (registrationServices.UnregisterAssembly(GetType().Assembly))
Trace.TraceInformation("Types unregistered successfully");
else
Trace.TraceError("Unable to unregister types");
base.Uninstall(savedState);
}
}
}
3) Right click on the project Properties and check off the following: Application > Assembly Information... > Make assembly COM-Visible and Build > Register for COM Interop
3.1) Right click on the project Add Reference... > .NET tab > Microsoft.Office.Interop.Excel
4) Build Solution (F6)
5) Run Excel. Go to Excel Options > Add-Ins > Manage Excel Add-Ins > Automation and select "StackOverflow.RtdServer"
6) Enter "=RTD("StackOverflow.RtdServer.ProgId",,200)" into a cell.
7) Cross your fingers and hope that it works!
Calling UpdateNotify from the timer thread will eventually cause strange errors or disconnections from Excel.
The UpdateNotify() method must only be called from the same thread that calls ServerStart(). It's not documented in RTDServer help, but it is restriction of COM.
The fix is simple. Use DispatcherSynchronizationContext to capture the thread that calls ServerStart and use that to dispatch calls to UpdateNotify:
public class RtdServer : IRtdServer
{
private IRTDUpdateEvent _rtdUpdateEvent;
private SynchronizationContext synchronizationContext;
public int ServerStart( IRTDUpdateEvent rtdUpdateEvent )
{
this._rtdUpdateEvent = rtdUpdateEvent;
synchronizationContext = new DispatcherSynchronizationContext();
_timer = new Timer(delegate { PostUpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return 1;
}
// Notify Excel of updated results
private void PostUpdateNotify()
{
// Must only call rtdUpdateEvent.UpdateNotify() from the thread that calls ServerStart.
// Use synchronizationContext which captures the thread dispatcher.
synchronizationContext.Post( delegate(object state) { _rtdUpdateEvent.UpdateNotify(); }, null);
}
// etc
} // end of class
Following the previous two answers for the RTD server worked for me. However I ran into an issue when on an x64 machine running Excel x64. In my case, until I switched the "target platform" of the project to x64, Excel always showed #N/A.

Categories