Service的电话录音实例
更新时间:2012/11/1 点击:1338次
我们知道,Android有四大组件,分别是Activity,Content Provider , Broadcast Receiver 和今天我们要用到的Service。
我们说Service是看不见摸不着的,是因为它对用户是不可见的,Service作为四大组件之一,它的职责是工作在后台,处理
一些比较耗时的操作(如下载,播放媒体文件,检测版本更新和日志输出等)。
就像学习Activity组件一样,要想熟悉Service,必须知道它的整个工作流程,即它的生命周期(Life-cycle),下面是官网给
出的一个具体图例:
从图例我们可以知道,Service有两种启动方式,第一种是调用Context.startService()方法,
另外一种是调用Context.bindService().
对于第一种调用方法,系统会先调用onCreate()方法,负责初始化工作,然后调用onStart()方法,
启动Service,如果程序显示调用Context.stopService()方法或者Service自身调用stopSelf()方法
或者stopSelfResult()方法,都会调用onDestroy()方法,结束该服务,另外需要注意的是,调用者
和Service是没有关联的,也就是说,如果调用者退出了,并不会影响服务的运行。
对于第二种方式,调用方法是Context.bindService(),系统会先调用onCreate()方法,然后调用onBind()
方法,和调用者绑定,如果调用者退出,服务会调用onDestroy()方法结束自己的运行。
学完了一个东西,如果趁热打铁,自己编写一个demo,肯定会加深对该知识点的理解。
废话少说,下面给出一个电话录音的例子:
首先,也是最重要的,关于权限的声明:
[html] view plaincopyprint?
01.<!-- 电话状态监听权限 -->
02.<uses-permission android:name="android.permission.READ_PHONE_STATE" />
03.<!-- 开机广播权限 -->
04.<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
05.
06.<!-- 音频刻录权限 -->
07.<uses-permission android:name="android.permission.RECORD_AUDIO" />
08.<!-- 写入权限 -->
09.<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 电话状态监听权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 开机广播权限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- 音频刻录权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- 写入权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
接下来是编写一个简单的Activity,用来启动Broadcast Receiver组件。
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- 写入权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
接下来是编写一个简单的Activity,用来启动Broadcast Receiver组件。
[java] view plaincopyprint?
01.package com.example.service_record_call;
02.
03.import android.app.Activity;
04.import android.content.Intent;
05.import android.os.Bundle;
06.
07.public class MainActivity extends Activity {
08.
09. @Override
10. public void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13.
14. Intent receiver = new Intent("zjut.tsw.receiver");
15. this.sendBroadcast(receiver);
16. }
17.
18.
19.}
package com.example.service_record_call;
01.package com.example.service_record_call;
02.
03.import android.app.Activity;
04.import android.content.Intent;
05.import android.os.Bundle;
06.
07.public class MainActivity extends Activity {
08.
09. @Override
10. public void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13.
14. Intent receiver = new Intent("zjut.tsw.receiver");
15. this.sendBroadcast(receiver);
16. }
17.
18.
19.}
package com.example.service_record_call;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent receiver = new Intent("zjut.tsw.receiver");
this.sendBroadcast(receiver);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent receiver = new Intent("zjut.tsw.receiver");
this.sendBroadcast(receiver);
}
}
然后是编写一个简单的Broadcast Receiver,负责启动Service
[java] view plaincopyprint?
01.package com.example.service_record_call;
02.
03.import android.content.BroadcastReceiver;
04.import android.content.Context;
05.import android.content.Intent;
06.
07.public class MyBroadcastReceiver extends BroadcastReceiver {
08.
09. @Override
10. public void onReceive(Context context, Intent intent) {
11. Intent service = new Intent(context,PhoneListenerService.class);
12. context.startService(service);
13. }
14.
15.}
package com.example.service_record_call;
01.package com.example.service_record_call;
02.
03.import android.content.BroadcastReceiver;
04.import android.content.Context;
05.import android.content.Intent;
06.
07.public class MyBroadcastReceiver extends BroadcastReceiver {
08.
09. @Override
10. public void onReceive(Context context, Intent intent) {
11. Intent service = new Intent(context,PhoneListenerService.class);
12. context.startService(service);
13. }
14.
15.}
package com.example.service_record_call;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,PhoneListenerService.class);
context.startService(service);
}
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,PhoneListenerService.class);
context.startService(service);
}
}
接下来是编写核心Service.
[java] view plaincopyprint?
01.package com.example.service_record_call;
02.
03.import java.io.File;
04.
05.import android.app.Service;
06.import android.content.Context;
07.import android.content.Intent;
08.import android.media.MediaRecorder;
09.import android.os.Environment;
10.import android.os.IBinder;
11.import android.telephony.PhoneStateListener;
12.import android.telephony.TelephonyManager;
13.import android.util.Log;
14.
15.public class PhoneListenerService extends Service {
16.
17.
18. private final String TAG = "PhoneListenerService";
19. @Override
20. public IBinder onBind(Intent intent) {
21. return null;
22. }
23.
24. @Override
25. public void onCreate() {
26. TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
27. telephonyManager.listen(new TeleListine(), PhoneStateListener.LISTEN_CALL_STATE);
28. Log.i(TAG,"onCreate");
29. super.onCreate();
30. }
31.
32. private class TeleListine extends PhoneStateListener {
33.
34. private String mobile; //来电电话
35. private MediaRecorder recorder; //多媒体刻录文件
36. private File autoFile; //保存文件
37. private boolean recoder; //是否刻录
38.
39. @Override
40. public void onCallStateChanged(int state,String incomingNumber) {
41. try{
42. switch(state) {
43. case TelephonyManager.CALL_STATE_IDLE :
44.
45. if(recoder) {
46. recorder.stop();
47. recorder.release();
48. recoder = false;
49. }
50. break;
51.
52. case TelephonyManager.CALL_STATE_OFFHOOK :
53. recorder = new MediaRecorder();
54. recorder.setAudioSource(MediaRecorder.AudioSource.MIC); //这里只是录制自己的声音,如果想录制双方的通话声音,可改用MediaRecorder.AudioSource.VOICE_CALL
55. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
56. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
57. String root_directory = Environment.getExternalStorageDirectory() + "/recorded_calls";
58. File root_file = new File(root_directory);
59. if(!root_file.exists()) {
60. root_file.mkdir();
61. }
62. String record_call = root_directory + "/" + mobile + "_" + System.currentTimeMillis() + ".3gp";
63. File autoFile = new File(record_call);
64. if(!autoFile.exists()) {
65. autoFile.createNewFile();
66. }
67. //autoFile = new File(getCacheDir(),mobile+ "_" + System.currentTimeMillis() + ".3gp");
68. recorder.setOutputFile(autoFile.getAbsolutePath());
69. recorder.prepare();
70. recorder.start();
71. recoder = true;
72. Log.i(TAG,"接起电话");
73. break;
74.
75. case TelephonyManager.CALL_STATE_RINGING :
76. mobile = incomingNumber;
77. Log.i(TAG,"mobile=" + mobile);
78. break;
79. default :
80. break;
81. }
82. }catch(Exception e) {
83. Log.i(TAG,e.toString());
84. e.printStackTrace();
85. }
86. super.onCallStateChanged(state, incomingNumber);
87. }
88.
89.
90. }
91.
92.}
package com.example.service_record_call;
01.package com.example.service_record_call;
02.
03.import java.io.File;
04.
05.import android.app.Service;
06.import android.content.Context;
07.import android.content.Intent;
08.import android.media.MediaRecorder;
09.import android.os.Environment;
10.import android.os.IBinder;
11.import android.telephony.PhoneStateListener;
12.import android.telephony.TelephonyManager;
13.import android.util.Log;
14.
15.public class PhoneListenerService extends Service {
16.
17.
18. private final String TAG = "PhoneListenerService";
19. @Override
20. public IBinder onBind(Intent intent) {
21. return null;
22. }
23.
24. @Override
25. public void onCreate() {
26. TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
27. telephonyManager.listen(new TeleListine(), PhoneStateListener.LISTEN_CALL_STATE);
28. Log.i(TAG,"onCreate");
29. super.onCreate();
30. }
31.
32. private class TeleListine extends PhoneStateListener {
33.
34. private String mobile; //来电电话
35. private MediaRecorder recorder; //多媒体刻录文件
36. private File autoFile; //保存文件
37. private boolean recoder; //是否刻录
38.
39. @Override
40. public void onCallStateChanged(int state,String incomingNumber) {
41. try{
42. switch(state) {
43. case TelephonyManager.CALL_STATE_IDLE :
44.
45. if(recoder) {
46. recorder.stop();
47. recorder.release();
48. recoder = false;
49. }
50. break;
51.
52. case TelephonyManager.CALL_STATE_OFFHOOK :
53. recorder = new MediaRecorder();
54. recorder.setAudioSource(MediaRecorder.AudioSource.MIC); //这里只是录制自己的声音,如果想录制双方的通话声音,可改用MediaRecorder.AudioSource.VOICE_CALL
55. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
56. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
57. String root_directory = Environment.getExternalStorageDirectory() + "/recorded_calls";
58. File root_file = new File(root_directory);
59. if(!root_file.exists()) {
60. root_file.mkdir();
61. }
62. String record_call = root_directory + "/" + mobile + "_" + System.currentTimeMillis() + ".3gp";
63. File autoFile = new File(record_call);
64. if(!autoFile.exists()) {
65. autoFile.createNewFile();
66. }
67. //autoFile = new File(getCacheDir(),mobile+ "_" + System.currentTimeMillis() + ".3gp");
68. recorder.setOutputFile(autoFile.getAbsolutePath());
69. recorder.prepare();
70. recorder.start();
71. recoder = true;
72. Log.i(TAG,"接起电话");
73. break;
74.
75. case TelephonyManager.CALL_STATE_RINGING :
76. mobile = incomingNumber;
77. Log.i(TAG,"mobile=" + mobile);
78. break;
79. default :
80. break;
81. }
82. }catch(Exception e) {
83. Log.i(TAG,e.toString());
84. e.printStackTrace();
85. }
86. super.onCallStateChanged(state, incomingNumber);
87. }
88.
89.
90. }
91.
92.}
package com.example.service_record_call;
import java.io.File;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneListenerService extends Service {
private final String TAG = "PhoneListenerService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new TeleListine(), PhoneStateListener.LISTEN_CALL_STATE);
Log.i(TAG,"onCreate");
super.onCreate();
}
private class TeleListine extends PhoneStateListener {
private String mobile; //来电电话
private MediaRecorder recorder; //多媒体刻录文件
private File autoFile; //保存文件
private boolean recoder; //是否刻录
@Override
public void onCallStateChanged(int state,String incomingNumber) {
try{
switch(state) {
case TelephonyManager.CALL_STATE_IDLE :
if(recoder) {
recorder.stop();
recorder.release();
recoder = false;
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK :
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); //这里只是录制自己的声音,如果想录制双方的通话声音,可改用MediaRecorder.AudioSource.VOICE_CALL
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
String root_directory = Environment.getExternalStorageDirectory() + "/recorded_calls";
File root_file = new File(root_directory);
if(!root_file.exists()) {
root_file.mkdir();
}
String record_call = root_directory + "/" + mobile + "_" + System.currentTimeMillis() + ".3gp";
File autoFile = new File(record_call);
if(!autoFile.exists()) {
autoFile.createNewFile();
}
//autoFile = new File(getCacheDir(),mobile+ "_" + System.currentTimeMillis() + ".3gp");
recorder.setOutputFile(autoFile.getAbsolutePath());
recorder.prepare();
recorder.start();
recoder = true;
Log.i(TAG,"接起电话");
break;
case TelephonyManager.CALL_STATE_RINGING :
mobile = incomingNumber;
Log.i(TAG,"mobile=" + mobile);
break;
default :
break;
}
}catch(Exception e) {
Log.i(TAG,e.toString());
e.printStackTrace();
}
super.onCallStateChanged(state, incomingNumber);
}
}
}
别忘了在AndroidManifest.xml中注册组件Service和Broadcast Receiver
[html] view plaincopyprint?
01.<receiver android:name=".MyBroadcastReceiver" >
02. <intent-filter>
03. <action android:name="android.intent.action.BOOT_COMPLETED" />
04. <action android:name="zjut.tsw.receiver" />
05. </intent-filter>
06.</receiver>
07.
08.<service android:name=".PhoneListenerService" >
09.</service>
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="zjut.tsw.receiver" />
</intent-filter>
</receiver>
01.<receiver android:name=".MyBroadcastReceiver" >
02. <intent-filter>
03. <action android:name="android.intent.action.BOOT_COMPLETED" />
04. <action android:name="zjut.tsw.receiver" />
05. </intent-filter>
06.</receiver>
07.
08.<service android:name=".PhoneListenerService" >
09.</service>
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="zjut.tsw.receiver" />
</intent-filter>
</receiver>
<service android:name=".PhoneListenerService" >
</service>
这样,当您打开了该软件,或者开机后,该服务会自动启动并运行(你可以在Android机上按Menu键->设置->应用程序->运行的服务 查看该服务的具体状态)
</service>
这样,当您打开了该软件,或者开机后,该服务会自动启动并运行(你可以在Android机上按Menu键->设置->应用程序->运行的服务 查看该服务的具体状态)
当有人打电话给你或者你打给别人,电话录音会保存在/recorded_calls/...里面。(该程序含有潜在的错误,如果通话时间足够多或足够长(煲电话粥的同志们注意了哦),可能会导致SD卡内存不足)