本文将通过实现一个简单的Service发送简单消息,然后通过一个BroadcastReceiver接收Service发送的消息,从而改变一个TextView的文本颜色。

这里,我们需要三个java文件,一个实现MainActivity,一个实现Service,一个实现BroadcastReceiver。

首先是MyService.java,为了让BroadcastReceiver,接收到消息,我们需要调用sendBroadcast(Intent) 方法,这里的intent便是我们需要发送的消息内容。发送消息的时候改变TextView的颜色一次。

    intent = new Intent("Change_Color");
sendBroadcast(intent);

为了实现1s改变一次TextView的颜色,我们需要将Service运行在一个线程之中,这时我们来新建一个线程,并让此线程每隔1s休眠一次。需要注意的是,在最后一定不能忘记调用Thread.start()。

        new Thread(){
@Override
public void run(){
while(true){
intent = new Intent("Change_Color"); // 待广播的intent
sendBroadcast(intent); // 广播intent
try{
Thread.sleep(1000); // 休眠1秒
} catch (Exception e){
e.printStackTrace();
}
}
} }.start(); // 开启线程

另外,继承Service的话,需要重载onBind方法,IBinder是远程对象的基本接口,是为高性能而设计的轻量级远程调用机制的核心部分。但它不仅用于远程调用,也用于进程内调用。这个接口定义了与远程对象交互的协议。Android的远程调用(就是跨进程调用)就是通过IBinder实现的。

完整代码如下:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service{ private Intent intent; @Override
public IBinder onBind(Intent i){
return null;
} @Override
public void onCreate(){
super.onCreate(); new Thread(){
@Override
public void run(){
while(true){
intent = new Intent("Change_Color");
sendBroadcast(intent);
try{
Thread.sleep(1000);
} catch (Exception e){
e.printStackTrace();
}
}
} }.start();
} @Override
public void onDestroy(){
super.onDestroy(); this.stopService(intent);
}
}

然后是MyBroadcastReceiver.java,继承BroadcastReceiver,然后重载onReceiver。在得到的intent判断intent.getAction()是否和发送的消息相同即可。

        if(intent.getAction().equals("Change_Color")){          // 接受的intent是上述发送的intent
if(!colorIndex) {
MainActivity.textView.setTextColor(Color.BLUE); // 改变TextView的颜色
colorIndex = true;
} else {
MainActivity.textView.setTextColor(Color.RED);
colorIndex = false;
}

colorIndex需要定义为static,为了使下一次实例化MyBroadcastReceiver的时候可以记住当前的TextView颜色。完整代码如下:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color; public class MyBroadcastReceiver extends BroadcastReceiver{ static boolean colorIndex = false; @Override
public void onReceive(Context context, Intent intent){ if(intent.getAction().equals("Change_Color")){
if(!colorIndex) {
MainActivity.textView.setTextColor(Color.BLUE);
colorIndex = true;
} else {
MainActivity.textView.setTextColor(Color.RED);
colorIndex = false;
} }
}
}

最后是MainActivity.java,这个比较简单,在onCreate()内startService(),在onDestroy()内stopService()即可。注意一定要stopService(),否则这个Service将一直占用CPU时间。

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity { private Button button;
static TextView textView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.textView);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { startService(new Intent(MainActivity.this, MyService.class)); // 启动服务
textView.setText("这是一个可以变颜色的文字");
}
});
} @Override
public void onDestroy(){
super.onDestroy(); stopService(new Intent(MainActivity.this, MyService.class)); // 关闭服务
}
}

仅仅这样做,我们发现仍然没法让程序按照我们希望的样子运行。这是因为我们没有在AndroidManifest.xml内注册我们定义的Service和BroadcastReceiver。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.doodle.example" > <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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 android:name=".MyService"/>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="Change_Color"/>
</intent-filter>
</receiver> </application> </manifest>

Android开发手记(25) 简单Service的实现的更多相关文章

  1. Android开发四大组件之Service(具体解释篇)

    Android开发之四大组件--Service 一.Service 简单介绍 Service是android系统中的四大组件之中的一个(Activity.Service.BroadcastReceiv ...

  2. Android开发之如何保证Service不被杀掉(broadcast+system/app

    Android开发之如何保证Service不被杀掉(broadcast+system/app) 序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作 ...

  3. Android 开发手记一NDK编程实例

    在Android上,应用程序的开发,大部分基于Java语言来实现.要使用c或是c++的程序或库,就需要使用NDK来实现.NDK是Native Development Kit的简称.它是一个工具集,集成 ...

  4. Android开发——Fragment的简单使用总结

    前言: 之前搞项目的时候,就使用了这个Fragment,中间遇到了许多坑,把坑都解决了,现在写一篇较为简单的Fragment使用总结 Fragment的简单介绍: 简单来说,Fragment其实可以理 ...

  5. Android开发之使用Web Service进行网络编程

    使用Web Service进行网络编程 Android应用通常都是执行在手机平台上.手机系统的硬件资源是有限的,无论是存储能力还是计算能力都有限.在Android系统上开发.执行一些单用户.小型应用是 ...

  6. Android开发学习之路--Service之初体验

    android最后一个组件便是service了,终于学习到最后一个组件了,从年前的开发环境的搭建,到现在学到最后一个组件花了三周的时间,期间记录的点点滴滴,照着书本学习编写的代码都受益匪浅,这里要感谢 ...

  7. 【转】Android开发之如何保证Service不被杀掉(broadcast+system/app)

    Service简介 1.Service 每个Service必须在manifest中 通过<service>来声明. 可以通过contect.startservice和contect.bin ...

  8. Android 开发之如何保证Service不被杀掉(broadcast+system/app)

    序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作,都要保证service不被kill,这可真是一个难题.参考了现今各种定制版的系统和安全厂商牛虻 ...

  9. Android开发手记(28) Handler和Looper

    Android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道.平 ...

随机推荐

  1. AWK 简明教程

    AWK 简明教程 转自:http://coolshell.cn/articles/9070.html 有一些网友看了前两天的<Linux下应该知道的技巧>希望我能教教他们用awk和sed, ...

  2. 【POJ2773】Happy 2006 欧几里德

    题目描述: 分析: 根据欧几里德,我们有gcd(b×t+a,b)=gcd(a,b) 则如果a与b互质,则b×t+a与b也一定互质,如果a与b不互质,则b×t+a与b也一定不互质. 所以与m互质的数对m ...

  3. [性能分析]linux文件描述符(转)

    1.什么是文件和文件描述符 Linux中文件可以分为4种:普通文件.目录文件.链接文件和设备文件.1.普通文件是用户日常使用最多的文件,包括文本文件.shell脚本.二进制的可执行和各种类型的数据.l ...

  4. 纯css切换左侧菜单

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  5. STM32F072B-DISCO 深入研究 中断系统

    STM32F072B-DISCO 是我认为性价比最高的一款CPU的demo系统,以前一直在用PIC的CPU但最近几年ST异军突起,几次课题查找芯片无一例外都是ST,像USB,CAN,ZIGBEE等,S ...

  6. MRTG开源监控安装手册

    环境要求: CentOS6以上版本 2G内存 16G存储 源码包下载:第一部分:下载,第二部分:下载 1.安装snmp: yum install -y net-snmp net-snmp-devel ...

  7. poj 2288 tsp经典问题

    题目链接:http://poj.org/problem?id=2288 #include<cstdio> #include<cstring> #include<iostr ...

  8. Navicat for MySQL之MySQL客户端的下载、安装和使用

    前期工作 若需使用Navicat for MySQL,则需要先安装MySQL,在此就不叙述了.具体可见我的博客: mysql-5.7.11-winx64.zip 的下载.安装.配置和使用(window ...

  9. java 检查是否是数组 检查是否是空数组 检查数组是否包含某个元素

    /** * Determine whether the given object is an array: * either an Object array or a primitive array. ...

  10. UILabel,文字添加下划线,中划线

    //显示下划线 //中划线 //        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber nu ...