第一步:新建一个Android工程,我这里命名为ServiceDemo.

第二步:修改main.xml代码,我这里增加了四个按钮,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextViewandroid:id="@+id/text"      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    /><Buttonandroid:id="@+id/startservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="startService"/><Buttonandroid:id="@+id/stopservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="stopService"/><Buttonandroid:id="@+id/bindservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="bindService"/><Buttonandroid:id="@+id/unbindservice"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="unbindService"/></LinearLayout>

第三步:新建一个Service,命名为MyService.java代码如下:

package com.tutor.servicedemo;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();@Overridepublic IBinder onBind(Intent intent) {Log.e(TAG, "start IBinder~~~");return mBinder;}@Overridepublic void onCreate() {Log.e(TAG, "start onCreate~~~");super.onCreate();}@Overridepublic void onStart(Intent intent, int startId) {Log.e(TAG, "start onStart~~~");super.onStart(intent, startId);}@Overridepublic void onDestroy() {Log.e(TAG, "start onDestroy~~~");super.onDestroy();}@Overridepublic 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;}}}

第四步:修改ServiceDemo.java,代码如下:

package com.tutor.servicedemo;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 ServiceDemo extends Activity implements OnClickListener{   private MyService  mMyService;private TextView mTextView;private Button startServiceButton;private Button stopServiceButton;private Button bindServiceButton;private Button unbindServiceButton;private Context mContext;//这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到private ServiceConnection mServiceConnection = new ServiceConnection() {//当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值public void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubmMyService = ((MyService.MyBinder)service).getService();mTextView.setText("I am frome Service :" + mMyService.getSystemTime());}public void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}};    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        setupViews();    }        public void setupViews(){        mContext = ServiceDemo.this;    mTextView = (TextView)findViewById(R.id.text);                startServiceButton = (Button)findViewById(R.id.startservice);    stopServiceButton = (Button)findViewById(R.id.stopservice);    bindServiceButton = (Button)findViewById(R.id.bindservice);    unbindServiceButton = (Button)findViewById(R.id.unbindservice);        startServiceButton.setOnClickListener(this);    stopServiceButton.setOnClickListener(this);    bindServiceButton.setOnClickListener(this);    unbindServiceButton.setOnClickListener(this);    }   public void onClick(View v) {// TODO Auto-generated method stubif(v == startServiceButton){Intent i  = new Intent();i.setClass(ServiceDemo.this, MyService.class);mContext.startService(i);}else if(v == stopServiceButton){Intent i  = new Intent();i.setClass(ServiceDemo.this, MyService.class);mContext.stopService(i);}else if(v == bindServiceButton){Intent i  = new Intent();i.setClass(ServiceDemo.this, MyService.class);mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);}else{mContext.unbindService(mServiceConnection);}}}

第五步:修改AndroidManifest.xml代码(将我们新建的MyService注册进去如下代码第14行:)

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.tutor.servicedemo"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".ServiceDemo"                  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=".MyService" android:exported="true"></service>    </application>    <uses-sdk android:minSdkVersion="7" /></manifest>&nbsp;

第六步:执行上述工程,效果图如下:

Android之service实例_第1张图片

点击startServie按钮时先后执行了Service中onCreate()->onStart()这两个方法,打开Logcat视窗效果如下图:

Android之service实例_第2张图片

我们这时可以按HOME键进入Settings(设置)->Applications(应用)->Running Services(正在运行的服务)看一下我们新启动了一个服务,效果如下:

Android之service实例_第3张图片

点击stopService按钮时,Service则执行了onDestroy()方法,效果图如下所示:

这时候我们再次点击startService按钮,然后点击bindService按钮(通常bindService都是bind已经启动的Service),我们看一下Service执行了IBinder()方法,以及TextView的值也有所变化了,如下两张图所示:

Android之service实例_第4张图片

最后点击unbindService按钮,则Service执行了onUnbind()方法,如下图所示:

Android之service实例_第5张图片

更多相关文章

  1. Android当方法总数超过64K时(Android Studio)
  2. android开发之res下的menu (xml+代码的形式)
  3. android ViewPager 使用方法
  4. 【源代码】一键分享各个社交平台_android
  5. Android 方法数超过64k限制的解决办法
  6. android的Services生命周期和使用方法
  7. Android常用框架混淆代码
  8. Android之GLES2.0显示图片测试代码
  9. 【Android】使用代码动态创建布局

随机推荐

  1. Android使用的MQTT客户端
  2. Android(安卓)ListFragment自定义view报
  3. Android中的Handler、Looper、Message简
  4. Android小米(miui)获取通话记录为null解决
  5. 解决Cordova https请求异常
  6. Android(安卓)NDK 知识系列(五)
  7. 『转』Android(安卓)Intent常见应用
  8. Activity的四种启动方式
  9. android:textAppearance设置文字外观
  10. Android清除本地数据缓存代码案例