【问题标题】:iphone background process not working for longtime in my applicationiphone后台进程在我的应用程序中长时间不起作用
【发布时间】:2012-02-22 09:58:33
【问题描述】:

我正在我的应用程序中使用 iphone 后台进程。它在后台运行,但 10 分钟后它正在终止我的应用程序。并且长时间不工作。

当 viewdidload 时,我的应用程序包含 1 个带有 timmer 的计数器,那时我的计数器将启动,当我单击主页按钮时,它将在后台运行。在后台它运行完美,但 10 分钟后它正在停止我的后台进程。以下是我的代码。

在 .h 文件中。

IBOutlet UILabel *thecount;
int count;
NSTimer *theTimer;
UIBackgroundTaskIdentifier counterTask;

在我的 .m 中

- (void)viewDidLoad {

    UIBackgroundTaskIdentifier bgTask = nil;
    UIApplication  *app = [UIApplication sharedApplication];


    counterTask = [[UIApplication sharedApplication]
                   beginBackgroundTaskWithExpirationHandler:^{
                       [app endBackgroundTask:counterTask]; 
                       //counterTask = UIBackgroundTaskInvalid;

                       // If you're worried about exceeding 10 minutes, handle it here
                       theTimer=[NSTimer scheduledTimerWithTimeInterval:0.5
                                                                 target:self
                                                               selector:@selector(countUp)
                                                               userInfo:nil
                                                                repeats:YES];
                   }];

    count=0;
    theTimer=[NSTimer scheduledTimerWithTimeInterval:0.5
                         target:self
                         selector:@selector(countUp)
                         userInfo:nil
                         repeats:YES];

    [super viewDidLoad];
}
  • (void)countUp {

     count++;
     NSString *currentCount;
    
     currentCount=[[NSString alloc] initWithFormat:@"%d",count];
     NSLog(@"timer running in background :%@",currentCount);
     thecount.text=currentCount;
     [currentCount release];
    

}

上面的代码只是示例来计算前景和背景的数量。但 10 分钟后它不起作用。

所以请帮助我并为此提供一些帮助。

【问题讨论】:

标签: iphone background


【解决方案1】:

10 分钟是长时间运行的后台任务的最长时间。 iOS 不提倡长时间运行后台进程的想法,为了您的用户,您不应该尝试这样做。

为了让您的代码运行更长时间,其他一些外部事件可能会使您的应用再次被唤醒或继续运行,例如GPS 定位事件、在您的 VoIP 类应用中播放音频或传入 VoIP 连接。

【讨论】:

  • 感谢您的回复。在我的应用程序中,我有时会向服务器发送 gps 数据。以上只是在后台工作的代码。请您提供一些详细示例,说明如何在某个时间将 gps 数据发送到我的服务器并且应用程序应该运行。所以我能理解。
  • 因此,每当您收到有关设备位置的通知时,您都可以安排任务将该位置发送到服务器。您可以通过 CLLocationManagerDelegate-protocol-implementing 类中的 locationManager:didUpdateToLocation:fromLocation 方法来做到这一点。
  • 哦,你没明白我的意思,我在某个特定的时差以后台模式跟踪用户。所以我必须实现类似的后台任务。 i want to implement like this 但我无法正确理解答案。想指导我吗?
  • 哦,对了。正如您从链接的线程中看到的那样,不可能任意运行您的代码,例如,从进入后台的一个小时后。您只能设置用户设备移动的最小距离,以便应用程序收到更改通知。如果您声明您的应用正在播放背景音频或处理 VoIP 服务,而实际上并非如此,您的应用将被 Apple 拒绝。
  • 如果有例子,你会深入解释一下吗?我不明白你的意思。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多