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

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

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

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

看代码

 package com.qf.service01;

 import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Toast; public class MainActivity extends Activity { Intent serviceIntent;
MyReceiver myReceiver;
LocalBroadcastManager localBroadcastMgr;//本地广播管理器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); serviceIntent=new Intent(getApplicationContext(),MyService.class);
localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext());
myReceiver=new MyReceiver();
localBroadcastMgr.registerReceiver(myReceiver, new IntentFilter("com.qf.broadcast.disen_service"));
} class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "收到service的广播", Toast.LENGTH_SHORT).show(); }
} public void start(View v) {
startService(serviceIntent);
} public void stop(View v) {
stopService(serviceIntent);
}
public void startService(View v) {
localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext());
Intent intent1=new Intent("com.qf.broadcast.activity"); localBroadcastMgr.sendBroadcast(intent1);
} @Override
protected void onDestroy() {
super.onDestroy(); //取消注册本地广播接收器
localBroadcastMgr.unregisterReceiver(myReceiver);
}
}

MainActivity.java

 package com.qf.service01;

 import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast; public class MyService extends Service { LocalBroadcastManager localBroadcastMgr;//本地广播管理器
MyReceiver myReceiver;
public void onCreate() { //只执行一次,用于初始化Service
super.onCreate();
Log.i("debug", "onCreate"); myReceiver=new MyReceiver();
localBroadcastMgr=LocalBroadcastManager.getInstance(getApplicationContext());
localBroadcastMgr.registerReceiver(myReceiver, new IntentFilter("com.qf.broadcast.activity"));
}
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "收到activity的广播", Toast.LENGTH_SHORT).show(); }
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO 每次启动Service都会执行的方法,在此实现核心的功能
Log.i("debug", "onStartCommand"); Intent intent1=new Intent("com.qf.broadcast.disen_service");
localBroadcastMgr.sendBroadcast(intent1); return super.onStartCommand(intent, flags, startId);
} @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onDestroy() { //只执行一次,用于销毁Service组件
super.onDestroy();
Log.i("debug", "onDestroy");
localBroadcastMgr.unregisterReceiver(myReceiver);
} }

Service.java

 <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=".MainActivity" > <Button
android:id="@+id/btn1Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"
android:text="启动服务" /> <Button
android:id="@+id/btn2Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stop"
android:text="停止服务"
android:layout_below="@id/btn1Id"/>
<Button
android:id="@+id/btn3Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startService"
android:layout_below="@id/btn2Id"
android:text="向服务发广播" /> </RelativeLayout>

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qf.service01"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.qf.service01.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> <!-- 注册Service组件 -->
<service android:name="com.qf.service01.MyService"/>
</application> </manifest>

AndroidManifest.xml

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

  1. Service 之间如何通信?- 每天5分钟玩转 Docker 容器技术(101)

    微服务架构的应用由若干 service 组成.比如有运行 httpd 的 web 前端,有提供缓存的 memcached,有存放数据的 mysql,每一层都是 swarm 的一个 service,每个 ...

  2. 101、Service 之间如何通信?(Swarm08)

    参考https://www.cnblogs.com/CloudMan6/p/7967419.html   微服务架构的应用由若干 service 构成.比如有运行 httpd 的 web 前端,有提供 ...

  3. activity 与 service 之间的通信

    activity和service通信:通过binder 举个我实际项目中的例子:在service中下载更新应用 首先是下载更新apk的service: public class UpdateVersi ...

  4. Android中Activity、Service和线程之间的通信

    Activity.Service和线程应该是Android编程中最常见的几种类了,几乎大多数应用程序都会涉及到这几个类的编程,自然而然的,也就会涉及到三者之间的相互通信,本文就试图简单地介绍一下这三者 ...

  5. activity与service之间的通信方式

    Activity之间的通信 1.activity与activity的通信可以通过Intent来封装数据,startActivityForResult()来实现,当跳转的activity调用finish ...

  6. android中四大组件之间相互通信

    好久没有写有关android有关的博客了,今天主要来谈一谈android中四大组件.首先,接触android的人,都应该知道android中有四大组件,activity,service,broadca ...

  7. 10月9日Android学习笔记:活动与服务之间的通信

    最近在照着<第一行代码>这本书来学安卓,顺便记下笔记.主要的内容是Android中服务的第二种启动方式,通过活动绑定服务来启动服务,实现活动与服务之间的通信. 一. 首先创建一个服务类 p ...

  8. ionic2+Angular 依赖注入之Subject ——使用Subject来实现组件之间的通信

    在Angular+ionic2 开发过程中,我们不难发现,页面之间跳转之后返回时是不会刷新数据的. 场景一:当前页面需要登录之后才能获取数据--去登录,登录成功之后返回--页面需要手动刷新才能获取到数 ...

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

    IPC可以实现本地进程之间通信.这种用法不是太常见,常见的替代方案是使用wcf,remoting,web service,socket(tcp/pipe/...)等其他分布式部署方案来替代进程之间的通 ...

随机推荐

  1. 补充2:Golang 一些特性

    Go语言的这些地方都做的还不错: 拥有自动垃圾回收: 不用手动释放内存 一个包系统: Go 语言的源码复用建立在包(package)基础之上.包通过 package, import, GOPATH 操 ...

  2. 原生态的javascript的n种技巧(我从别人的博客中拷贝过来的,方便以后查阅)

    1.原生JavaScript实现字符串长度截取 function cutstr(str, len) { var temp; var icount = 0; var patrn = /[^\x00-\x ...

  3. 分割List为指定size

    背景 老项目,用的原生的JDBC,获取连接,预编译...然后业务需要要更新很多条数据,我就写了条件为 ——IN()... 根据传入的 list 的 size 循环的给sql语句拼接上“ ? ”为了之后 ...

  4. ajaxGet 获取封装

    callback 表示下一个功能(回调函数) function ajaxGet(url,callback,data){           如果路径上有参数  就在url后面拼接参数 否则只请求url ...

  5. redis 4,0 安装

    安装redis : 1,yum install wget -y 2,cd /opt: 3,wget http://download.redis.io/releases/redis-4.0.10.tar ...

  6. JavaScript词法分析(尽力理解)

    JavaScript中在调用函数的那一瞬间之前,会先进行词法分析 词法分析的过程: 当函数调用的前一瞬间,会先形成一个激活对象:Avtive Object(AO),并会分析以下3个方面: 1:函数参数 ...

  7. 2018-2019-2 《网络对抗技术》Exp2 后门原理与实践 Week4 20165233

    Exp2 后门原理与实践 实验内容 一.基础问题回答 1.例举你能想到的一个后门进入到你系统中的可能方式? 答:通过访问钓鱼网站,无意下载了一些图片或是文件.而这个图片或文件中携带后门. 2.例举你知 ...

  8. leetcode107

    /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNo ...

  9. Application HookMainWindow

    //H Filebool __fastcall AppHookFunc(TMessage &Message); //cpp file void __fastcall TForm2::FormC ...

  10. 使用JsonViewer来格式化json字符串

    1. 在线转换 https://www.bejson.com/jsonviewernew/ ==>格式化 2. 使用notepad ++ 的jsonViewer插件 下载地址 http://ww ...