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打交道.平 ...
随机推荐
- Github、Jekyll 搭建及优化静态博客方法指南
尝试自己写 Blog 的人,一般会经历三个阶段. 第一阶段,刚接触 Blog,觉得很新鲜,试着选择一个免费空间来写. 第二阶段,发现免费空间限制太多,就自己购买域名和空间,搭建独立博客. 第三阶段,觉 ...
- utf8_to_utf16
17down voteaccepted Here's some code. Only lightly tested and there's probably a few improvements. C ...
- SQL语句 远程操作数据库
--远程操作数据库SQL语句exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '211.81.251.85 'exec sp_addlinkedsr ...
- ping详解
Linux系统的ping命令是常用的网络命令,它通常用来测试与目标主机的连通性,我们经常会说“ping一下某机器,看是不是开着”.不能打开网页时会说“你先ping网关地址192.168.1.1试试”. ...
- window.alert弹出处理
# -*- coding:utf-8 -*- """ window.alert 处理 """ from selenium import we ...
- Linux学习笔记12——Unix中的进程
通过调用fork和exec函数都能创建新的进程,但两者有着本质的区别:fork函数拷贝了父进程的内存映像,而exec函数用用新的映像来覆盖调用进程的进程映像的功能. 一 fork函数 #includ ...
- idea安装Scala插件
最近在学习研究kafka,当我们进行debug跟踪时,就需要研究源码了.kafka的源码是Scala语言,在此就需要Scala环境来运行kafka源码了. 接下来记录的是我在IDEA中安装Scala插 ...
- poj 2505 A multiplication game(博弈)
A multiplication game Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 5622 Accepted: ...
- JavaScript的Date 方法
js中Date 方法 Date (对象) Date 对象能够使你获得相对于国际标准时间(格林威治标准时间,现在被称为 UTC-Universal Coordinated Time)或者是 Flash ...
- [cocos2d-x3.0]Android+NDK+Eclipse环境搭建及编译步骤~
1: 必要准备 1): jdk&jre 2): adt-bundle 3): android ndk r9 4): python2.7 5): cocos2d-x 3.0 alpha0 2: ...