关于android service 的具体解释请參考: android四大组件--android service具体解释。以下将用两个实例具体呈现Android Service的两种实现。

一个是startService()方法来启动一个服务,这里用电话录音的样例。

还有一个是bindService()方法来绑定一个服务,这里用获取系统当前时间的样例;

实例一(电话录音):

/CallRecorderService/res/layout/main.xml

<?

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <TextView
android:id="@+id/tvTemp"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:gravity="center"
android:text="@string/hello"
android:textSize="30dip" /> <Button
android:id="@+id/startrecordservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开启电话录音的功能" /> </LinearLayout>

/CallRecorderService/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?

>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zymic.callrecord"
android:versionCode="1"
android:versionName="1.0" > <application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".CallRecord01"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <service
android:name="CallRecordService"
android:enabled="true" >
</service>
</application> <uses-sdk android:minSdkVersion="7" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission> </manifest>

以下将是三个核心的实现

/CallRecorderService/src/com/bing/callrecord/CallRecordService.java

package com.bing.callrecord;

import java.io.File;
import java.io.IOException; import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast; public class CallRecordService extends Service { @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} @Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "录音服务已经创建!", Toast.LENGTH_LONG).show();
} @Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "录音服务已经销毁!", Toast.LENGTH_LONG).show();
} @Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "录音服务已经启动!", Toast.LENGTH_LONG).show();
//
TelephonyManager telephonymanager=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonymanager.listen(new PhoneListener(getApplicationContext()), PhoneStateListener.LISTEN_CALL_STATE); } }

/CallRecorderService/src/com/bing/callrecord/PhoneListener.java

package com.bing.callrecord;

import java.io.File;
import java.io.IOException; import android.content.Context;
import android.media.MediaRecorder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast; public class PhoneListener extends PhoneStateListener {
File audioFile;
MediaRecorder mediaRecorder; //= new MediaRecorder();
Context c;
//
boolean iscall=false;
//
public PhoneListener(Context context){
c=context;
iscall=false;
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
mediaRecorder = new MediaRecorder();
switch(state){
case TelephonyManager.CALL_STATE_OFFHOOK:
iscall=true;
try {
recordCallComment(); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mediaRecorder.stop();
}
Toast.makeText(c, "正在录音", Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_IDLE:
//if(mediaRecorder!=null){
//mediaRecorder.stop();
//mediaRecorder=null;
//}
if(iscall){
mediaRecorder.stop();
iscall=false;
}
break;
}
}
//
public void recordCallComment() throws IOException{
System.out.println(mediaRecorder);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder
.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
audioFile = File.createTempFile("record_", ".amr");
mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
mediaRecorder.prepare();
mediaRecorder.start();
} }

/CallRecorderService/src/com/bing/callrecord/CallRecorder.java

package com.bing.callrecord;

import com.zymic.callrecord.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; public class CallRecorder extends Activity {
private Button beginrecordservice;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
beginrecordservice=(Button)findViewById(R.id.startrecordservice);
beginrecordservice.setOnClickListener(new BeginRecord());
}
//
private class BeginRecord implements OnClickListener{ @Override
public void onClick(View v) {
Intent serviceIntent=new Intent(getApplicationContext(),CallRecordService.class);
getApplicationContext().startService(serviceIntent); } }
}

最后效果图例如以下:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTA2NzM2MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />

实例二(获取当前时间):

界面代码实现:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" > <TextView
android:id="@+id/tvTemp"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:gravity="center"
android:textSize="30dip"
android:text="@string/hello" /> <Button
android:id="@+id/btnStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btnBind_name" /> <Button
android:id="@+id/btnStop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btnUnbind_name" /> <TextView
android:id="@+id/tvInfo"
android:layout_width="fill_parent"
android:layout_height="100dip" /> </LinearLayout>

在Manifest里面声明服务,加入MyService声明.

<?

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gel.service"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" android:exported="true"></service>
</application> </manifest>

加入一个MyService类.代码例如以下:

package com.gel.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { private MyService mMyService;
private TextView mTextView;
private Button bindServiceButton;
private Button unbindServiceButton;
private Context mContext; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupViews();
} private ServiceConnection mServiceConnection = new ServiceConnection() {
// 当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mMyService = ((MyService.MyBinder) service).getService();
mTextView.setText("来自MyService的系统时间:"
+ mMyService.getSystemTime());
} public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub }
}; public void setupViews() { mContext = MainActivity.this;
mTextView = (TextView)findViewById(R.id.tvInfo); bindServiceButton = (Button) findViewById(R.id.btnStart);
unbindServiceButton = (Button) findViewById(R.id.btnStop); bindServiceButton.setOnClickListener(this);
unbindServiceButton.setOnClickListener(this);
} public void onClick(View v) {
// TODO Auto-generated method stub
if (v == bindServiceButton) {
Intent i = new Intent();
i.setClass(MainActivity.this, MyService.class);
mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);
} else {
mContext.unbindService(mServiceConnection);
}
} }

创建Bound Service,MyService代码:

 

package com.gel.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log; public class MyService extends Service { // 定义个一个Tag标签
private static final String TAG = "MyService";
// 这里定义一个Binder类,用在onBind()有方法里。这样Activity那边能够获取到
private MyBinder mBinder = new MyBinder(); @Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "Start IBinder!");
return mBinder;
} @Override
public void onCreate() {
Log.e(TAG, "Start onCreate!");
super.onCreate();
} @Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "Start onStart!");
super.onStart(intent, startId);
} @Override
public void onDestroy() {
Log.e(TAG, "Start onDestroy!");
super.onDestroy();
} @Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "Start onUnbind!");
return super.onUnbind(intent);
} // 这里我写了一个获取当前时间的函数,
public String getSystemTime() {
Time t = new Time();
t.setToNow();
return t.toString();
} public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
} }

最后的效果例如以下:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTA2NzM2MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />

android service 样例(电话录音和获取系统当前时间)的更多相关文章

  1. java获取系统指定时间年月日

    java获取系统指定时间年月日 private String setDateTime(String falg) { Calendar c = Calendar.getInstance(); c.set ...

  2. Unity3D获取系统当前时间,并格式化显示

    Unity 获取系统当前时间,并格式化显示.通过“System.DateTime”获取系统当前的时间,然后通过格式化把获得的时间格式化显示出来,具体如下: 1.打开Unity,新建一个空工程,Unit ...

  3. Oracle,MySQL,sqlserver三大数据库如何获取系统当前时间

    Oracle中如何获取系统当前时间:用SYSDATE() MySQL中获取系统当前时间主要有以下几点: (1)now()函数以('YYYY-MM-dd HH:mm:SS')返回当前的日期时间,可以直接 ...

  4. java 获取系统当前时间并格式化

      java 获取系统当前时间并格式化 CreateTime--2018年5月9日11:41:00 Author:Marydon 实现方式有三种 updateTime--2018年7月23日09点32 ...

  5. 使用js时,如何获取系统当前时间并且得到格式为"yyyy年MM月"的日期

    1.使用js时,如何获取系统当前时间并且得到格式为"yyyy年MM月"的日期: 1 var newdate = new Date(); 2 var nowyear = newdat ...

  6. C++ 获取系统当前时间(日历时)

    获取系统当前时间(日历时) //Linux & C++11 #include <chrono> #include <ctime> using namespace std ...

  7. C# 获取系统开机时间

    原文:C# 获取系统开机时间 ///         ///  获取系统开机时间          ///         ///         private DateTime GetComput ...

  8. C/C++获取系统当前时间

    C/C++获取系统当前时间   C库中与系统时间相关的函数定义在<time.h>头文件中, C++定义在<ctime>头文件中. 一.time(time_t*)函数 函数定义如 ...

  9. T_SQL 获取系统当前时间与明天时间的两种格式

    --获取系统明天的时间 select CONVERT(nvarchar(20),dateadd(d,1,getdate()),120)         2017-01-21 15:04:10 sele ...

随机推荐

  1. 递归算法介绍及Java应用实战

    什么是递归算法 递归算法是把问题转化为规模缩小了的同类问题的子问题,然后递归调用函数(或过程)来表示问题的解.一个过程(或函数)直接或间接调用自己本身,这种过程(或函数)叫递归过程(或函数). 递归过 ...

  2. C++中初始化列表的使用

    1,初始化列表是在 C++ 中才引入的: 2,以“类中是否可以定义 const 成员?”这个问题来引入初始化列表: 1,const 这个关键字可以定义真正意义上的常量,也可以在某些情况下定义只读变量: ...

  3. vue实现全选反选--简单使用

    最近需要用到vue的反选全选功能,于是就在网上找了一些代码实现,发现都不能够完美的实现.于是乎决定自己写出一套.经过一翻努力,完美了进行了实现.bug也已经修复完毕,希望能够帮助到大家!   < ...

  4. 【转】SQLSERVER磁盘原理

    [声明:本篇博客转载自http://www.cnblogs.com/ljhdo/p/5149401.html] 最近一段时间的工作主要是与SQLSERVER数据库打交道,需要对SQLSERVER有一个 ...

  5. Mongo 备份

    1. Windows下远程连接服务器上的MongoDB数据库 使用的是mongo命令,如果安装mongodb时配置了环境变量,可以直接快捷键windows+R打开cmd. Cmd  --- mongo ...

  6. Electron-vue实战(二)— 请求Mock数据渲染页面

    Electron-vue实战(二)— 请求Mock数据渲染页面 作者:狐狸家的鱼 本文链接 GitHub:sueRimn 一.环境搭建 1.安装Mock.js 如果仅仅用作脱离后台的模拟数据,就安装在 ...

  7. Steup Factory 操作注册表

    //判断注册表是否存在,不存在就创建 result = Registry.DoesKeyExist(HKEY_CURRENT_USER, "SOFTWARE\\MyTestApp" ...

  8. 木棍加工(dp,两个参数的导弹拦截问题)

    题目描述 一堆木头棍子共有n根,每根棍子的长度和宽度都是已知的.棍子可以被一台机器一个接一个地加工.机器处理一根棍子之前需要准备时间.准备时间是这样定义的:     第一根棍子的准备时间为1分钟:   ...

  9. 【Flutter学习】基本组件之TabBar顶部导航

    一,概述 TabBar,是材料设计(Material design)中很常用的一种横向标签页.在Android原生开发中,我们常用ViewPage或者一些常用的标签页开源库,来实现并行界面的横向滑动展 ...

  10. Python基础(一):程序输入输出、判断合法用户、编写判断成绩的程序

    一.程序输入输出 目标: 编写login.py脚本,实现以下目标: 提示用户输入用户名 将用户名保存在变量中 在屏幕上显示欢迎用户的信息 方案: 编写程序时,很多情况下都需要程序与用户交互.在pyth ...