gpt4 book ai didi

iOS:将 ObjC 代码转换为 C#,如何知道应用程序处于空闲状态的时间

转载 作者:可可西里 更新时间:2023-11-01 05:12:54 25 4
gpt4 key购买 nike

我是 iOS 开发的新手,我正在使用 monotouch 开发 iOS 应用程序,我想知道自应用程序闲置以来的时间,我获得了 ObjC 代码,但无法将其转换为 C#。这是代码:

- (void)sendEvent:(UIEvent *)event {
[super sendEvent:event];

// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
}

- (void)resetIdleTimer {
if (idleTimer) {
[idleTimer invalidate];
[idleTimer release];
}

idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}

- (void)idleTimerExceeded {
NSLog(@"idle time exceeded");
}

谁能帮我把它转换成 C#。

最佳答案

当然有更好的方法来实现这一点,但让我们将此 Obj-C 代码几乎逐行转换为 Xamarin.iOS C#:

sendEventUIApplication 的一个方法。对其进行子类化是非常罕见的,请参阅 UIApplication class reference 上的子类化注释

一旦对其进行子类化,就必须指示运行时使用它,这是在 Main 方法中完成的,通常在 Main.cs 中找到。这是修改后的 Main.cs 现在的样子。

public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
UIApplication.Main (args, "MyApplication", "AppDelegate");
}
}

[Register ("MyApplication")]
public class MyApplication : UIApplication
{

}

注意类上的 Register 属性,用作 UIApplication.Main 的第二个参数。

现在,让我们真正翻译您的代码:

[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 ();
}
}

NSTimer idleTimer;
void ResetIdleTimer ()
{
if (idleTimer != null) {
idleTimer.Invalidate ();
idleTimer.Release ();
}

idleTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromHours (1), TimerExceeded);
}

void TimerExceeded ()
{
Debug.WriteLine ("idle time exceeded");
}
}

我用 TimeSpan.FromHours (1) 替换了 maxIdleTime。否则,您将拥有与 Obj-C 相同的行为,包括错误(如果有的话)(尽管看起来还不错)。

关于iOS:将 ObjC 代码转换为 C#,如何知道应用程序处于空闲状态的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19928361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com