Android绑定方式开始服务&调用服务当中的方法

来源:互联网 发布:二叉树叶子节点数算法 编辑:程序博客网 时间:2024/05/21 15:07

绑定方式开启服务,调用服务当中的方法

1、调用过程图解

2、案例代码

package com.example.bindCreateService;import com.example.bindCreateService.ChunGeService.Mybinder;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;public class MainActivity extends Activity {private ChunGeService.Mybinder myybinder;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void start(View view){Intent intent  = new Intent(this, ChunGeService.class);startService(intent);}public void stop(View view){Intent intent  = new Intent(this, ChunGeService.class);stopService(intent);}public void bind(View view){Intent intent  = new Intent(this, ChunGeService.class);//intent激活意图,设置绑定服务的对象//conn 设置代理,用来个服务建立联系,不能为空//在绑定服务的时候,如果服务不存在,将自动创建。bindService(intent, new myConn(), BIND_AUTO_CREATE);}private class myConn implements ServiceConnection{@Override//服务被绑定成功后调用的方法public void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubSystem.out.println("春哥把代理人返回回来了....");System.out.println(service.toString()); myybinder = (Mybinder) service;}@Override//服务被断开后调用的方法public void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}}public void change(View view){myybinder.CallChangeSing("月亮之上");}}
package com.example.bindCreateService;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.widget.Toast;public class ChunGeService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubSystem.out.println("春哥服务被成功的绑定了。。。");Mybinder mybinder = new Mybinder();System.out.println(mybinder.toString());return mybinder; //返回一个自定义的代理}public class Mybinder extends Binder{public void CallChangeSing(String singName){changeSing(singName);}}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();System.out.println("服务开始了,春哥开始唱歌了.....");}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();System.out.println("服务销毁了,春哥停止唱歌了.....");}/** * 更改唱的歌曲 * @param singName */public void changeSing(String singName){Toast.makeText(getApplicationContext(), "开始唱"+singName+"...", 0).show();}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubreturn super.onUnbind(intent);}}

3、绑定服务:绑定服务开启服务,可以调用服务里面的方法。解除绑定服务后、或应用程序关闭,服务也将会停止

      开启服务:不能够调用服务当中的方法,应用程序关闭,服务仍然会在后台运行。

--需求:需要能够调用服务中的方法,并能够长期在后台运行。

解决办法:先开启服务,然后使用绑定服务。这样当应用程序退出后,虽然绑定会解除,但是服务仍然会在后台运行。

 

0 0