在Titanium中使用Android的Service
在使用Titanium做MP3播放器的时候,对于Android平台,我们可以不用特别的考虑,使用Titanium.Media.AudioPlayer、Titanium.Media.Sound等函数即可在播放声音,当前Activity终了新的Activity生成的时候,正在播放的身音也不会被中止。
在我们使用手机时,往往是多线程的,而且是会突然间断的。比如我们会一边浏览网页,一边听MP3,或者正在发短信的时候,突然打进来电话。这样我们必定会离开当前的用户界面。比如你会关闭MP3歌曲列表,去发短信,所以往往就需要有些程序在后台完成,暂时脱离屏幕。
那么对于Android平台来说,是如何实现的呢?答案很简单,这时就可以用到Android中的Service!
我们查看Titanium的例子KitchenSink可以发现,Titanium也支持Service。
<ti:app xmlns:ti="http://ti.appcelerator.org"> <android xmlns:android="http://schemas.android.com/apk/res/android"> <tool-api-level>7</tool-api-level> <manifest> <uses-sdk android:minSdkVersion="7"/> </manifest> <services> <service type="interval" url="playSoundService.js"/> </services> <activities/> </android></ti:app>
Titanium会为你自动生成以下代码:
import ti.modules.titanium.android.TiJSIntervalService;public final class PlaySoundServiceService extends TiJSIntervalService {public PlaySoundServiceService() {super("playSoundService.js");}}
<service android:name="《tiapp_id》.PlaySoundServiceService"/>
var soundIntent = Ti.Android.createServiceIntent( { url: 'playSoundService.js' } );soundIntent.putExtra('interval', 1000);
sound_service = Ti.Android.createService( soundIntent );sound_service.start();
var service = Ti.Android.currentService;var intent = service.intent;if( !service.initialized ){service.addEventListener( 'playSound' , function( e ){if( service.sound == undefined || service.sound.url != service.fileToPlay ){if( service.sound ){service.sound.stop();}service.sound = Ti.Media.createSound({url:service.fileToPlay});}service.sound.play();});service.addEventListener( 'pauseSound' , function( e ){service.sound.pause();});service.addEventListener( 'resumeSound' , function( e ){service.sound.play();});service.addEventListener( 'stopSound' , function( e ){service.sound.stop();});service.initialized = true;}
var sound_service;var soundIntent = Ti.Android.createServiceIntent( { url: 'playSoundService.js' } );if( Ti.Android.isServiceRunning( soundIntent ) == false ){Ti.API.info( 'service is not Running' );soundIntent.putExtra('interval', 1000);sound_service = Ti.Android.createService( soundIntent );sound_service.addEventListener('resume', function(e) {if( e.source.sound ){Ti.API.info( 'sound.getTime() ' + e.source.sound.getTime() );}});sound_service.addEventListener('pause', function(e) {});sound_service.addEventListener('stop', function(e) {Ti.API.info('Service is stopped');});sound_service.start();}else{Ti.API.info( 'service is Running' );sound_service = Ti.Android.currentService;}
sound_service.fileToPlay = 'music.mp3';sound_service.fireEvent( 'startSound' );