Android进阶之路 - 广播实现强制下线功能

阅读本文需 5分,理解本文需8分,copy本文需3分

修订于2019/11/1
采用的是Android中的广播机制,如果大家不理解广播的使用的话,可以通过以下地址进行学习(可以比较全面的理解和使用)
Android进阶之路 - 四大组件之BroadcaseReceiver

本篇学于郭霖大神的第一行代码(第二版),自我加以理解敲出自己的篇章 (很实用)

实现效果
Android进阶之路 - 广播实现强制下线功能_第1张图片

前置了解
正确账号:123
正确密码:123

AndroidMainfest(进入初始Activity设置)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dow.accountintercept">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <activity android:name=".LoginActivity"
            android:launchMode="singleTask">        
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"
            android:launchMode="singleTask"/>
    </application>
</manifest>
准备工作 - 关键部分
  • AccountReceiver - 下线广播接收器
package com.example.dow.accountintercept;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

public class AccoutReceiver 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("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityCollector.finishAll();
                context.startActivity(new Intent(context,LoginActivity.class));
            }
        });
            dialog.show();
    }
}

  • ActivityCollector(采用的郭神的工具类)- Activity管理工具类

主要作用在当用户跳转登录界面时不会因为操作返回键而返回到app内部界面

package com.example.dow.accountintercept;

import android.app.Activity;
import java.util.ArrayList;
import java.util.List;

public class ActivityCollector {
    public static List<Activity>activities=new ArrayList<Activity>();

    public static void addActivity(Activity activity){
        activities.add(activity);
    }

    public static void removeActivity(Activity activity){
        activities.remove(activity);
    }

    public static void finishAll(){
        for(Activity activity : activities){
            if (!activity.isFinishing()){
                activity.finish();
            }
        }
    }
}

  • BaseActivity - 将ActivityCollector使用到Base中,从而实现Activity的收集与操作
package com.example.dow.accountintercept;

import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {

    private AccountReceiver receiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter("ForcedDownline");
        receiver = new AccountReceiver();
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(receiver != null){
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}

实战场景
  • MainActivity - 需执行下线操作的场景类
package com.example.dow.accountintercept;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends BaseActivity {

    private TextView mBtn;

    @Override
    public  void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        mBtn = (TextView) findViewById(R.id.tv_btn);
        //在事件处理的内部进行发送广播
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("ForcedDownline");
                sendBroadcast(intent);
            }
        });
    }
}

Xml - activity_main

<?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:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dow.accountintercept.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="登陆成功,这里是主界面" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="强制下线"
        android:layout_gravity="center"
        android:background="#f00"
        android:textColor="#fff"
        android:id="@+id/tv_btn"
        android:layout_marginBottom="30dp"
        />
</LinearLayout>

  • LoginActivity - 执行下线操作后的登录界面
package com.example.dow.accountintercept;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends BaseActivity {

    private EditText mAccount;
    private EditText mPassword;
    private TextView mLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
        initData();
    }


    private void initView() {
        mAccount = (EditText) findViewById(R.id.ed_account);
        mPassword = (EditText) findViewById(R.id.ed_password);
        mLogin = (TextView) findViewById(R.id.tv_login);
    }
    private void initData() {
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String eAccount=mAccount.getText().toString();
                String ePassword= mPassword.getText().toString();
                if(eAccount.equals("123")&&ePassword.equals("123")){
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                }else{
                    Toast.makeText(LoginActivity.this,"用户密码错误,请您重新输入",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

Xml - activity_login

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_marginTop="150dp"
        android:layout_marginLeft="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:text="账户:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/ed_account"/>
    </LinearLayout>
    <LinearLayout
        android:layout_marginLeft="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:text="密码:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/ed_password"/>
    </LinearLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="登陆"
        android:id="@+id/tv_login"
        android:textColor="#fff"
        android:background="#3F51B5"
        android:layout_gravity="center"
        />
</LinearLayout>

你可能感兴趣的:(Android进阶之路,#,项目开发知识点归纳,Android,强制下线,广播强制下线)