初学Android,绑定本地Service并与之通信(五十九)

news/2024/7/4 0:54:37 标签: service, android, button, class, thread, action
class="baidu_pl">
class="article_content clearfix">
class="htmledit_views">

如果Service和访问者之间需要进行方法调用或数据交换,则需要使用bindService()和unbindService()方法启动,关闭服务


BindService和Started Service都是Service,有什么地方不一样呢:
1. Started Service中使用StartService()方法来进行方法的调用,调用者和服务之间没有联系,即使调用者退出了,服务依然在进行【onCreate()-  >onStartCommand()->startService()->onDestroy()】,注意其中没有onStart(),主要是被onStartCommand()方法给取代了,onStart方法不推荐使用了。

2. BindService中使用bindService()方法来绑定服务,调用者和绑定者绑在一起,调用者一旦退出服务也就终止了【onCreate()->onBind()->onUnbind()->onDestroy()】。

定义服务类

class="language-java">package WangLi.Service.BindService;

import class="tags" href="/tags/ANDROID.html" title=android>android.app.Service;
import class="tags" href="/tags/ANDROID.html" title=android>android.content.Intent;
import class="tags" href="/tags/ANDROID.html" title=android>android.os.Binder;
import class="tags" href="/tags/ANDROID.html" title=android>android.os.IBinder;

public class BindService extends Service {
	private int count;
	private boolean quit;
	// 定义onBinder方法所返回的对象
    private MyBinder binder = new MyBinder();
	// 通过继承Binder来实现IBinder类
	public class MyBinder extends Binder {
		public int getCount()
		{
			//获取Service的运行状态:count
			return count;
		}
	}
    //必须实现的方法
	@Override
	public IBinder onBind(Intent arg0) {
		System.out.println("Service is Binded");
		//返回IBinder对象
		return binder;
	}

	//Service被创建时回调该方法
	@Override
	public void onCreate()
	{
		super.onCreate();
		System.out.println("Service is Created");
		//启动一条线程,动态地修改count状态值
		new Thread()
		{
			@Override
			public void run()
			{
				while(!quit)
				{
					try
					{
						Thread.sleep(1000);
					}
					catch(InterruptedException e)
					{
						
					}
					count++;
				}
			}
		}.start();
	}
	//Service断开连接时回调该方法
	@Override
	public boolean onUnbind(Intent intent)
	{
		System.out.println("Service is Unbinded");
		return true;
	}
	//Serice被关闭之前回调
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		this.quit = true;
		System.out.println("Service is Destroyed");
	}
}
绑定,解除服务

class="language-java">package WangLi.Service.BindService;

import class="tags" href="/tags/ANDROID.html" title=android>android.app.Activity;
import class="tags" href="/tags/ANDROID.html" title=android>android.app.Service;
import class="tags" href="/tags/ANDROID.html" title=android>android.content.ComponentName;
import class="tags" href="/tags/ANDROID.html" title=android>android.content.Intent;
import class="tags" href="/tags/ANDROID.html" title=android>android.content.ServiceConnection;
import class="tags" href="/tags/ANDROID.html" title=android>android.os.Bundle;
import class="tags" href="/tags/ANDROID.html" title=android>android.os.IBinder;
import class="tags" href="/tags/ANDROID.html" title=android>android.view.View;
import class="tags" href="/tags/ANDROID.html" title=android>android.view.View.OnClickListener;
import class="tags" href="/tags/ANDROID.html" title=android>android.widget.Button;
import class="tags" href="/tags/ANDROID.html" title=android>android.widget.Toast;

public class MainActivity extends Activity {
	Button bind, unbind, getServiceStatus;
	// 保持所启动的Service的IBinder对象
	BindService.MyBinder binder;
	// 定义一个ServiceConnection对象
	private ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder class="tags" href="/tags/SERVICE.html" title=service>service) {
			System.out.println("--Service Connected--");
			// 获取Service的onBind方法所返回的MyBinder对象
			binder = (BindService.MyBinder) class="tags" href="/tags/SERVICE.html" title=service>service;
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			System.out.println("--Service Disconnected--");
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取程序界面中的start,stop,getServiceStatus按钮
		bind = (Button) findViewById(R.id.bind);
		unbind = (Button) findViewById(R.id.unbind);
		getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
		// 创建启动Service的Intent
		final Intent intent = new Intent();
		// 为Intent设置Action属性
		intent.setAction("WangLi.Service.Bind_Service");
		bind.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// 绑定指定的Service
				bindService(intent, conn, Service.BIND_AUTO_CREATE);
			}
		});
		unbind.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 解除绑定Service
				unbindService(conn);
			}
		});
		getServiceStatus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 获取并显示Service的count值
				Toast.makeText(MainActivity.this,
						"Service的count值为:" + binder.getCount(), 4000).show();
			}
		});
	}
}

打印效果






http://www.niftyadmin.cn/n/1411299.html

相关文章

Spring Boot 之 RestTemplate 网络请求实践

引入依赖<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></p…

bind方法的实现

bind方法的作用&#xff1a;就是进行this绑定。他的返回值是一个函数&#xff0c;返回的函数中的this就是bind的参数对象。 可以这样的进行简单的实现&#xff1a; function bind(fn, context){return function(){return fn.apply(context,arguments);} } 在原生JavaScript中…

初学Android,跨进程调用Service(六十)

Android系统中&#xff0c;各应用程序都运行在自己的进程中&#xff0c;进程之间一般无法进行数据交换。 Android调用Service先定义一个远程调用接口&#xff0c;然后为该接口提供一个实现类。Android访问Service时&#xff0c;不是直接返回Service对象给客户端——Service只是…

什么是原型

prototype 函数有原型&#xff0c;函数有一个属性叫prototype&#xff0c;函数的这个原型指向一个对象&#xff0c;这个对象叫原型对象。这个原型对象有一个constructor属性&#xff0c;指向这个函数本身。 一个实例化对象&#xff0c;没有prototype属性。 function fn(){co…

第十六周进度表

所花时间 9h 代码量 500行 博客量 2篇 了解到的知识点 软件开发团队注意事项 转载于:https://www.cnblogs.com/ming123/p/7011589.html

mallocstacklogging和MallocStackLoggingNoCompact引起的app文稿数据快速增加

最近由于定位一个iOS16系统适配引起的闪退设置了mallocstacklogging和MallocStackLoggingNoCompact。 配置如下&#xff1a; 在上线前测试&#xff0c;结果发现手机存储空间不足。删除了手机的很多图片后&#xff0c;测试不到两分钟&#xff0c;手机存储空间又不足了。查看app…

初学Android,传递复杂数据的Service(六十一)

本篇来学学怎么传递自定义数据类型&#xff0c;例中定义了两个类&#xff0c;Person和Pet&#xff0c;其中Person对象作为调用远程Service的参数&#xff0c;而Pet作为返回值&#xff0e; 不管是远程调用的参数&#xff0c;还是返回值都要求实现Parcelable接口&#xff0e; 实现…

UNIX 终结

2019独角兽企业重金招聘Python工程师标准>>> System V Application Binary Interface - X86-64.org Oh snap! It seems like the remote file you are searching for is unavailable. Dont worry! There are some similar files below. Alert me when the remote fi…