1.首先开发插件:因为我的项目前需要所以要做(根据情况)

在项目的plugins文件中新建obj c文件。如

Demo,此时会产生出Demo.h和Demo.m两个文件。

.h文件主要就是定义一些方法,类似java中的接口.(要继承CDVPlugin)

.m文件是对h文件夹的实现,在插件执行时会进入相应的函数,切记:此函数要易执行长时的内容,此时uithread处于阻塞状态。不用我们可以启动一个线程在函数中,启动线的的的函数如下:

  1. NSThread *thread=[[NSThread alloc]initWithTarget:selft selector:@selector(doInBackground:)object:argumetns];
  2. //doInBackground是在新得线程中要执行的方法
  3. [thread start];
NSThread *thread=[[NSThread alloc]initWithTarget:selft selector:@selector(doInBackground:)object:argumetns];
//doInBackground是在新得线程中要执行的方法
[thread start];

我这里简单很一些code:

  1. #import<Foundation/Foundation.h>
  2. #import<Cordova/CDVPlugin.h>
  3. @Interface DisplayNumber:CDVPlugin
  4. -(void) setNumber:(CDVInvokeURLCommand) command;
  5. @end;
#import<Foundation/Foundation.h>
#import<Cordova/CDVPlugin.h>
@Interface DisplayNumber:CDVPlugin
-(void) setNumber:(CDVInvokeURLCommand) command;
@end;

2.在config.xml中启用插件

添加<feature name="Demo">

<param name='ios-package'  value='Demo'/>

</feature>

这里说明一下:value值是我们前面定义的类名,面feature中的name指得是我们前面再写js时,要调用的插件的名子,如果不明白,写个写成同一个名也行。(我就是这样做的)

3 编辑写插件js

  1. var Demo=function(){
  2. }
  3. Demo.prototype={
  4. method:function(fun1,fun2,params){cordova.exec(fun1//成功时调用,fun2,'插件名','插件的方法名',[params//参数数组]);
  5. }
  6. }
var Demo=function(){

  }
Demo.prototype={
method:function(fun1,fun2,params){cordova.exec(fun1//成功时调用,fun2,'插件名','插件的方法名',[params//参数数组]);
}
}

若我们想使用Demo插件,简单的可以写成new Demo().method(fun1,fun2,params);//很简单

说明一下:我们也可以在插件的js里的new Demo()给一个变量,我们再调用时就不用再new 一个。

关于后台无限运行的解决(网上也有很多解决方案)

1. Info.plist文件中新增:Required Background modes (是一个数组形式的建值),在item0后的value设置成为 App plays audio or streams audio/video using AirPlay。

2.在Classes文件夹下找到MainViewController.h,

  1. #import <Cordova/CDVViewController.h>
  2. #import <Cordova/CDVCommandDelegateImpl.h>
  3. #import <Cordova/CDVCommandQueue.h>
  4. #import <AVFoundation/AVFoundation.h>
  5. @interface MainViewController : CDVViewController{
  6. AVAudioPlayer *audioPlayer;
  7. }
  8. @property(nonatomic) AVAudioPlayer * audioPlayer;
  9. @end
  10. @interface MainCommandDelegate : CDVCommandDelegateImpl
  11. @end
  12. @interface MainCommandQueue : CDVCommandQueue
  13. @end
#import <Cordova/CDVViewController.h>
#import <Cordova/CDVCommandDelegateImpl.h>
#import <Cordova/CDVCommandQueue.h>
#import <AVFoundation/AVFoundation.h> @interface MainViewController : CDVViewController{
AVAudioPlayer *audioPlayer;
}
@property(nonatomic) AVAudioPlayer * audioPlayer;
@end @interface MainCommandDelegate : CDVCommandDelegateImpl
@end @interface MainCommandQueue : CDVCommandQueue
@end

接着修改MainViewController.m文件,找到viewDidLoad方法,修改为:

  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. // Do any additional setup after loading the view from its nib.
  5. dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  6. dispatch_async(dispatchQueue, ^(void) {
  7. NSError *audioSessionError = nil;
  8. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  9. if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
  10. NSLog(@"Successfully set the audio session.");
  11. } else {
  12. NSLog(@"Could not set the audio session");
  13. }
  14. NSBundle *mainBundle = [NSBundle mainBundle];
  15. NSLog(@"%@",mainBundle);
  16. NSString *filePath = [mainBundle pathForResource:@"love" ofType:@"wav"];
  17. NSData *fileData = [NSData dataWithContentsOfFile:filePath];
  18. NSError *error = nil;
  19. NSLog(@"AA%@",filePath);
  20. self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
  21. if (self.audioPlayer != nil){
  22. self.audioPlayer.delegate = self;
  23. [self.audioPlayer setNumberOfLoops:-1];
  24. if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
  25. NSLog(@"Successfully started playing...");
  26. } else {
  27. NSLog(@"Failed to play.");
  28. }
  29. } else {
  30. NSLog(@"Failed to play.");
  31. }
  32. });
  33. }
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
} NSBundle *mainBundle = [NSBundle mainBundle];
NSLog(@"%@",mainBundle);
NSString *filePath = [mainBundle pathForResource:@"love" ofType:@"wav"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
NSLog(@"AA%@",filePath);
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error]; if (self.audioPlayer != nil){
self.audioPlayer.delegate = self; [self.audioPlayer setNumberOfLoops:-1];
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing...");
} else {
NSLog(@"Failed to play.");
}
} else {
NSLog(@"Failed to play.");
}
}); }

说明:love.wav文件是other Sources下的文件。

接着修改AppDelegate.m文件,新增方法:

  1. -(void) applicationDidEnterBackground:(UIApplication *)application{
  2. //    [NSRunLoop currentRunLoop];
  3. //
  4. //    UIApplication *app=[UIApplication sharedApplication];
  5. //    __block UIBackgroundTaskIdentifier bgTask;
  6. //    bgTask=[app beginBackgroundTaskWithExpirationHandler:^{
  7. //        dispatch_async(dispatch_get_main_queue(), ^{
  8. //            if(bgTask!=UIBackgroundTaskInvalid){
  9. //                bgTask=UIBackgroundTaskInvalid;
  10. //            }
  11. //        });
  12. //    }];
  13. //
  14. //   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  15. //       dispatch_async(dispatch_get_main_queue(), ^{
  16. //           if(bgTask!=UIBackgroundTaskInvalid){
  17. //               bgTask=UIBackgroundTaskInvalid;
  18. //           }
  19. //       });
  20. //   });
  21. //
  22. //    [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
  23. //        NSLog(@"KeepAlive");
  24. //    }];
  25. MainViewController *mvc=[[MainViewController alloc] init];
  26. [mvc viewDidLoad];
  27. }
-(void) applicationDidEnterBackground:(UIApplication *)application{
// [NSRunLoop currentRunLoop];
//
// UIApplication *app=[UIApplication sharedApplication];
// __block UIBackgroundTaskIdentifier bgTask;
// bgTask=[app beginBackgroundTaskWithExpirationHandler:^{
// dispatch_async(dispatch_get_main_queue(), ^{
// if(bgTask!=UIBackgroundTaskInvalid){
// bgTask=UIBackgroundTaskInvalid;
// }
// });
// }];
//
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// dispatch_async(dispatch_get_main_queue(), ^{
// if(bgTask!=UIBackgroundTaskInvalid){
// bgTask=UIBackgroundTaskInvalid;
// }
// });
// });
//
// [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
// NSLog(@"KeepAlive");
// }];
MainViewController *mvc=[[MainViewController alloc] init];
[mvc viewDidLoad]; }

网上也有很多,发现在模拟器下可以长时间运行,但在真实机下并不能运行。发现还是长时间播放一个无声的音频文件好一点.

-------------------如果有什么不好的地方,请指教。

phonegap ios插件开发及无限后台运行解决的更多相关文章

  1. IOS高级开发~开机启动&无限后台运行&监听进程

    一般来说, IOS很少给App后台运行的权限. 仅有的方式就是 VoIP. IOS少有的为VoIP应用提供了后台socket连接,定期唤醒并且随开机启动的权限.而这些就是IOS上实现VoIP App的 ...

  2. IOS开发~开机启动&无限后台运行&监听进程

    非越狱情况下实现: 开机启动:App安装到IOS设备设备之后,无论App是否开启过,只要IOS设备重启,App就会随之启动: 无限后台运行:应用进入后台状态,可以无限后台运行,不被系统kill: 监听 ...

  3. 原创翻译:iOS 应用程序 蓝牙后台运行

    默认情况下,普通的CoreBluetooth 任务中的大多数,无论是Central还是peripheral ,在后台或者挂起状况下都是无法进行的.也就是说,你可以通过宣布你的应用程序支持后台处理模式来 ...

  4. iOS保持App真后台运行

    https://www.jianshu.com/p/d466f2da0d33 在我看来,苹果系统与安卓系统最直观的区别就是后台处理方式了吧,安卓手机一旦开启了很多app放到后台,即使前台什么也不做,就 ...

  5. IOS开发使用GCD后台运行

    什么是GCD Grand Central Dispatch (GCD)是Apple开发的一个多核编程的解决方法.该方法在Mac OS X 10.6雪豹中首次推出,并随后被引入到了iOS4.0中.GCD ...

  6. Delphi IOS 蓝牙锁屏后台运行

    Delphi IOS 后台运行 同样的程序,编译成android,锁屏后继续运行正常,蓝牙通讯正常,但在IOS下锁屏后程序的蓝牙就中断通讯了? IOS的机制就是这样,锁屏就关闭了. 音乐播放器是怎么做 ...

  7. MongoDB服务重启及后台运行解决方法

    1 在MongoDB 安装目录下 新建一个test文件夹 mkdir /test 2 切换到MongoDB的安装目录(可通过 find -name 'mongod'命令查找安装目录)下 执行: bin ...

  8. ios GCD简单介绍 后台运行~

    本从实践出发简单说明: 首先,gcd是Grand Central Dispatch的缩写,意为多线程优化技术,是苹果为多核处理优化的技术.使用简单.清晰. 多线程就分同步.异步方法如下: //异步线程 ...

  9. iOS无限后台加速耗电的问题

    背景 总所周知,iPhone的电池容量本身比较小.所以iOS系统本身为了弥补这一短板做出了一个重大的优化 —— 『伪后台』. 这一机制是在iPhone在续航上发挥重大的作用,但是也因为『伪后台』限制了 ...

随机推荐

  1. localStorage的跨与实现方案

    实现原理: HTML5 的 postMessage 为解决跨域页面通信提供了一套可控的机制, 而 localStorage 则提供了易用简洁的本地存储方案? 这两者结合起来,能否实现跨域的本地存储呢 ...

  2. CentOS服务器的16个监控命令

    你可以通过图形化用户界面(GUI)程序来获取这些外壳命令提供的大量信息,具体取决于使用哪一种Linux发行版.比如说,SUSE Linux就有一款出色的.图形化配置和管理工具YaST,KDE的KDE ...

  3. freeCodeCamp:Diff Two Arrays

    比较两个数组,然后返回一个新数组,该数组的元素为两个给定数组中所有独有的数组元素.换言之,返回两个数组的差异. function diff(arr1, arr2) { var newArr = []; ...

  4. FusionCharts

    上一篇已经介绍了一款免费的JS图表插件,这一篇再介绍另一款图表插件,同样是免费的,同样是基于JS的,使用依然很简单.该插件的官方网站,貌似也是收费的,我们可以下载对应的免费版FusionCharts ...

  5. ORACLE的分组统计之ROLLUP(一)

    Oracle 9i以后,扩展了group by 的功能,能够满足大部分多维数据的分析统计功能,主要表现: 1. rollup,cube,grouping sets 扩展group by字句提供了丰富的 ...

  6. 数据校验validator 与 DWZ

    在做系统时经常会用到数据校验,数据校验可以自己写,也可以用现在成的,现在记录下两种类库使用方法, <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 ...

  7. UI3_UITableView

    // // AppDelegate.m // UI3_UITableView // // Created by zhangxueming on 15/7/13. // Copyright (c) 20 ...

  8. 了解常见的开源协议(BSD, GPL, LGPL,MIT)

    一直对各种开源协议比较模糊, 特意在网上搜索了一下资料, 整理总结,以作记录 如果不喜欢长篇大论的话, 看下图就可以了 基本概念了解: 1. Contributors 和 Recipients Con ...

  9. IEEE 802.15.4协议学习之物理层

    在详细讲述IEEE 802.15.4协议之前,谈谈自己这两个星期看协议过程中的一点心得,或者是收获吧. 看协议文档,一定要看有书签的,边看边在旁边做些备注,以便于后期整理.对于协议层次相关的,最好在纸 ...

  10. python——异常处理

    python处理异常的格式一般如下: try: A部分 Except  .... [as ..]: B部分 [ finally: C部分 Else: D部分 ] ps: 1.不管有没有异常,final ...