Android 监听HOME键、锁屏、亮屏、解锁广播操作是否启动前台service以及停止service

1.PhoneReceiver类



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.tsq.junbanpt.utils.MessageEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * @author xuwei
 * 监听手机锁屏 APP在前后台
 */
public class PhoneReceiver extends BroadcastReceiver {
    final String SYSTEM_DIALOG_REASON_KEY = "reason";
    final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    final String SYSTEM_DIALOG_REASON_LOCK_KEY = "lock";
    final String SYSTEM_DIALOG_REASON_RECENTAPPS_KEY = "recentapps";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //按HOME键
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
            if (reason != null && (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) || reason.equals(SYSTEM_DIALOG_REASON_LOCK_KEY) || reason.equals(SYSTEM_DIALOG_REASON_RECENTAPPS_KEY))) {
                //app 按HOME键
                EventBus.getDefault().post(new MessageEvent("监听APP在前后台", "HOME键"));
            }
        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
            //app 锁屏
            EventBus.getDefault().post(new MessageEvent("监听APP在前后台", "锁屏"));
        } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
            //app 亮屏
            EventBus.getDefault().post(new MessageEvent("监听APP在前后台", "亮屏"));
        } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
            //app 解锁
            EventBus.getDefault().post(new MessageEvent("监听APP在前后台", "解锁"));
        }
    }
}

 2.前台NotificationService



import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;

import com.tsq.junbanpt.R;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

public class NotificationService extends Service {
    private static final String TAG = "NotificationService";
    private NotificationManager notificationManager;
    //通知的唯一标识号。
    private int NOTIFICATION = R.string.notification_live_start;


    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    private void showNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        // 【适配Android8.0】设置Notification的Channel_ID,否则不能正常显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("notification_id");
        }

        // 额外添加:
        // 【适配Android8.0】给NotificationManager对象设置NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        }

        // 启动前台服务通知
        startForeground(1, builder.build());
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onDestroy() {
        super.onDestroy();
        notificationManager.cancel(NOTIFICATION);
    }

}

 3.在AndroidManifest中注册

  <service
            android:name=".module.netphone.socket.NotificationService"
            android:enabled="true"
            android:exported="true" />
        <activity android:name=".module.netphone.activity.NetPhoneActivity"></activity>

 4.应用到activity中

 

 //初始化forgroundService

  Intent forgroundService;
  forgroundService = new Intent(this, NotificationService.class);

 //广播注册
  receiver = new PhoneReceiver();
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction("android.intent.action.CLOSE_SYSTEM_DIALOGS");
  intentFilter.addAction("android.intent.action.SCREEN_OFF");
  intentFilter.addAction("android.intent.action.SCREEN_ON");
  intentFilter.addAction("android.intent.action.USER_PRESENT");
  registerReceiver(receiver, intentFilter);

//销毁广播
 @Override
    protected void onDestroy() {
        super.onDestroy();
        //广播销毁
        unregisterReceiver(receiver);
    }

  //处理退到后台之后又点击返回APP时 停止service
   @Override
    protected void onResume() {
        super.onResume();
        if (isAppForeground("com.tsq.junbanpt")) {
            NetPhoneActivity.this.stopService(forgroundService);
        }
    }


 /**
     * 接受广播发送的消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        if (event.getType().equals("监听APP在前后台")) {
            if (event.getContect().equals("HOME键")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NetPhoneActivity.this.startForegroundService(forgroundService);
                } else {
                    NetPhoneActivity.this.startService(forgroundService);
                }
            } else if (event.getContect().equals("锁屏")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NetPhoneActivity.this.startForegroundService(forgroundService);
                } else {
                    NetPhoneActivity.this.startService(forgroundService);
                }
            } else if (event.getContect().equals("亮屏")) {
                if (isAppForeground("com.tsq.junbanpt")) {
                    NetPhoneActivity.this.stopService(forgroundService);
                }
            } else if (event.getContect().equals("解锁")) {
                if (isAppForeground("com.tsq.junbanpt")) {
                    NetPhoneActivity.this.stopService(forgroundService);
                }
            }
        }
    }

    /**
     * 判断APP是否在前台
     */
    private boolean isAppForeground(String packageName) {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(packageName)) {
            return true;
        }

        return false;
    }

 5.这里没有对EventBus的使用做介绍,要是不会的话查一下,很简单

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中可以通过重写 `onKeyDown()` 方法来监听 back ,`onUserLeaveHint()` 方法来监听 home ,以及通过注册系统广播监听多任务(最近任务)。 以下是示例代码: 1. 监听 back Service 中重写 `onKeyDown()` 方法,判断 keyCode 是否为 KeyEvent.KEYCODE_BACK,即可监听到 back 的点击事件。 ``` @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 处理 back 点击事件 return true; } return super.onKeyDown(keyCode, event); } ``` 2. 监听 home Service 中重写 `onUserLeaveHint()` 方法,即可监听home 的点击事件。 ``` @Override public void onUserLeaveHint() { super.onUserLeaveHint(); // 处理 home 点击事件 } ``` 3. 监听多任务(最近任务) 通过注册系统广播 `Intent.ACTION_CLOSE_SYSTEM_DIALOGS`,即可监听到多任务(最近任务)的点击事件。 ``` private BroadcastReceiver mCloseSystemDialogsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (TextUtils.equals(action, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); if (TextUtils.equals(reason, SYSTEM_DIALOG_REASON_RECENT_APPS)) { // 处理多任务点击事件 } } } }; private static final String SYSTEM_DIALOG_REASON_KEY = "reason"; private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"; private void registerCloseSystemDialogsReceiver() { IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); } private void unregisterCloseSystemDialogsReceiver() { unregisterReceiver(mCloseSystemDialogsReceiver); } ``` 在 Service 的 `onCreate()` 方法中注册广播,`onDestroy()` 方法中注销广播: ``` @Override public void onCreate() { super.onCreate(); registerCloseSystemDialogsReceiver(); } @Override public void onDestroy() { super.onDestroy(); unregisterCloseSystemDialogsReceiver(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值