最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。
广播在四大组件中算比较简单的一个,今天就结合自己的学习简单总结一下:
1,广播分类
我们可以把广播按照是否有序分为:
- 标准广播:完全异步,在发出后,所有注册了该广播的接收器都会同时接受到该广播
- 有序广播:同步机制,在发出后,同时只有一个接收器能接收到该广播
我们也可以根据广播的作用域分为:
- 全局广播:一个地方发出广播,所有应用的注册了该广播的接收器都可以接收
- 本地广播:本应用内有效
我们还可以根据广播的性质分为:
- 系统广播:android系统自带的广播,比如开机,网络变化,位置变化,电量变化等等,由系统自己发送
- 自定义广播:根据需求,自己定义的广播;这种广播只能自己业务实现发送
概念都不难理解,下面就来看看关于广播的使用步骤:
2,广播的使用步骤
第一步:定义自己想要的广播,如果是系统的,直接使用;如果自定义的,则只需要想一个名字即可;比如:
系统广播:
android.intent.action.BOOT_COMPLETED android.intent.action.DATE_CHANGED等等...;很多很多
自定义广播:
Intent intent=new Intent("hfut.com.why");
第二步:定义广播接收者,定义一个继承BroadcastReceiver的类,重写onReceive()方法,在里面实现自己在接收到广播后要处理的业务。
第三步:广播接收者注册,这里你可以选择静态(在AndroidManifest.xml)或者动态(记得一等要取消注册);实现的示例如下:
静态:
<receiver android:name=".ForceOffLineReceiver">
<intent-filter>
<action android:name="hfut.com.why"></action>
</intent-filter>
</receiver>
动态:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("hfut.com.why");
receiver=new ForceOffLineReceiver();
registerReceiver(receiver, intentFilter);
第四步:发送广播
系统广播:系统自己触发
自定义广播:
Intent intent=new Intent("hfut.com.why");
sendBroadcast(intent);
整个思路很简单,当然里面还有很多细节需要考虑和使用,比如上面发送自定义广播,我使用的是:sendBroadcast(intent)而在发送有序广播的时候,我们就需要使用:sendOrderdBroadcast(intent,参数2);参数2是一个和权限有关的参数,正常我们设置为null即可;还有就是我们在使用本地广播的时候,需要使用到一个LocalBroadcastManager来实现;首先通过其一个静态方法获取该类的一个实例,然后调用其发送广播的sendBroadcast()方法即可。注册也是一样需要使用这个实例的registerReceiver()方法。
3,综合示例:强制下线
书中给出了一个强制下线的小案列,这里我对其进行了简单的调整,把代码放在这里;该示例的主要功能就是通过广播模拟一个账号在其他地方登陆强制本地下线的现象。用得主要知识点有:
(1)广播(动态注册,取消注册,发送)
(2)SharedPreferences的基本使用,就是简单的读写数据操作
(3)AlertDialog的使用,主要就是简单的设置,包括点击事件的实现
(4)Activity的全局管理,这里主要使用了一个ActivityManager配合BaseActivity(自定义所有自己Activity的父类)的自定义类来实现
具体的代码:
ActivityManager.java:
package com.hfut.forceofflinedemo;
import android.app.Activity;
import java.util.List;
import java.util.ArrayList;
/**
* author:why
* created on: 2018/3/10 23:33
* description:
*/
public class ActivityManager {
//保存创建的activity
public static List<Activity> exsitActivities = new ArrayList<>();
//添加一个新建的activity
public static void add(Activity activity) {
exsitActivities.add(activity);
}
//删除一个activity
public static void remove(Activity activity) {
exsitActivities.remove(activity);
}
//关闭所有的activity,并清空列表
public static void finishAll() {
for (Activity activity : exsitActivities) {
if (!activity.isFinishing()) {
activity.finish();
}
}
//清空列表
exsitActivities.clear();
}
}
BaseActivity.java:
package com.hfut.forceofflinedemo;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
/**
* 用于管理创建的Activity
*/
public class BaseActivity extends AppCompatActivity {
ForceOffLineReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityManager.add(this);
}
//获取焦点才可以收到广播
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("hfut.com.why");
receiver=new ForceOffLineReceiver();
registerReceiver(receiver, intentFilter);
}
//失去焦点取消广播接收
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityManager.remove(this);
}
}
LoginActivity.java:
package com.hfut.forceofflinedemo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends BaseActivity {
private EditText name;
private EditText password;
private CheckBox status;
private TextView saveInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initUI();
}
private void initUI() {
this.name=findViewById(R.id.name);
this.password=findViewById(R.id.psd);
this.status=findViewById(R.id.cb);
this.saveInfo=findViewById(R.id.isSave);
//初始化UI数据
SharedPreferences loginInfo =getSharedPreferences("loginInfo",MODE_PRIVATE);
name.setText(loginInfo.getString("name",""));
password.setText(loginInfo.getString("psd",""));
status.setChecked(loginInfo.getBoolean("status",false));
}
public void login(View view){
if(name.getText().toString().equals("why")&&password.getText().toString().equals("123456")){
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
if(status.isChecked()){
//保存登录数据
SharedPreferences.Editor editor=getSharedPreferences("loginInfo",MODE_PRIVATE).edit();
editor.putString("name","why");
editor.putString("psd","123456");
editor.putBoolean("status",true);
editor.apply();
}
else{
}
finish();
}
else{
Toast.makeText(this,"用户名或者密码错误",Toast.LENGTH_SHORT).show();
}
}
}
activity_login.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.forceofflinedemo.LoginActivity">
<LinearLayout
android:layout_marginLeft="210dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="账户" />
<EditText
android:textSize="15dp"
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入账户" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="210dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码" />
<EditText
android:textSize="15dp"
android:password="true"
android:id="@+id/psd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入密码" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="180dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:textSize="20dp"
android:onClick="login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="登录" />
<TextView
android:id="@+id/isSave"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="保存密码"
/>
<CheckBox
android:id="@+id/cb"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
SuccesLoginActivity.java:
package com.hfut.forceofflinedemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SuccesLoginActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void forceOffLine(View view){
Intent intent=new Intent("hfut.com.why");
sendBroadcast(intent);
}
}
activity_succes.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.forceofflinedemo.SuccesLoginActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="恭喜你登录成功"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="forceOffLine"
android:text="强制下线"/>
</LinearLayout>
ForceOffLineReceiver.java:
package com.hfut.forceofflinedemo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
/**
* author:why
* created on: 2018/3/11 0:05
* description:
*/
public class ForceOffLineReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//实现强制下线功能弹窗
AlertDialog.Builder dialog=new AlertDialog.Builder(context);
dialog.setTitle("警告");
dialog.setMessage("你的账号在其他移动设备登录,请确认是否是本人操作");
dialog.setCancelable(false);
dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityManager.finishAll();
Intent intent1=new Intent(context,LoginActivity.class);
context.startActivity(intent1);
}
});
dialog.show();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hfut.forceofflinedemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SuccesLoginActivity" />
<activity android:name=".BaseActivity"></activity>
<receiver android:name=".ForceOffLineReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
<action android:name="android.intent.action.DATE_CHANGED"></action>
</intent-filter>
</receiver>
</application>
</manifest>
演示结果如下:
第一步:打开应用,进入图1
图 1
第二步:编辑如图2信息
图 2
第三步:点击登录,进入图3界面
图 3
第四步:点击“强制下线”,弹出对话框,如图4
图 4
第五步:点击确定,返回如图2登录界面,我们取消勾选“保存密码”,如图5
图 5
第六步:让后点击“登录”,点击“强制下线”,点击弹出对话框“确定”,返回如图6登录界面
图 6
总结:关于广播很多细节都没有写出来,因为这一块的东西确实相对较简单,基本上遇到问题查一查都很容易解决,于是主要结合一个示例展开;没有围绕具体单个知识点展开。好的,这一部分暂时就介绍到这来了。明天还要早起上班了,嘿嘿。