Aactivity和Service之间的通信

一、在activity中定义三个按钮 一个开启服务  一个关闭服务,还有一个是向服务发送广播

当创建出Serevice时先执行Service的onCreate()创建服务后只执行一次 以后每次点击开启服务都不会再执行onCreate()而是去执行onStartCommand()停止服务时执行Service的onDestroy()

二、在Activity中点击发送广播键会向服务发送广播(本例采用LocalBroadcastManager发送和接受广播)服务接收广播吐司出“接收到activity的广播”。服务是在oncreate()里边创建接受者不在onStartcommand()里边创建是因为每次点击开启服务时都会执行onStartcommand()    activity创建出service时在service中的oncreate()里向activity发送广播   activity在oncreate()里创建出接受者。

三、其实就是双方都有一个发送者和接收者

看代码

 1 package com.qf.service01;
 2
 3 import android.app.Activity;
 4 import android.content.BroadcastReceiver;
 5 import android.content.Context;
 6 import android.content.Intent;
 7 import android.content.IntentFilter;
 8 import android.os.Bundle;
 9 import android.support.v4.content.LocalBroadcastManager;
10 import android.view.View;
11 import android.widget.Toast;
12
13 public class MainActivity extends Activity {
14
15     Intent serviceIntent;
16     MyReceiver myReceiver;
17     LocalBroadcastManager localBroadcastMgr;//本地广播管理器
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_main);
22
23         serviceIntent=new Intent(getApplicationContext(),MyService.class);
24         localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext());
25         myReceiver=new MyReceiver();
26         localBroadcastMgr.registerReceiver(myReceiver, new IntentFilter("com.qf.broadcast.disen_service"));
27     }
28
29
30     class MyReceiver extends BroadcastReceiver{
31         @Override
32         public void onReceive(Context context, Intent intent) {
33             Toast.makeText(MainActivity.this, "收到service的广播", Toast.LENGTH_SHORT).show();
34
35         }
36     }
37
38     public void start(View v) {
39         startService(serviceIntent);
40     }
41
42     public void stop(View v) {
43         stopService(serviceIntent);
44     }
45     public void startService(View v) {
46         localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext());
47         Intent intent1=new Intent("com.qf.broadcast.activity");
48
49         localBroadcastMgr.sendBroadcast(intent1);
50     }
51
52
53     @Override
54     protected void onDestroy() {
55         super.onDestroy();
56
57         //取消注册本地广播接收器
58         localBroadcastMgr.unregisterReceiver(myReceiver);
59     }
60 }

MainActivity.java

 1 package com.qf.service01;
 2
 3 import android.app.Service;
 4 import android.content.BroadcastReceiver;
 5 import android.content.Context;
 6 import android.content.Intent;
 7 import android.content.IntentFilter;
 8 import android.os.IBinder;
 9 import android.support.v4.content.LocalBroadcastManager;
10 import android.util.Log;
11 import android.widget.Toast;
12
13 public class MyService extends Service {
14
15     LocalBroadcastManager localBroadcastMgr;//本地广播管理器
16     MyReceiver myReceiver;
17     public void onCreate() { //只执行一次,用于初始化Service
18         super.onCreate();
19         Log.i("debug", "onCreate");
20
21         myReceiver=new MyReceiver();
22         localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext());
23         localBroadcastMgr.registerReceiver(myReceiver, new IntentFilter("com.qf.broadcast.activity"));
24     }
25     class MyReceiver extends BroadcastReceiver{
26         @Override
27         public void onReceive(Context context, Intent intent) {
28             Toast.makeText(context, "收到activity的广播", Toast.LENGTH_SHORT).show();
29
30         }
31     }
32
33     @Override
34     public int onStartCommand(Intent intent, int flags, int startId) {
35         // TODO 每次启动Service都会执行的方法,在此实现核心的功能
36         Log.i("debug", "onStartCommand");
37
38          Intent intent1=new Intent("com.qf.broadcast.disen_service");
39         localBroadcastMgr.sendBroadcast(intent1);
40
41         return super.onStartCommand(intent, flags, startId);
42     }
43
44
45
46     @Override
47     public IBinder onBind(Intent intent) {
48         return null;
49     }
50
51     @Override
52     public void onDestroy() { //只执行一次,用于销毁Service组件
53         super.onDestroy();
54         Log.i("debug", "onDestroy");
55         localBroadcastMgr.unregisterReceiver(myReceiver);
56     }
57
58 }

Service.java

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity" >
10
11     <Button
12         android:id="@+id/btn1Id"
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:onClick="start"
16         android:text="启动服务" />
17
18     <Button
19         android:id="@+id/btn2Id"
20         android:layout_width="wrap_content"
21         android:layout_height="wrap_content"
22         android:onClick="stop"
23         android:text="停止服务"
24         android:layout_below="@id/btn1Id"/>
25     <Button
26         android:id="@+id/btn3Id"
27         android:layout_width="wrap_content"
28         android:layout_height="wrap_content"
29         android:onClick="startService"
30         android:layout_below="@id/btn2Id"
31         android:text="向服务发广播" />
32
33 </RelativeLayout>

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.qf.service01"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="17" />
10
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name="com.qf.service01.MainActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25
26         <!-- 注册Service组件 -->
27        <service android:name="com.qf.service01.MyService"/>
28     </application>
29
30 </manifest>

AndroidManifest.xml

时间: 2024-08-06 03:42:12

Aactivity和Service之间的通信的相关文章

activity 与 service 之间的通信

activity和service通信:通过binder 举个我实际项目中的例子:在service中下载更新应用 首先是下载更新apk的service: public class UpdateVersionService extends Service { private final String tag = "young"; private Context context = this; private BaseApplication application; private Down

使用Messenger进行Activity与Service之间的相互通信

在Android开发中,有时候我们需要让一个Activity绑定一个Service,进行两者之间的通信.当Activity绑定成功以后,就可以调用Service中的public(或有对应可见级别)的方法.如果Service想把一些信息反馈给Activity,则需要将Activity的Listener传递给Service,由Service负责调用. 这样的做法是可以实现功能的,但有一些缺憾. 首先,Service需要把被调用的方法做成public的,不利于隐藏实现. 第二,调用显得凌乱,在Acti

赵雅智:service与访问者之间进行通信,数据交换

服务类 中间人:service服务中的bind对象 创建中间人并通过onBinder方法的return暴露出去 在服务类创建一个服务 创建中间人继承Binder MainActivity类 声明服务的中间人 private ServiceTese.MyBinder myBinder; 链接成功的时候赋值service 设置按钮点击事件 输出结果: 赵雅智:service与访问者之间进行通信,数据交换

多个 ng-app 中 Controllers &amp; Services 之间的通信

原文发布在个人独立博客上,链接:http://pengisgood.github.io/2016/01/31/communication-between-multiple-angular-apps/ 通常情况下,在 Angular 的单页面应用中不同的 Controller 或者 Service 之间通信是一件非常容易的事情,因为 Angular 已经给我们提供了一些便利的方法:$on,$emit,$broadcast. 在这里用一个简单的例子来演示一下这三个方法的用途,完整版代码也可以参考这里

AngularJS 中 Controller 之间的通信

用 Angular 进行开发,基本上都会遇到 Controller 之间通信的问题,本文对此进行一个总结. 在 Angular 中,Controller 之间通信的方式主要有三种: 1)作用域继承.利用子 Controller 控制父 Controller 上的数据.(父 Controller 中的数据要为引用类型,不能是基本类型,原因参见 AngularJS中的作用域 一文) 2)注入服务.把需要共享的数据注册为一个 service,在需要的 Controller 中注入. 3)基于事件.利用

c# IPC实现本机进程之间的通信

IPC可以实现本地进程之间通信.这种用法不是太常见,常见的替代方案是使用wcf,remoting,web service,socket(tcp/pipe/...)等其他分布式部署方案来替代进程之间的通信.虽然不常见但也避免不了一些场景会使用该方案. 应用包含: 1)使用IPC技术实现多client与一个sever通信(不过是本机,感觉意义不大,但如果想实现本机上运行确实是一个不错的方案): 2)使用IPC技术实现订阅者和生产者分离时,一个server接收并消费消息,客户端是生产消息的. 1 1:

WCF、WebAPI、WCF REST、Web Service之间的区别

在.net平台下,有大量的技术让你创建一个HTTP服务,像Web Service,WCF,现在又出了Web API.在.net平台下,你有很多的选择来构建一个HTTP Services.我分享一下我对Web Service.WCF以及Web API的看法. Web Service 1.它是基于SOAP协议的,数据格式是XML 2.只支持HTTP协议 3.它不是开源的,但可以被任意一个了解XML的人使用 4.它只能部署在IIS上 WCF 1.这个也是基于SOAP的,数据格式是XML 2.这个是We

Android应用程序组件之间的通信Intent和IntentFilter

Android应用程序的基本组件,这些基本组建除了Content Provider之外,几乎全部都是依靠Intent对象来激活和通信的. 下面介绍Intent类,并通过例子来说明Intent一般用法 1.1 Intent类简介 Intent类的对象是组件间通信的载体,组件之间进行通信就是一个个Intent对象在不断地传递.Intent对象主要作用于运行在相同或不同应用程序的Activity,Service和Broadcast Receiver组件之间,对于这3种组件,其作用机制也不相同 一,对于

McAfee Vulnerability Manager(Foundstone)各组件之间的通信关系

Components andwhat they do McAfeeVulnerability Manager consists of components that work together to monitor yoursystems. Enterprise manager – Uses Microsoft Internet Information Services (IIS) to provideauthorized users with access to McAfee Vulnerab