Highly recommended article: Welcome Favorite
Android Dry Share
Reading five minutes, ten o'clock daily, lifelong learning with you, here is the Android programmer
This article describes the Android
part of the development of knowledge by reading this article, you will reap the following:
- Broadcast life cycle
- One of the four components, it must be registered in the Androidmainfest.xml
- Registration broadcasting (radio static, dynamic broadcast)
- Broadcast transmission (normal, orderly and sustained)
- The broadcast receiving (broadcasting system, custom broadcast)
Broadcast
Is Android
one of the four components, is a mechanism widely used in asynchronous transfer information between applications.
Broadcast
In essence is a Intent
target, wherein the difference Broadcast
may be a plurality of BroadcastReceiver
processing. BroadcastReceiver
It is a global listener, through which onReceive()
can filter the broadcast that the user wants, and then perform other operations.
Introduction 1. BroadcastReceiver
BroadcastReceiver inheritance
BroadcastReceiver
The default is to perform in the main thread, if the onReceiver()
method to handle events over 10s
, the application will take place ANR(Application Not Responding)
at this time, if the establishment of worker threads will not solve this problem, it is proposed: time-consuming operations such as handling, use Service
instead.
BroadcastReceiver
Inheritance as follows:
java.lang.Object
↳ android.content.BroadcastReceiver
BroadcastReceiver
The main statement cycle approach onReceiver()
, after the completion of the implementation of this method, BroadcastReceiver
examples will be destroyed.
2. One of the four components, must be registered in the Androidmainfest.xml
<receiver
android:name="ReceiverMethod"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="String....." />
</intent-filter>
</receiver>
Note:
If you do not register, will result in a broadcast message can not be processed
Broadcast Registration (static registration and dynamic registration)
Registered broadcast two, one in the ndroidMfest.xml
registration static, the other is in the Java
dynamic registration code.
1. static registration
Some broadcast systems required in Androidmainfest.xml
the static registration, such as boot broadcast, apk change of state broadcasting, power state change broadcasting. These static registration broadcast, usually in the Androidmainfest.xml
interception of a particular string.
Radio static registration method is as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.programandroid"
android:versionCode="1"
android:versionName="1.0" >
... ...
<receiver
android:name="com.programandroid.BroadcastReceiver.NotificationReceived"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="Notification_cancel" />
<action android:name="Notification_music_pre" />
<action android:name="Notification_music_play" />
<action android:name="Notification_music_next" />
</intent-filter>
</receiver>
... ...
1. Power broadcast static registration method
Broadcast special boot, you need to Androidmainfest.xml
add permissions. Otherwise, you can not get the boot broadcast.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
//静态注册广播的方法
<receiver
android:name=".component.BroadcastReceiver.BootReceiverMethod"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
2. dynamic registration broadcast
In Java, dynamic registration broadcast, usually in the following format:
//动态注册广播
registerReceiver(BroadcastReceiver, IntentFilter);
Dynamic registration screen monitor off, light up the screen broadcast
Dynamic registration on the radio broadcast, please note that we must use context.getApplicationContext()
to prevent context
empty, causing a null pointer exception.
public class ScreenOnOffReceiver {
public static void ReceiverScreenOnOff(Context context) {
IntentFilter screenOffFilter = new IntentFilter();
screenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
screenOffFilter.addAction(Intent.ACTION_SCREEN_ON);
BroadcastReceiver mScreenOnOffReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Toast.makeText(context, "接收屏幕熄灭广播", Toast.LENGTH_SHORT).show();
}
if (action.equals(Intent.ACTION_SCREEN_ON)) {
Toast.makeText(context, "接收屏幕点亮广播", Toast.LENGTH_SHORT).show();
}
}
};
/**
* context.getApplicationContext()
* 在广播中注册广播时候需要注意,防止context 为空 ,引起空指针异常
* **/
// 2.动态注册广播的方法
context.registerReceiver(mScreenOnOffReceiver, screenOffFilter);
}
}
4. broadcast transmission (unordered, ordered, continuous)
1. A method of transmitting a broadcast disordered
Send disorder broadcasting Android
is common in a relationship of one to many, mainly by sendBroadcast(intent);
sending broadcasts.
Send custom broadcast Case
Broadcast it means a belt Action
and other string tag Intent
. Send custom broadcast for example as follows:
Intent customIntent=new Intent();
customIntent.setAction("SendCustomBroadcast");
sendBroadcast(customIntent);
The method of receiving broadcast Custom
When the user some broadcasters interested, can obtain the broadcast case, then onReceive
the processing operation at receiving a broadcast method.
public class CustomBroadcast extends BroadcastReceiver {
public CustomBroadcast() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SendCustomBroadcast")){
Toast.makeText(context,"自定义广播接收成功:Action:SendCustomBroadcast",Toast.LENGTH_SHORT).show();
}
}
}
Note Custom broadcast in
Androidmanfest.xml
static registration.
2. Send orderly broadcast
Broadcast Android
is a priority, a high priority broadcast may terminate or modify the broadcast content. Method of transmitting a broadcast order is as followssendOrderedBroadcast(intent,"str_receiver_permission");
For example: Send custom ordered broadcast
Intent customOrderIntent=new Intent();
customOrderIntent.setAction("SendCustomOrderBroadcast");
customOrderIntent.putExtra("str_order_broadcast","老板说:公司每人发 10 个 月饼");
sendOrderedBroadcast(customOrderIntent,"android.permission.ORDERBROADCAST");
Belong to broadcast the four components must be in the AndroidMainfest.xml
registry.
Ordered broadcast static registration
Static registration method of receiving broadcasting ordered as follows:
<receiver
android:name=".component.BroadcastReceiver.CustomHightBrodcast"
android:enabled="true"
android:exported="true"
>
<intent-filter android:priority="1000">
<action android:name="SendCustomOrderBroadcast" />
</intent-filter>
</receiver>
<receiver
android:name=".component.BroadcastReceiver.CustomMiddleBroadcast"
android:enabled="true"
android:exported="true"
>
<intent-filter android:priority="500">
<action android:name="SendCustomOrderBroadcast" />
</intent-filter>
</receiver>
<receiver
android:name=".component.BroadcastReceiver.CustomLowerBroadcast"
android:enabled="true"
android:exported="true"
>
<intent-filter android:priority="100">
<action android:name="SendCustomOrderBroadcast" />
</intent-filter>
</receiver>
-
- Orderly broadcasting, high-priority broadcast prioritize
public class CustomHightBrodcast extends BroadcastReceiver {
public CustomHightBrodcast() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SendCustomOrderBroadcast")) {
Toast.makeText(context, intent.getStringExtra("str_order_broadcast"), Toast.LENGTH_SHORT).show();
Bundle bundle=new Bundle();
bundle.putString("str_order_broadcast","经理说:公司每人发 5 个 月饼");
// 修改广播传输数据
setResultExtras(bundle);
}
}
}
-
- After the priority order of processing broadcast
public class CustomMiddleBroadcast extends BroadcastReceiver {
public CustomMiddleBroadcast() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SendCustomOrderBroadcast")) {
Toast.makeText(context, getResultExtras(true).getString("str_order_broadcast"), Toast.LENGTH_SHORT).show();
Bundle bundle=new Bundle();
bundle.putString("str_order_broadcast","主管说:公司每人发 2 个 月饼");
setResultExtras(bundle);
}
}
}
-
- Low priority broadcast last treatment
public class CustomLowerBroadcast extends BroadcastReceiver {
public CustomLowerBroadcast() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SendCustomOrderBroadcast")) {
String notice= getResultExtras(true).getString("str_order_broadcast");
Toast.makeText(context,notice, Toast.LENGTH_SHORT).show();
// 终止广播继续传播下去
abortBroadcast();
}
}
}
Note:
Ordered need to declare and use the broadcast rights
- 1. Declare usage rights
<!-- 申请使用自定义 有序广播的权限 -->
<uses-permission > android:name="android.permission.ORDERBROADCAST" />
- 2. Declaration of Competence
<!-- 自定义 有序广播的权限 -->
<permission>
android:name="android.permission.ORDERBROADCAST"/>
High priority broadcast receiving broadcast, the broadcast can modify the data in-order, and then passed to a low-priority broadcast.
3. Send continued broadcasting (has been deprecated)
Sticky broadcast will Android
have been present in the system, but with the Android
system constantly updated, this method gradually abandoned, used as follows:sendStickyBroadcast(intent);
The broadcast receiving (broadcasting system, custom broadcast)
Once the broadcast is issued, how to receive broadcast it, the following will describe a method for receiving broadcast.
Receiving broadcast principal inheritance BroadcastReceiver
, then onReceive
, filtering broadcast Action
carried by Intent
, and then performs the correlation process.
A method of receiving a broadcast start
1. To achieve BootReceiverMethod inheritance BroadcastReceiver
p ublic class BootReceiverMethod extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 接收开机广播处理事情,比如启动服务
Intent mStartIntent = new Intent(context, StartServiceMethods.class);
context.startService(mStartIntent);
}
}
2. Androidmainfest.xml statement component information, and filtering the boot to complete the Action
<receiver
android:name=".component.BroadcastReceiver.BootReceiverMethod"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3. Statement receiving the broadcast rights to complete the boot
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Highly recommended article: Welcome Favorite
Android Dry Share
Reading five minutes, ten o'clock daily, lifelong learning with you, here is the Android programmer
This article describes the Android
part of the development of knowledge by reading this article, you will reap the following:
- Service Introduction
- One of the four components, it must be registered in the Androidmainfest.xml
- Startup mode service
- Binding Service binding mode
- Reception
- AIDL remote service
Service
Is Android
one of the four components ( Activity
activities, Service
services, ContentProvider
content providers, BroadcastReceiver
broadcast), and Activity
in comparison, Activity
is running in the foreground, you can see, Service
is running in the background, with no user interface, users can not see.
Service
Mainly used for interaction between the components (for example: with Activity
, ContentProvider
, BroadcastReceiver
interact), the background to perform time-consuming operation (such as downloading files, play music, but Service
in the main thread running length should not exceed 20s
, otherwise there will be ANR
time-consuming operation is generally recommended operating in the sub-thread).
1.Service Profile
In understanding Service
the previous life-cycle, we first look at Service
inheritance, to help us better understand Service
.
Service inheritance as follows:
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.app.Service
Two startup mode Service
Service
There are two different startup mode, startup mode different corresponding to different life cycle.
Service
Startup Mode is divided into two kinds: 1. Start mode. 2. binding mode.
1. Start mode
This mode startService()
method to start this service has been running in the background can not start with the demise of the component die out. Can only perform a single operation, no results are returned to the caller, commonly used in network download, upload files, play music and so on.
2. Binding mode
This mode binding component ( Activity
calls, etc.) bindService()
to start this service with the demise of the binding and unbinding of components.
If by this time there are no other startService()
start, this service will vary with the demise of binding components die out.
Not only can multiple components simultaneously bind one Service
, and inter-process communication can (IPC)
perform cross-process operations.
3. Both services can run at the same time
Start-up mode and the binding mode of service can run at the same time, the service at the time of the destruction, only two models are not in use Service
when the service before they can be destroyed, otherwise it will cause an exception.
4. two kinds of life-cycle mode Service
Two kinds of Service
model life cycle is as follows:
2. One of the four components, must be registered in the Androidmainfest.xml
Service registration method is as follows:
<manifest ... >
...
<application ... >
<service android:name=".ServiceMethods" />
...
</application>
</manifest>
note:
Service
If not registered, not as Activity
that would lead to App Crash
, Service
do not register will not be reported abnormal information, but the service will get up, do not pay attention as it is easy to confuse.
3. Start mode
By startup mode of Service
, if not take the initiative to shut down, Service
it will always be.
Startup mode of service method
Intent mBindIntent = new Intent(ServiceMethods.this, BindServiceMethods.class);
startService(mStartIntent);
Startup mode Lifecycle Services
Here is the authentication method startup mode of life-cycle services, please see the above detailed life cycle Service
life cycle graph.
01-03 17:16:36.147 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onCreate----
01-03 17:16:36.223 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onStartCommand----
01-03 17:16:38.174 23789-23789/com.android.program.programandroid I/StartService wjwj:: ----onDestroy----
Startup mode Service Case
This case features: Start Services, created in the service notification
// Service 创建方法
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "----onCreate----");
}
// Service 启动方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "----onStartCommand----");
// 获取NotificationManager实例
notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 实例化NotificationCompat.Builder并设置相关属性
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this)
// 设置小图标
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(
BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher))
// 设置通知标题
.setContentTitle("我是通过StartService服务启动的通知")
// 设置通知不能自动取消
.setAutoCancel(false).setOngoing(true)
// 设置通知时间,默认为系统发出通知的时间,通常不用设置
// .setWhen(System.currentTimeMillis())
// 设置通知内容
.setContentText("请使用StopService 方法停止服务");
// 通过builder.build()方法生成Notification对象,并发送通知,id=1
notifyManager.notify(1, builder.build());
return super.onStartCommand(intent, flags, startId);
}
// Service 销毁方法
@Override
public void onDestroy() {
Log.i(TAG, "----onDestroy----");
notifyManager.cancelAll();
super.onDestroy();
}
4. binding mode is activated binding service
Binding mode service will start with the gradual demise of the binding to release the Service
binding, if this time Service
is not started by the startup mode, this service will be destroyed.
The binding mode is activated binding service method
The binding mode is initiated by other components Service
.
Method to start binding mode services
// 启动绑定服务处理方法
public void BtnStartBindService(View view) {
// 启动绑定服务处理方法
bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
isBindService = true;
Toast.makeText(ServiceMethod.this, "启动 " + mBindCount + " 次绑定服务",
Toast.LENGTH_SHORT).show();
}
public void BtnSopBindService(View view) {
if (isBindService) {
// 解除绑定服务处理方法
unbindService(serviceConnection);
Toast.makeText(ServiceMethod.this, "解除 " + mUnBindCount + " 次绑定服务",
Toast.LENGTH_SHORT).show();
isBindService = false;
}
}
With the demise of binding service binding component die out
Binding mode lifecycle callbacks code is as follows:
// Service 创建方法
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "----onCreate----");
}
// Service 绑定方法
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "----onBind----");
MyBinder myBinder = new MyBinder();
return myBinder;
}
// Service 解除绑定方法
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "----onUnbind----");
return super.onUnbind(intent);
}
// Service 销毁方法
@Override
public void onDestroy() {
Log.i(TAG, "----onDestroy----");
super.onDestroy();
}
Lifecycle services binding code prints Log
the following information:
01-03 20:32:59.422 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onCreate----
01-03 20:32:59.423 13306-13306/com.android.program.programandroid I/BindService wjwj:: -----onBind-----
01-03 20:33:09.265 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onUnbind----
01-03 20:33:09.266 13306-13306/com.android.program.programandroid I/BindService wjwj:: ----onDestroy----
Binding Service Case
Function: Gets the number of binding mode is activated binding service and unbind services
Binding service classes
package com.android.program.programandroid.component.Service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class BindServiceMethods extends Service {
private static final String TAG = "BindService wjwj:";
public BindServiceMethods() {
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "----onCreate----");
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "----onBind----");
MyBinder myBinder = new MyBinder();
return myBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "----onUnbind----");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.i(TAG, "----onDestroy----");
super.onDestroy();
}
}
- The interactions between components and binding service classes
// 启动绑定服务处理方法
public void BtnStartBindService(View view) {
bindService(mBindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
isBindService = true;
Toast.makeText(ServiceMethods.this,"启动 "+mBindCount+" 次绑定服务",Toast.LENGTH_SHORT).show();
}
// 解除绑定服务处理方法
public void BtnSopBindService(View view) {
if (isBindService) {
unbindService(serviceConnection);
Toast.makeText(ServiceMethods.this,"解除 "+mUnBindCount+" 次绑定服务",Toast.LENGTH_SHORT).show();
isBindService=false;
}
}
- Interaction between the components required
Binder
interface class
/**
* 该类提供 绑定组件与绑定服务提供接口
* */
public class MyBinder extends Binder {
private int count = 0;
public int getBindCount() {
return ++count;
}
public int getUnBindCount() {
return count> 0 ? count-- : 0;
}
}
5. improve service priority
Services default startup mode is a background service, but may be set by front desk services, improve priority services, thereby avoiding the phone memory is tight, the service process is killed.
Set of two ways front desk
1. Set to front desk
//设置为前台服务
startForeground(int, Notification)
2. Cancellation front desk
//取消为前台服务 stopForeground(true);
startForeground front desk Case
Features: Front Desk binding notification information, improve service process priority, otherwise the cancellation notice information
package com.android.program.programandroid.component.Service;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.android.program.programandroid.R;
public class MyStartForcegroundService extends Service {
public MyStartForcegroundService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("start_forceground_service")) {
// 获取NotificationManager实例
NotificationManager notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 实例化NotificationCompat.Builder并设置相关属性
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// 设置小图标
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
// 设置通知标题
.setContentTitle("我是通过startForeground 启动前台服务通知")
// 设置通知不能自动取消
.setAutoCancel(false)
.setOngoing(true)
// 设置通知时间,默认为系统发出通知的时间,通常不用设置
// .setWhen(System.currentTimeMillis())
// 设置通知内容
.setContentText("请使用stopForeground 方法改为后台服务");
//通过builder.build()方法生成Notification对象,并发送通知,id=1
// 设置为前台服务
startForeground(1, builder.build());
} else if (intent.getAction().equals("stop_forceground_service")) {
stopForeground(true);
}
return super.onStartCommand(intent, flags, startId);
}
}
6. Use the remote interface binding AIDL
As more content, open another follow-up detail.
So far herein, this has ended, if the wrong place, welcome your suggestions and corrections. At the same time look forward to your attention, thank you for reading, thank you!