Android四大组件之Service(服务)实例详解

来源:互联网 发布:获取httppost请求数据 编辑:程序博客网 时间:2024/06/17 13:15

这篇文章主要介绍了Android四大组件之Service(服务)的用法,结合实例形式详细分析了Service的基本概念,类型,用法与相关注意事项,需要的朋友可以参考下


本文实例讲述了Android四大组件之服务用法。分享给大家供大家参考,具体如下:

很多情况下,一些与用户很少需要产生交互的应用程序,我们一般让它们在后台运行就行了,而且在它们运行期间我们仍然能运行其他的应用。

为了处理这种后台进程,Android引入了Service的概念。Service在Android中是一种长生命周期的组件,它不实现任何用户界面。

基本概念

Ÿ   Service是一种在后台运行,没有界面的组件,由其他组件调用开始。
Ÿ   创建Service,定义类继承Service,AndroidManifest.xml中定义<service>
Ÿ   开启Service,在其他组件中调用startService方法
Ÿ   停止Service,调用stopService方法

1.在activity中调用service

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 * 开启服务
 */
public void start(View view) {
  Intent intent = new Intent(this, MyService.class);
  startService(intent);
}
/*
 * 结束服务
 */
public void stop(View view) {
  Intent intent =new Intent(this, MyService.class);
  stopService(intent);
}

2.定义Service:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyService extendsService {
  /*
   * 绑定时调用
   */
  public IBinder onBind(Intent intent) {
    return null;
  }
  /*
   * 开启服务时调用
   */
  public void onCreate() {
    super.onCreate();
    System.out.println("onCreate");
  }
  /*
   * 结束服务时调用
   */
  publicvoid onDestroy() {
    super.onDestroy();
    System.out.println("onDestroy");
  }
}

3.在清单文件中进行定义服务

复制代码 代码如下:
<service android:name=".PMyService" />

电话录音

电话录音是使用服务来实现的,在后台运行,使用监听器来监听电话的状态,当来电话时,监听器获取到来电话的电话号码,当用户接听后,就开始录音,当监听到电话的状态挂断后,停止录音,并将录音保存到sdcard中。

java代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@Override
public void onCreate() {
  //拿到电话服务
  TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  //电话的状态监听器
  manager.listen(newMyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
private final class MyListenerextends PhoneStateListener {
  privateString num;
  privateMediaRecorder recorder;  //录音
  privateFile file;
  publicvoid onCallStateChanged(intstate, String incomingNumber) {
    switch(state) {
      //响铃状态
      caseTelephonyManager.CALL_STATE_RINGING:
        //保存电话号
        num = incomingNumber;
        break;
      //接通电话状态
      caseTelephonyManager.CALL_STATE_OFFHOOK:
        try{
          //设置文件保存位置
          file =new File(Environment.getExternalStorageDirectory(), num +"_" + System.currentTimeMillis() +".3gp");
          //创建录音器
          recorder =new MediaRecorder();
          //设置音频的来源(麦克风)
          recorder.setAudioSource(AudioSource.MIC);
          //采取3gp格式保存
          recorder.setOutputFormat(OutputFormat.THREE_GPP);
          //设置编码器
          recorder.setAudioEncoder(AudioEncoder.AMR_NB);
          //输出文件路径
          recorder.setOutputFile(file.getAbsolutePath());
          //准备
          recorder.prepare();
          //录音
          recorder.start();
        }catch (Exception e) {
          e.printStackTrace();
        }
        break;
      //电话空闲状态
      caseTelephonyManager.CALL_STATE_IDLE:
        //电话挂断后停止录音
        if(recorder != null) {
          recorder.stop();
          recorder.release();
        }
        break;
    }
  }
}

权限:

?
1
2
3
4
5
6
7
8
9
10
<!-- 读电话的状态权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- 录音权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- sdCard读的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- sdCard写的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 打开网络权限 -->
<uses-permission android:name="android.permission.INTERNET"/>

绑定本地服务

绑定本地服务实际上就是activity和服务进行绑定,activity一般是和用户进行交互,而服务一般是进行后台的工作,如果activity中需要访问服务中的一些方法,进行交互,这就需要进行绑定。

Ÿ   使用bindService绑定服务,传入一个自定义的ServiceConnection用来接收IBinder
Ÿ   定义一个业务接口,其中定义需要的使用的方法
Ÿ   服务中自定义一个IBinder继承Binder并实现业务接口,在onBind方法中返回
Ÿ   调用端将IBinder转为接口类型,调用接口中的方法即可调用到服务中的方法

Activity和Service进行绑定示例:

Activity:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MainActivity extendsActivity {
  privateQueryService qs;
  privateEditText editText;
  publicvoid onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    editText = (EditText) findViewById(R.id.id);
    // 绑定服务, 传入ServiceConnection用来接收IBinder
    bindService(newIntent(this, PersonService.class),new MyConn(), BIND_AUTO_CREATE);
  }
  /*
   * 自定义的ServiceConnection用来接收IBinder
   */
  private final class MyConn implements ServiceConnection {
    public void onServiceConnected(ComponentName name, IBinder service) {
      qs = (QueryService) service;
    }
    public void onServiceDisconnected(ComponentName name) {
    }
  }
  /*
   * 根据Id获取联系人
   */
  publicvoid queryName(View view) {
    String id = editText.getText().toString();
    String name = qs.query(Integer.parseInt(id));
    Toast.makeText(this, name,0).show();
  }
}

Service:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class PersonService extendsService {
  privateString[] data = { "zxx","lhm", "flx"};
  /*
   * 当绑定时调用此方法, 返回一个IBinder, 用来调用当前服务中的方法
   */
  public IBinder onBind(Intent intent) {
    return new MyBinder();
  }
  /*
   * 查询方法
   */
  public String query(int id) {
    return data[id];
  }
  /*
   * 自定义IBinder, 实现QueryService业务接口, 提供给调用者访问当前服务的方法
   */
  privatefinal class MyBinder extends Binder implements QueryService {
    publicString query(intid) {
      returnPersonService.this.query(id);
    }
  }
}

绑定远程服务

Ÿ   远程绑定服务时无法通过同一个接口来调用方法,这时就需要使用AIDL技术
Ÿ   将接口扩展名改为“.aidl”
Ÿ   去掉权限修饰符
Ÿ   gen文件夹下会生成同名接口
Ÿ   将服务中自定义的IBinder类改为继承接口中的Stub
Ÿ   ServiceConnection中返回的IBinder是代理对象,不能使用强转,改用Stub.asInterface()

希望本文所述对大家Android程序设计有所帮助。


0 0