Service

https://github.com/fei-ke/GridViewAndPhoneRecorder

Service
Service是Android系统的后台服务组件,适用于开发无界面、长时间运行
的应用功能
特点
没有用户界面
比Activity 的优先级高,不会轻易被Android系统终止
即使Service被系统终止,在系统资源恢复后Service也将自动恢复运行状态
用于进程间通信(Inter Process Communication,IPC),解决两个不同Andr
oid应用程序进程之间的调用和通讯问题

Service简介
Service生命周期
活动生命周期
onCreate(): Service的生命周期开始,完成Service的初始化工作
onStart():活动生命周期开始,但没有与之对应的“停止”函数,因此可以近似认为活动生命周期也是以onDestroy()标志结束
onDestroy(): Service的生命周期结束,释放Service所有占用的资源

step1.写一个类,继承Service,重写onCreate(),onStartCommand(),onDestroy()方法
step2.在AnroidManifest.xml文件配置service
<service android:name=".service.MyFirstService"/>
step3.
****启动service

Intent intent = new Intent(getApplicationContext(),MyFirstService.class);
startService(intent);

第一次启动时,会调用onCreate()来创建service,之后会调用onStartCommand()启动服务
然后再startService()时,不再执行onCreate(),而是多次调用onStartCommand()

****停止service

Intent intent = new Intent(getApplicationContext(),MyFirstService.class);
stopService(intent);

那么此时会停止service,并回调onDestory()方法。

 

隐式启动service:
step1.定义AndroidManifest.xml

<service android:name=".service.MyFirstService">
    <intent-filter >
        <action android:name="com.anjoyo.myservice"/>
    </intent-filter>
</service>

step2.
Intent intent = new Intent();
intent.setAction("com.anjoyo.myservice");
startService(intent);

2.Service使用方法
启动方式分两种:绑定方式(bindService)、启动方式(startService)
通过调用Context.startService()启动Service,通过调用
Context.stopService()或Service.stopSefl()停止Service
Service是由其他的组件启动的,但停止过程可以通过其他组件或自身完成
如果仅以启动方式使用的Service,这个Service需要具备自管理的能力,
且不需要通过函数调用向外部组件提供数据或功能

例子:
通过监听电话状态,如果电话被接通,那么启动service后台录音

录音:

MediaRecorder recorder;
recorder = new MediaRecorder();
//声音源为话筒
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//设置输出格式
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
//音频编码
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(
        "/mnt/sdcard/record_"+
        (new SimpleDateFormat("yyyyMMdd_HHmmss")
        .format(new Date()))+".amr");
recorder.prepare();
recorder.start();

权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>

注意:
setAudioEncoder()必须在setOutputFormat()之后运行。

 

监听电话状态
step1.获取TelephonyManager对象

TelephonyManager teleMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
teleMan.listen(new MyPhoneStateListener(this), PhoneStateListener.LISTEN_CALL_STATE);
step2.写那个类MyPhoneStateListner,实现PhoneStateListener接口
public class MyPhoneStateListener extends PhoneStateListener {
    private MediaRecorder recorder ;
    boolean isRecoder = false;
    Context context;
    public MyPhoneStateListener(Context context) {
        this.context = context;
    }
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
        case TelephonyManager.CALL_STATE_OFFHOOK:
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            File sdcardFile = Environment.getExternalStorageDirectory();
            String fileName = "record_"+
                    (new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new Date()))+".amr";
            recorder.setOutputFile(new File(sdcardFile,fileName).getAbsolutePath());
            try {
                recorder.prepare();
                recorder.start();
                isRecoder = true;
                Toast.makeText(context, "开始录音...", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                isRecoder = false;
            } 
            break;
        case TelephonyManager.CALL_STATE_IDLE:
            if(isRecoder){
                recorder.stop();
                isRecoder = false;
                Toast.makeText(context, "录音结束...", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
}
step3.manifest.xml文件中声明权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
posted on 2013-01-03 15:32  @与非  阅读(797)  评论(0编辑  收藏  举报