前面我们学习了广播的内容,现在我们就来综合运用下广播。通过广播来实现强制下线功能。其实强制下线我们大家并不陌生,我们已经遇到,QQ,微信,微博等等都用强制下线的功能。这时候就会弹出一个对话框来告知你,你被强制下线了,你点确定就会退到登录的界面。这个逻辑还是挺简单的,接下来就让我们运用广播的知识来实现吧!(但这个程序可能有点小bug,不喜勿进。)
效果图
登录界面
首先我们就需要实现登录的界面,用它来实现用户登录。我们需要新建一个LoginActivity活动,它所对应的布局界面是login.xml。我们要将LoginActivity活动改为主活动,让程序启动的时候以LoginActivity活动界面启动。这一步比较简单,我就不细说了,直接看代码。
<activity android:name=".MainActivity" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
接下来我们需要把登录的布局做出来。这里我们用到的是表格布局。控件也比较简单,一行是输入账号,一行是输入密码,一行是登录按钮。
android:inputType=“textPassword”这里是把账号用星号掩饰掉,让人看不到你的密码。
android:stretchColumns="1"代表TableRow中的每第二列拉长铺满一行。 android:layout_span="2"表示把两行合并成一行
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"
tools:context=".LoginActivity">
<!-- android:layout_span="2" 表示两行合并成一行-->
<TableRow>
<TextView
android:layout_height="wrap_content"
android:text="账号:"
/>
<EditText
android:id="@+id/account"
android:layout_height="wrap_content"
android:hint="请输入用户账号"
/>
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:text="密码:"
/>
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword"
/>
</TableRow>
<TableRow>
<Button
android:id="@+id/login"
android:layout_height="wrap_content"
android:layout_span="2"
android:text="登录"/>
</TableRow>
</TableLayout>
创建基类与工具类
这里我们的LoginActivity要继承一个BaseActivity,可我们没有这个类,就需要我们去新建一个基类BsaeActivity。但我们需要的活动类,课BaseActivity并不是活动,我们就需要让他继承Activity。并且要重写他的onCreate()方法和onDestroy()方法。
然后我们再去编写工具类 ActivityCollector ,它用于管理所有的活动。这里我们活动用一个动态数组装,方便使用。方法我们也都是用的全局,课为什么要用全局呢,因为我们这是一个工具类,为了便于其他类来使用,所以我们需要用全局的。方法的解释我在代码里写了,这里就不简绍了。
package com.example.myapplication13;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
/**
* @author QiuSiQi
* @package com.example.myapplication13
* @fileName ActivityCollector
* @date on 2020/4/7 10:52
* @describe TODO
*/
public class Ac