android 发送前台广播,使用IntentService与BroadcastReceiver实现后台服务(Android7.0可用)...
IntentService的优点
IntentService会创建单独的线程处理所有的Intent请求,
会处理onHandleIntent方法实现的代码,
隐藏开发者无须处理多线程问题,
当所有请求处理完成后,IntentService会自动停止
Action的使用
Action其实就是一个字符串,可以起到一个标识的作用
BroadcastReceiver的使用
BroadcastReceiver本质是一个监听器,有自己的进程
重写onReceive方法即可,但是在该方法里面不要执行耗时的操作,否则会ANR
发送
创建Intent
设置Action
putExtra
send发送
接收
实现onReceive方法
在AndroidManifest内增加配置
BroadcastReceiver
其他
开机自动运行的Service
第一步
动态注册广播
broadcastReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.space.text2.action.MSGTEXT");
//这个Action的作用是当发送为该Action的广播时,
该MyReceiver类的onReceive方法将会接收到并处理
registerReceiver(broadcastReceiver,intentFilter);
第二步
在Activity中添加一个UI组件,比如按钮
为按钮添加监听器
在该监听器内启动IntentService
Intent intent = new Intent(FinsihActivity.this,TextIntentService.class);
intent.setAction("com.example.space.text2.action.MSGFINSIH");
//设置该Action以便IntentService接收到Intent,
判断是哪个Action,如果是这个Action话,就进行相应处理
intent.putExtra("finish","这是finishactivity发送的消息");
FinsihActivity.this.startService(intent);
第三步
添加一个IntentService.java类,可以使用Android Studio的自动生成
注释掉没有用的代码
但是一定要保留protected void onHandleIntent(Intent intent) 和
public TextIntentService() {
super("TextIntentService");
}
方法
在protected void onHandleIntent(Intent intent) 方法中进行后台任务的处理即可
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_MSGFINSIH.equals(action)) {
String param1 = intent.getStringExtra("finish");
Intent intent1 = new Intent(ACTION_MSGTEXT);
//此处ACTION_MSGTEXT等于"com.example.space.text2.action.MSGTEXT",
生成包含该Action的Intent后,就可以使用sendBroadcast发送广播了,
之后自己定义的MyReceiver类的onReceive方法将会接收到并处理
intent1.putExtra("msg",param1+",IntentService收到并且广播了出去");
sendBroadcast(intent1);
}
}
}
第四步
在自己定义的MyReceiver类的onReceive方法将会接收到并处理收到的intent
这个自己定义的MyReceiver类最好以内部类的形式写在使用该广播的Activity中,
这样就可以使用该Activity的UI组件了,
即可实现把后台服务进程中的数据更新在UI线程中的UI组件中
//内部类
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"),
Toast.LENGTH_SHORT).show();
//throw new UnsupportedOperationException("Not yet implemented");
//注意,该句是自动生成的,
一定要注释掉,否则程序会崩溃重启,
无法显示出后台服务通过广播改变前台UI的效果
}
}
完整代码
第一个是Activity
public class FinsihActivity extends AppCompatActivity {
BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finsih);
//第一步:注册广播,绑定广播和action
try
{
broadcastReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.space.text2.action.MSGTEXT");
registerReceiver(broadcastReceiver,intentFilter);
Log.i("mss","registerReceiver(broadcastReceiver,intentFilter);");
}
catch (ParcelFormatException e)
{
Log.i("mss","catch");
}
Button button = (Button)super.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//第二步:开始IntentService
try
{
Intent intent = new Intent(FinsihActivity.this,TextIntentService.class);
Log.i("mss","Intent intent = new Intent(FinsihActivity.this,TextIntentService.class)");
intent.setAction("com.example.space.text2.action.MSGFINSIH");
intent.putExtra("finish","这是finishactivity发送的消息");
FinsihActivity.this.startService(intent);
Log.i("mss","FinsihActivity.this.startService(intent);");
Toast.makeText(getApplicationContext(), "startService(intent)", Toast.LENGTH_SHORT).show();
}
catch(ParcelFormatException e)
{
Log.i("mss","catch");
}
}
});
}
//内部类
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//
Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();
// TextView textView = (TextView)FinsihActivity.super.findViewById(R.id.textView13);
// textView.setText(""+intent.getStringExtra("msg"));
//throw new UnsupportedOperationException("Not yet implemented");
}
}
}
第二个是IntentService
public class TextIntentService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_MSGTEXT = "com.example.space.text2.action.MSGTEXT";
private static final String ACTION_MSGFINSIH = "com.example.space.text2.action.MSGFINSIH";
private static final String ACTION_BAZ = "com.example.space.text2.action.BAZ";
// TODO: Rename parameters
public TextIntentService() {
super("TextIntentService");
}
// /**
// * Starts this service to perform action Foo with the given parameters. If
// * the service is already performing a task this action will be queued.
// *
// * @see IntentService
// */
// // TODO: Customize helper method
// public static void startActionFoo(Context context, String param1, String param2) {
// Intent intent = new Intent(context, TextIntentService.class);
// intent.setAction(ACTION_MSGTEXT);
// intent.putExtra(EXTRA_PARAM1, param1);
// intent.putExtra(EXTRA_PARAM2, param2);
// context.startService(intent);
// }
//
// /**
// * Starts this service to perform action Baz with the given parameters. If
// * the service is already performing a task this action will be queued.
// *
// * @see IntentService
// */
// // TODO: Customize helper method
// public static void startActionBaz(Context context, String param1, String param2) {
// Intent intent = new Intent(context, TextIntentService.class);
// intent.setAction(ACTION_BAZ);
// intent.putExtra(EXTRA_PARAM1, param1);
// intent.putExtra(EXTRA_PARAM2, param2);
// context.startService(intent);
// }
@Override
protected void onHandleIntent(Intent intent) {
Log.i("mss","onHandleIntent");
if (intent != null) {
final String action = intent.getAction();
if (ACTION_MSGFINSIH.equals(action)) {
Log.i("mss","ACTION_MSGFINSIH.equals(action)");
String param1 = intent.getStringExtra("finish");
Log.i("mss","intent.getStringExtra(\"finish\") = "+param1);
Intent intent1 = new Intent(ACTION_MSGTEXT);
Log.i("mss","Intent intent1 = new Intent(ACTION_MSGTEXT);");
Log.i("mss",ACTION_MSGTEXT);
intent1.putExtra("msg",param1+",IntentService收到并且广播了出去");
Log.i("mss","intent1.putExtra(\"msg\",param1+\",IntentService收到并且广播了出去\");");
sendBroadcast(intent1);
Log.i("mss","super.sendBroadcast(intent1);");
}
}
}
// /**
// * Handle action Foo in the provided background thread with the provided
// * parameters.
// */
// private void handleActionFoo(String param1, String param2) {
// // TODO: Handle action Foo
// throw new UnsupportedOperationException("Not yet implemented");
// }
// private void handleActionFinish(String param1, String param2) {
// // TODO: Handle action Foo
// throw new UnsupportedOperationException("Not yet implemented");
// }
// /**
// * Handle action Baz in the provided background thread with the provided
// * parameters.
// */
// private void handleActionBaz(String param1, String param2) {
// // TODO: Handle action Baz
// throw new UnsupportedOperationException("Not yet implemented");
// }
}
第三个是AndroidManifest
android:name=".TextIntentService"
android:exported="false">
其中exported="false"的意思是防止其他应用访问该Service
android 发送前台广播,使用IntentService与BroadcastReceiver实现后台服务(Android7.0可用)...相关推荐
- android: 发送自定义广播
5.3.1 发送标准广播 在发送广播之前,我们还是需要先定义一个广播接收器来准备接收此广播才行,不然发 出去也是白发.因此新建一个 MyBroadcastReceiver 继承自 Broadca ...
- android 发送重启广播,Android实现关机重启的方法分享
实现系统重启的APK需要system的权限,在AndroidManifest.xml中增加android:sharedUserId="android.uid.system",再修改 ...
- android 发送显示广播,如何查看Android系统当前发送了什么广播
作者:Yogi 前言:在开发的时候,我们有时想知道我们定义的广播是否成功发送,或者想知道做了某个操作,系统是否会发送广播,并且发送了什么广播.如果说能够直接查看到,那是非常好的,这样就不需要googl ...
- 说说Android的广播(4) - 前台广播为什么比后台广播快?
说说Android的广播(4) - 前台广播为什么比后台广播快? 前台广播为什么比后台广播快 讨论超时的细节之前,我们先讲讲对应用开发有帮助的,为什么前台队列比后台队列要快? 应用开发的同学在给系统团 ...
- Android——后台服务
Android应用编程实验 实验名称:Android 后台服务 实验目的:通过Service设计后台服务程序,通过Broadcast实现信息广播机制 实验内容: 设计一个简单的后台音乐服务程序: 设计 ...
- android 测试屏幕触点,如何检测Android Studio中的后台服务是否触摸了屏幕?
我正在研究 android studio上的一个项目.我需要在后台服务中检测屏幕是否被触摸(并弹出一条消息).但是,我在后台服务中检测屏幕是否被触摸有问题而不影响使用智能手机的用户. 当我说" ...
- Android短信的发送和广播接收者实现短信的监听
Android短信的发送和广播接收者实现短信的监听 要注意Android清单中权限的设置以及广播的注册监听实现 以下就是 Android清单的XML AndroidManifest.xml < ...
- Android——发送和接收广播
一,发送广播 利用Intent来发送广播. 使用:在需要发送广播的地方创建一个Intent对象,将信息的内容和用于过滤的信息封装起来,通过以下三种方法将Intent广播出去: 1,Context.se ...
- Android 第二十课 广播机制(大喇叭)----发送自定义广播(包括发送标准广播和发送有序广播)
广播分为两种类型:标准广播和有序广播 我们来看一下具体这两者的具体区别: 1.发送标准广播 我们需要先定义一个广播接收器来准备接收此广播才行,否则也是白发. 新建一个MyBroadcastReceiv ...
最新文章
- Storage medium
- 【火爆全网,好评如潮】DS100手持示波器现货发售拉,附原子哥发布会详细讲解视频以及宣传视频...
- wpf: DataGridTextColumn 数字格式显示,编辑时取消格式(StringFormat)
- 陈松松:如何锁定细分领域,视频营销才更容易持续做下去
- HDU1864(01背包)
- linux裁剪内核和移植,嵌入式Linux内核裁剪及移植的研究与实现
- turtle库自动轨迹绘制
- 小毛thinking:why c# sucks and python rocks
- python正则表达式笔记之字符集合的使用
- 电力系统分析—潮流计算代码Python编程练习(基于极坐标形式的常规牛拉法)
- 在div的左上角添加三角形,文字45度倾斜显示
- 一文详解结构光发展简史
- IT互联网行业猎头的年终总结:结束后开始
- 交叉编译openssl(arm和x86_64)
- OFDMA和OFDM的区别
- 限制百度地图拖动范围限制,当超如范围时自动返回
- GAN生成对抗网络基础知识
- 每日3词 2021-03-11 【name】【attribute】【value】
- 艾略特波段理论实战(1):8浪
- 10家企业上榜!2021“中国制造隐形冠军”完整榜单揭晓