Android 锁屏后不被暂停的奇淫巧计

据说是某狗音乐的方案。现在的情况是锁屏后线程、主进程都停止运行,建立服务置为前台服务,绑定通知都不行。

但是一些音乐类软件还能后台播放,所以打开脑洞,一直播放一个无声的音频能不能保持锁屏后进程运行。

测试后确实可行。前台服务/绑定通知+循环播放无声音频。

 

public class MService extends Service {

    Notification notification;
    private Context mContext;
    public static Thread thread;
    private MediaPlayer mediaPlayer;
    private boolean isrun = true;

    public MService() {
    }

    public static final String CHANNEL_ONE_ID = "nyd001";
    public static final String CHANNEL_ONE_NAME = "诺秒贷";

    private static class MyHandler extends Handler {
        private WeakReference<MService> reference;
        public MyHandler(MService service) {
            reference = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                //todo
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            sendEmptyMessageDelayed(0, 5000);
        }
    }

    MyHandler handler;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mContext = this;

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {

            Notification.Builder builder = new Notification.Builder(mContext)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setTicker("music")
                    .setContentTitle("标题")
                    .setContentText("内容")
                    .setOngoing(true)
                    .setPriority(PRIORITY_MAX)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(false);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                 //修改安卓8.1以上系统报错
                 NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
                 notificationChannel.enableLights(false);//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
                 notificationChannel.setShowBadge(false);//是否显示角标
                 notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
                 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                 manager.createNotificationChannel(notificationChannel);
                 builder.setChannelId(CHANNEL_ONE_ID);
            }

            notification = builder.build();
        }
        /*使用startForeground,如果id为0,那么notification将不会显示*/
        startForeground(100, notification);

        
        if(thread == null){
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    
                    while (isrun){

                        
                        try {
                            Thread.sleep(5000);
                            try {
                                //todo
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                           

                            return;
                        }

                    }
                }
            });
        }

        handler = new MyHandler(this);
//        handler.sendEmptyMessage(0);
        thread.start();

        
        if(mediaPlayer == null){
            mediaPlayer = MediaPlayer.create(this,R.raw.test);
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
        }

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        isrun = false;
        stopForeground(true);
        thread.interrupt();
        mediaPlayer.release();
        handler.removeMessages(0);
        stopSelf();
        super.onDestroy();
    }
}

 

Intent forgroundService = new Intent(this,MService.class);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                startForegroundService(forgroundService);
            } else {
                startService(forgroundService);
            }


Intent forgroundService = new Intent(this,MService.class);
            stopService(forgroundService);

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android锁屏无法继续定位问题 产生问题的原因: 手机锁屏后,Android系统为了省电以及减少CPU消耗,在一段时间后会将手机进入休眠状态。此时的服务以及线程等都会停止。 最近就这个问题,阅读了很多代码以及官方文档,下面就说下最近都尝试过的方式,可能其中有些您实现了,我这边没实现,望见谅。本文采用的高德定位。 一、PowerManager.WakeLock (1)直接强制当前页面cpu运行 private PowerManager pm; private PowerManager.WakeLock wakeLock; @Override public void onCreate() { super.onCreate(); //创建PowerManager对象 pm = (PowerManager) getSystemService(Context.POWER_SERVICE); //保持cpu一直运行,不管屏幕是否黑屏 wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CPUKeepRunning"); wakeLock.acquire(); } @Override public void onDestroy() { wakeLock.release(); super.onDestroy(); } 这个写法我表示并没有什么用,并不能强制cpu持续运行。 (2)WakefulBroadcastReceiver public class WLWakefulReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // String extra = intent.getStringExtra("msg"); Intent serviceIntent = new Intent(context, MyIntentService.class); serviceIntent.putExtra("msg", extra); startWakefulService(context, serviceIntent); } } WakefulBroadcastReceiver 内部的原理也是PowerManager,注册广播时8.0的请动态注册,静态没有用。广播注册完了之后,写一个服务用来与广播互动。 public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void onHandleIntent(@Nullable final Intent intent) { //子线程中执行 Log.i("MyIntentService", "onHandleIntent"); String extra = intent.getStringExtra("msg"); new Thread(new Runnable() { @Override public void run() { Loca

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值