Android开发手记(25) 简单Service的实现
本文将通过实现一个简单的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的实现的更多相关文章
- Android开发四大组件之Service(具体解释篇)
		
Android开发之四大组件--Service 一.Service 简单介绍 Service是android系统中的四大组件之中的一个(Activity.Service.BroadcastReceiv ...
 - Android开发之如何保证Service不被杀掉(broadcast+system/app
		
Android开发之如何保证Service不被杀掉(broadcast+system/app) 序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作 ...
 - Android 开发手记一NDK编程实例
		
在Android上,应用程序的开发,大部分基于Java语言来实现.要使用c或是c++的程序或库,就需要使用NDK来实现.NDK是Native Development Kit的简称.它是一个工具集,集成 ...
 - Android开发——Fragment的简单使用总结
		
前言: 之前搞项目的时候,就使用了这个Fragment,中间遇到了许多坑,把坑都解决了,现在写一篇较为简单的Fragment使用总结 Fragment的简单介绍: 简单来说,Fragment其实可以理 ...
 - Android开发之使用Web Service进行网络编程
		
使用Web Service进行网络编程 Android应用通常都是执行在手机平台上.手机系统的硬件资源是有限的,无论是存储能力还是计算能力都有限.在Android系统上开发.执行一些单用户.小型应用是 ...
 - Android开发学习之路--Service之初体验
		
android最后一个组件便是service了,终于学习到最后一个组件了,从年前的开发环境的搭建,到现在学到最后一个组件花了三周的时间,期间记录的点点滴滴,照着书本学习编写的代码都受益匪浅,这里要感谢 ...
 - 【转】Android开发之如何保证Service不被杀掉(broadcast+system/app)
		
Service简介 1.Service 每个Service必须在manifest中 通过<service>来声明. 可以通过contect.startservice和contect.bin ...
 - Android 开发之如何保证Service不被杀掉(broadcast+system/app)
		
序言 最近项目要实现这样一个效果:运行后,要有一个service始终保持在后台运行,不管用户作出什么操作,都要保证service不被kill,这可真是一个难题.参考了现今各种定制版的系统和安全厂商牛虻 ...
 - Android开发手记(28) Handler和Looper
		
Android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道.平 ...
 
随机推荐
- 通过jquery-ui中的sortable来实现拖拽排序
			
1.引入文件 <script src="{sh::PUB}js/jquery-1.10.1.min.js"></script> <link rel=& ...
 - VM Depot 镜像新增系列III – 社交媒体,内容管理 与 项目协同系统
			
 发布于 2014-06-30 作者 刘 天栋 对于架设可协同作业的网站平台, Windows Azure有着得天独厚的优势.这不仅在于其强大的扩展性和安全性,更重要的是 Azure 平台对各类 ...
 - UVA1416 Warfare And Logistics
			
UVA1416 Warfare And Logistics 链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=36232 [ ...
 - openStack 性能开测
 - 天津Uber优步司机奖励政策(1月18日~1月24日)
			
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
 - ArrStack——数组栈(procedure)
			
//数组栈,对于无法预料栈的长度情况下,可能会因为原分配数组不够长而导致数据溢出,或因为数组太长而浪费空间.但是操作快,不需要额外的操作.而链表与此想法,可以动态分配内存,但是要增加额外的操作. #i ...
 - 002-python书写规范--消去提示波浪线
			
强迫症患者面对PyCharm的波浪线是很难受的,针对如下代码去除PyCharm中的波浪线: # _*_coding:utf-8_*_ # /usr/bin/env python3 A_user = & ...
 - Parallel.Foreach的并发问题解决方法-比如爬虫WebClient
			
场景五:线程局部变量 Parallel.ForEach 提供了一个线程局部变量的重载,定义如下: public static ParallelLoopResult ForEach<TSource ...
 - Hibernate自定查询返回list<?>
			
/** * * @param session * :一个会话 * * @param hql * :是需要执行的hql语句, * * @param offset * 设置开始位置 * * @param ...
 - textarea文本域
			
textarea中换行问题 一旦用nl2br函数处理会多个\n导致十分难看 也无法形成文本框默认效果 前台的html如果用<br/>处理也会给后台的编辑造成困难 所以在编辑的时候这样处理 ...