完成service服务需要如下几步:

<1> : 重写Serivce子类,即写一个继承Service类(extends Service);



public class MyService extends Service{
...
}


 

<2> : 在AndroidMainfest.xml文件中添加service,基本上和Activity差不多:



<service 
android:name=".MyService">
<intent-filter>
<action android:name="com.example.androidservicedemo0.MY_SERVICE"/>
</intent-filter>
</service>


<3> : 如果是不介意activity结束后,service仍然继续运行,只需要使用:



....

final Intent intent=new Intent();
intent.setAction("com.example.androidservicedemo0.BIND_SERVICE");

....
startService(intent);


停止服务:



stopService(intent);


 

如果希望activity结束后,service也随之结束,需要绑定服务.

activity或者service之间要通信,传递参数,可以使用Binder接口,自己实现这个接口.

实现上面demo如下:

主类:



package com.example.androidservicedemo0;

import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import .Activity;
import .Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

private Button mStartButton,mStopButton;
private Button mBindButton,mUnBindButton;
private Button mSerivceStatusButton;

BindService.MBinder binder;

private final String TAG="MainActivity";

private ServiceConnection conn=new ServiceConnection(){

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
Log.i(TAG,"service connection .");
binder=(BindService.MBinder)service;
}

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.i(TAG,"service disconnection .");
}

};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Intent intent=new Intent();
intent.setAction("com.example.androidservicedemo0.BIND_SERVICE");

mStartButton=(Button)findViewById(.button1);
mStartButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(intent);
}

});

mStopButton=(Button)findViewById(.button2);
mStopButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(intent);
}

});

mBindButton=(Button)findViewById(.button3);
mBindButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
bindService(intent,conn,Service.BIND_AUTO_CREATE);
}

});
mUnBindButton=(Button)findViewById(.button4);
mUnBindButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(conn);
}

});
mSerivceStatusButton=(Button)findViewById(.button5);
mSerivceStatusButton.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "counter : "+binder.getCounter(), Toast.LENGTH_SHORT).show();
}

});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


服务类:



package com.example.androidservicedemo0;

import .Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BindService extends Service{

private final String TAG="BindService";

private MBinder mBinder=new MBinder();
private int mCounter;
private boolean quit;

public class MBinder extends Binder{
public int getCounter(){

return mCounter;

}
}

@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG,"unbind service .");
return super.onUnbind(intent);
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i(TAG,"bind service .");
return mBinder;
}

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i(TAG,"service create .");
new Thread(){
public void run(){
while(!quit){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCounter++;
}

}
}.start();

}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG,"stop service .");
this.quit=true;
}

@Override
@Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.i(TAG,"service start .");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i(TAG,"service start command .");
mCounter=0;
return super.onStartCommand(intent, flags, startId);
}


}


AndroidMainfest.xml文件配置如下:



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http:///apk/res/android"
package="com.example.androidservicedemo0"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<service
android:name=".BindService">
<intent-filter>
<action android:name="com.example.androidservicedemo0.BIND_SERVICE"/>
</intent-filter>
</service>

<activity
android:name="com.example.androidservicedemo0.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


布局文件:



<RelativeLayout xmlns:android="http:///apk/res/android"
xmlns:tools="http:///tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="39dp"
android:layout_marginTop="22dp"
android:text="start service" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="stop service" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_below="@+id/button2"
android:text="bind service" />

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button3"
android:layout_below="@+id/button3"
android:layout_marginTop="96dp"
android:text="unbind service" />

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button3"
android:layout_alignRight="@+id/button1"
android:layout_centerVertical="true"
android:text="service status" />

</RelativeLayout>


android service基本知识(demo版)_ide