核心代码

Activity

public class MusicActivity extends Activity implements OnClickListener{@Overridepublic void onClick(View v) {connection(); }private void connection() {Intent intent = new Intent("david.bindService");bindService(intent, sc, Context.BIND_AUTO_CREATE);}//在客户端覆写onServiceConnected方法,当服务绑定成功会调用此回调函数private ServiceConnection sc = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {MyBinder binder = (MyBinder)service; //通过IBinder获取ServicemusicService = binder.getService();if(musicService != null){ musicService.play(); }}};}}

Service

public class MusicService extends Service {//需用内部类继承Binder,并定义方法获取Service对象private final IBinder binder = new MyBinder();public class MyBinder extends Binder {BindMusicService getService() {return BindMusicService.this;}}@Overridepublic IBinder onBind(Intent intent) {//当客户端调用bindService()方法时调用此函数return binder;}@Overridepublic void onCreate() { }@Overridepublic void onDestroy() { }}


应用范例

Activity文件

package com.app.myservice;import com.app.myservice.service.MyService;import com.app.myservice.service.MyService.MyBind;import android.os.Bundle;import android.os.IBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class ServiceDemo03_Bind extends Activity implements OnClickListener{private Button startservice,stopservice,binderservice,unbinderservice,getService;private boolean mIsBound;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_first);startservice = (Button) findViewById(R.id.button1);stopservice = (Button) findViewById(R.id.button2);binderservice = (Button) findViewById(R.id.button3);unbinderservice = (Button) findViewById(R.id.button4);getService = (Button) findViewById(R.id.button5);startservice.setOnClickListener(this);stopservice.setOnClickListener(this);binderservice.setOnClickListener(this);unbinderservice.setOnClickListener(this);getService.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent(ServiceDemo03_Bind.this,MyService.class);switch (v.getId()) {case R.id.button1:startService(intent);break;case R.id.button2:stopService(intent);break;case R.id.button3://绑定Service//BIND_AUTO_CREATE表示自动创建bindService(intent, connection, BIND_AUTO_CREATE);mIsBound = true;break;case R.id.button4://解除绑定Serviceif (mIsBound == true) {unbindService(connection);}mIsBound = false;break;case R.id.button5://提示框Toast.makeText(ServiceDemo03_Bind.this, "当前Service的值为"+mService.getIndex(), 1000).show();break;default:break;}} private MyService mService = new MyService();ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubToast.makeText(ServiceDemo03_Bind.this, "这里是:onServiceDisconnected", 1000).show();}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubToast.makeText(ServiceDemo03_Bind.this, "这里是:onServiceConnected", 1000).show();System.out.println("onServiceConnected");MyService.MyBind myBind = (MyBind) service;mService = myBind.getMyService();}};}

Service文件

package com.app.myservice.service;import java.util.Timer;import java.util.TimerTask;import android.R.integer;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.widget.Toast;public class MyService extends Service{private Timer timer;private TimerTask task;private int index=0;Context context;@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn mBind;}private MyBind mBind = new MyBind();public class MyBind extends Binder {public MyService getMyService() {return MyService.this;}}                                                @Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();context = getApplicationContext();Toast.makeText(context, "这里是:onCreate", 1000).show();System.out.println("onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubSystem.out.println("onStartCommand");Toast.makeText(context, "这里是:onStartCommand", 1000).show();startTimer();return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubSystem.out.println("onDestroy");Toast.makeText(context, "这里是:onDestroy", 1000).show();super.onDestroy();stopTimer();}public void startTimer() {timer = new Timer();task = new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubindex++;System.out.println(index);}};// 安排指定的任务从指定的延迟后开始进行重复的固定延迟执行timer.schedule(task, 1000, 1000);}public void stopTimer() {timer.cancel();//取消此计时器任务}public int getIndex() {return index;}}

XML布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/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=".FirstActivity"    android:background="#fff" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginLeft="38dp"        android:layout_marginTop="14dp"        android:text="开始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="停止cervice" />    <Button        android:id="@+id/button3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button2"        android:layout_below="@+id/button2"        android:text="绑定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:text="解除绑定service" />    <Button        android:id="@+id/button5"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button4"        android:layout_below="@+id/button4"        android:text="获取service" /></RelativeLayout>


更多相关文章

  1. Android中RadioGroup RadioButton CheckBox多选按钮实现方法以及
  2. android 文件目录权限
  3. Android文件操作IO技术
  4. Android将Uri转化为文件路径的方法
  5. android HTTP post方法时,如何使用cookies
  6. 解决TabLayout+viewpager 滑动切换时 布局文件不是从头显示
  7. Android NDK之----- C调用Java [GetMethodID方法的使用]
  8. 一些常用SD卡操作的方法,APk管理之类的方法
  9. android之sax解析xml文件

随机推荐

  1. Androidの联系人群组Group操作示例
  2. Android Studio使用小结
  3. android 笔记 --- 电源应用
  4. Android Service启动(二) bindService()启
  5. Android之设置页面(PreferenceActivity使
  6. SmartFoxServer: massive multiplayer ga
  7. androidStudio没有httpclient的解决办法
  8. android 常用的数据库表以及操作说明
  9. 《Android开发从零开始》——2.模拟器的
  10. 安卓5.1屏蔽recent_apps