UIApplicationDidBecomeActiveNotification和UIApplicationWillResignActiveNotification并非始终在Unity iOS App中触发

时间:2016-09-18 16:48:46

标签: ios objective-c xcode unity3d

我创建了一个Unity iOS应用程序。我在团结中创建应用程序的原因是因为它可以轻松移植到其他平台。

我正通过BLE技术与Axivity Sensors进行通信。一切都很好。但现在我想在后台运行应用程序。因此,我发现我应该使用UIApplicationDidBecomeActiveNotificationUIApplicationWillResignActiveNotification通知,以便我可以进行一些后台处理。

但有时,当应用变为有效或无效时,我不会收到通知。

有什么我做错了或者有更好的方法吗?

以下是代码:

-(id) init {

    self = [super init];

    if (!self) return nil;

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];

        return self;
    }

-(void)appWillResignActive:(NSNotification*)note {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(BLEOnCharactersticsUpdateNotification:)
                                             name:BLEOnCharactersticsUpdate object:nil]; 
}

-(void)appDidBecomeActive:(NSNotification*)note {

    NSLog(@"AppDidBecomeActive ");

    [[NSNotificationCenter defaultCenter] removeObserver:self name:BLEOnCharactersticsUpdate object:nil];

    for(int timeStampIndex = 0; timeStampIndex < [timeStampArray count]; timeStampIndex++) {

        NSLog(@"TimeStamp %i : Value : %@",timeStampIndex,[timeStampArray objectAtIndex:timeStampIndex]);
    }
}

-(void)appWillTerminate:(NSNotification*)note {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}

1 个答案:

答案 0 :(得分:0)

如何确保整个应用程序生命周期中都存在代码示例中的对象? 最有可能的是,它在执行的某个时刻被释放,这就是为什么它不接收通知的原因。 iOS本身保证该应用程序始终至少接收UIApplicationDidBecomeActiveNotificationUIApplicationWillResignActiveNotification

P.S。您以init方法订阅通知。并退订appWillTerminate。最好的退订地点是dealloc