phonegap ios外掛程式開發及無限後台運行解決

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   os   ar   使用   java   

1.首先開發外掛程式:因為我的項目前需要所以要做(根據情況)

   在項目的plugins檔案中建立obj c檔案。如

   Demo,此時會產生出Demo.h和Demo.m兩個檔案。

   .h檔案主要就是定義一些方法,類似java中的介面.(要繼承CDVPlugin)

   .m檔案是對h檔案夾的實現,在外掛程式執行時會進入相應的函數,切記:此函數要易執行長時的內容,此時uithread處於阻塞狀態。不用我們可以啟動一個線程在函數中,啟動線的的的函數如下:

Java代碼  
  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:

Java代碼  
  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

  

Java代碼  
  1. var Demo=function(){  
  2.    
  3.   }  
  4.   Demo.prototype={  
  5.   method:function(fun1,fun2,params){cordova.exec(fun1//成功時調用,fun2,‘外掛程式名‘,‘外掛程式的方法名‘,[params//參數數組]);  
  6. }  
  7. }  
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,

 

Java代碼  
  1. #import <Cordova/CDVViewController.h>  
  2. #import <Cordova/CDVCommandDelegateImpl.h>  
  3. #import <Cordova/CDVCommandQueue.h>  
  4. #import <AVFoundation/AVFoundation.h>  
  5.   
  6. @interface MainViewController : CDVViewController{  
  7.     AVAudioPlayer *audioPlayer;  
  8. }  
  9. @property(nonatomic) AVAudioPlayer * audioPlayer;  
  10. @end  
  11.   
  12. @interface MainCommandDelegate : CDVCommandDelegateImpl  
  13. @end  
  14.   
  15. @interface MainCommandQueue : CDVCommandQueue  
  16. @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方法,修改為:

Java代碼  
  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.           
  15.           
  16.         NSBundle *mainBundle = [NSBundle mainBundle];  
  17.         NSLog(@"%@",mainBundle);  
  18.         NSString *filePath = [mainBundle pathForResource:@"love" ofType:@"wav"];  
  19.         NSData *fileData = [NSData dataWithContentsOfFile:filePath];  
  20.         NSError *error = nil;  
  21.         NSLog(@"AA%@",filePath);  
  22.         self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];  
  23.           
  24.         if (self.audioPlayer != nil){  
  25.             self.audioPlayer.delegate = self;  
  26.               
  27.             [self.audioPlayer setNumberOfLoops:-1];  
  28.             if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){  
  29.                 NSLog(@"Successfully started playing...");  
  30.             } else {  
  31.                 NSLog(@"Failed to play.");  
  32.             }  
  33.         } else {  
  34.             NSLog(@"Failed to play.");  
  35.         }  
  36.     });  
  37.    
  38. }  
- (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檔案,新增方法:

Java代碼  
  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.   
  28. }  
-(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外掛程式開發及無限後台運行解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.