简体   繁体   English

当手机进入睡眠状态时,无法获得android活动

[英]Cant get android activity to stay on when the phone goes to sleep

I am rather new to android and I am attempting an alarm clock app. 我是Android的新手,正在尝试使用闹钟应用程序。 I am starting an activity through an AlarmManager which works fine as long as the phone is awake. 我正在通过AlarmManager启动活动,只要手机醒着就可以正常工作。 When the phone is asleep it appears to run the code properly and then it runs the onStop function closing the activity. 当手机处于睡眠状态时,它似乎可以正常运行代码,然后运行onStop功能关闭活动。 I have tried various combinations of WakeLock and Window flags with no avail. 我尝试了WakeLock和Window标志的各种组合,但无济于事。

This does however work on an older phone (2.3) if that helps. 但是,如果有帮助,这可以在较旧的电话(2.3)上运行。 Any insight is appreciated. 任何见解均表示赞赏。

Here is code for the Alarm activity: 这是“警报”活动的代码:

package com.myAlarm.android;

import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.DigitalClock;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView;
import com.snoozulooze.android.UtilityFunctions;

@SuppressLint("NewApi")
public class Alarm extends Activity{
    private int timerDelay = 4000;
    private int id;
    private double snoozeInt = 1;
    private TextView clockText;
    private TextView dateText;
    private LinearLayout clockLayout;
    private DatabaseHandler db;
    public static AlarmRow ALARM_DATA;
    private Animation animScroll;
    private SensorManager mSensorManager;
    private ShakeEventListener mSensorListener;
    private Runnable alertLoop;
    private Handler handler;
    private ImageView snooze;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        turnOnScreen();
        Log.i("ALARM", "on create ran");
        AlarmWakeLock.acquireCpuWakeLock(Alarm.this);
        setContentView(R.layout.activity_alarm);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorListener = new ShakeEventListener();   
        handler = new Handler();
        alertLoop = new Runnable() {

            @Override
            public void run() {
                playAlarm();
                handler.postDelayed(this, timerDelay);

            }

        };

        //Create the clock for text clock of digital clock
        LayoutParams clockParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        clockLayout = (LinearLayout)findViewById(R.id.alarmClockLayout);
        dateText = (TextView) findViewById(R.id.alarmClockDateTxt);
        try{
            TextClock tc = new TextClock(Alarm.this);
            tc.setLayoutParams(clockParams);
            tc.setTextColor(getResources().getColor(R.color.white));
            tc.setGravity(Gravity.CENTER);
            clockText = (TextClock) tc;
        }
        catch(Throwable t){
            Log.e("Alarm", t.getMessage());
            DigitalClock dc = new DigitalClock(Alarm.this);
            dc.setLayoutParams(clockParams);
            dc.setTextColor(getResources().getColor(R.color.white));
            dc.setGravity(Gravity.CENTER);
            clockText = (TextView) dc;

        }
        clockLayout.addView(clockText,0);
        UtilityFunctions.assignText(Alarm.this, clockText, "fonts/Roboto-Thin.ttf");
        SimpleDateFormat sdf = new SimpleDateFormat("EEE. LLLL dd");
        String currentDateandTime = sdf.format(new Date());
        dateText.setText(currentDateandTime.toLowerCase());

        clockLayout.post(new Runnable(){
            public void run(){
                float clockHeight = (float) (clockLayout.getHeight()*.35);
                float dateHeight = (float) (clockLayout.getHeight()*.15);
                if (clockHeight > 45){
                    clockHeight = 45;
                    dateHeight = 24;
                }
                clockText.setTextSize(((float) clockHeight));
                dateText.setTextSize(((float) dateHeight));

            }
        });
        //SetupAlarm aSetUp = new SetupAlarm();
        //aSetUp.execute();
        init();

    }

    private void init(){
        db = new DatabaseHandler(this);
        Intent fromIntent = getIntent();
        Bundle bundle = fromIntent.getExtras();
        id = bundle.getInt("id");
        Alarm.ALARM_DATA = db.getAlarmData(id);
        snooze = (ImageView) findViewById(R.id.snoozeAlarmBtn);
        setupUI();
    }

    private void setupUI(){
        String message = Alarm.ALARM_DATA.getMessage();
        if(message != "" && message != null){
            TextView tv = new TextView(Alarm.this);
            tv.setText(message);
            tv.setTextSize(16);
            FrameLayout sf = (FrameLayout) findViewById(R.id.snoozFrame);
            tv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            sf.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            sf.addView(tv, tv.getMeasuredWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
            animScroll = new TranslateAnimation(sf.getMeasuredWidth(), tv.getMeasuredWidth()*-1, 0, 0);
            long durationMulti = ((sf.getMeasuredWidth()+tv.getMeasuredWidth())/sf.getMeasuredWidth());
            int duration = (int) (5000*durationMulti);
            animScroll.setDuration(duration);
            animScroll.setInterpolator(new LinearInterpolator());
            animScroll.setRepeatCount(Animation.INFINITE);
            tv.startAnimation(animScroll);
        }

        snooze.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                handler.removeCallbacks(alertLoop);
                handler.removeCallbacksAndMessages(null);
                AlarmReceiverRepeating.resetPhone(Alarm.this);
                AlarmReceiver ar = new AlarmReceiver();
                ar.setOnetimeTimer(Alarm.this, Alarm.ALARM_DATA.getId(), (long) (System.currentTimeMillis() + (1000*60*snoozeInt)),Alarm.ALARM_DATA.getId());
                Intent mainIntent = new Intent(Alarm.this,Main.class);
                mainIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(mainIntent);
                finish();
                AlarmWakeLock.releaseCpuLock();
            }
        });

        mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {

              public void onShake() {
                handler.removeCallbacks(alertLoop);
                handler.removeCallbacksAndMessages(null);
                AlarmReceiverRepeating.resetPhone(Alarm.this);
                Intent mainIntent = new Intent(Alarm.this,Main.class);
                mainIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(mainIntent);
                Notifications.setNextAlarmNotification(Alarm.this);
                AlarmReceiverRepeating.resetPhone(Alarm.this);
                finish();
                AlarmWakeLock.releaseCpuLock();
              }
            });
        AlarmReceiverRepeating.setCurrentState(Alarm.this,Alarm.ALARM_DATA.getVolume());
        handler.post(alertLoop);
    }


    //function for playing the ringer and vibrator
    public void playAlarm(){

        try {
            if(AlarmReceiverRepeating.AUDIO_MANAGER == null){
                AlarmReceiverRepeating.setCurrentState(Alarm.this, Alarm.ALARM_DATA.getVolume());
            }
            AlarmReceiverRepeating.REPEAT_COUNT ++;
            if(AlarmReceiverRepeating.REPEAT_COUNT > 1){
                AlarmReceiverRepeating.REPEAT_COUNT = 0;
                if(AlarmReceiverRepeating.CURRENT_VOLUME < AlarmReceiverRepeating.ADJUSTED_MAX_VOLUME)
                    AlarmReceiverRepeating.CURRENT_VOLUME++;
            }
            AlarmReceiverRepeating.AUDIO_MANAGER.setStreamVolume(AudioManager.STREAM_RING, AlarmReceiverRepeating.CURRENT_VOLUME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
            Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(2000);
            AlarmReceiverRepeating.AUDIO_MANAGER.setStreamVolume(AudioManager.STREAM_RING, AlarmReceiverRepeating.CURRENT_VOLUME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
            Uri alarm = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Alarm.this);
            MediaPlayer mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(Alarm.this, alarm);
            } catch (Exception e1) {
                e1.printStackTrace();
                mediaPlayer.release();
                return;
            }
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mediaPlayer.release();
                }
            });
            try {
                mediaPlayer.prepare();
            } catch (Exception e1) {
                e1.printStackTrace();
                mediaPlayer.release();
                return;
            }
            mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {

                @Override
                public void onSeekComplete(MediaPlayer mediaPlayer) {
                    mediaPlayer.stop();
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setVolume(AlarmReceiverRepeating.CURRENT_VOLUME, AlarmReceiverRepeating.CURRENT_VOLUME);
            mediaPlayer.start();
         }
        catch (Throwable t) {
            Log.i("ALARM", "ERROR PLAYING ALARM");
            Toast.makeText(this, "there was a problem in the playAlarm function", Toast.LENGTH_SHORT).show();
        }
    }//end playAlarm



    @Override
    protected void onStop(){
        super.onStop();
        Log.i("ALARM", "on stop ran");
        handler.removeCallbacks(alertLoop);
        handler.removeCallbacksAndMessages(null);
        Notifications.setNextAlarmNotification(Alarm.this);
        AlarmReceiverRepeating.resetPhone(this);
        finish();
        AlarmWakeLock.releaseCpuLock();

    }
    @Override
    protected void onStart(){
        super.onStart();

    }
    @Override
    protected void onPause(){
        super.onPause();
        Log.i("ALARM", "on pause ran");

    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        turnOnScreen();
        Log.i("ALARM", "on resume ran");
        mSensorManager.registerListener(mSensorListener,
        mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_UI);
    }
    private void turnOnScreen(){
        final Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                + WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    }

    private class SetupAlarm extends AsyncTask<Void, Void, Void> {

          protected Void doInBackground(Void... urls) {
             init();
             return null;
          }

          protected void onPostExecute(Void args) {
              setupUI();
          }
        }

}

I have figured out what was going on. 我已经知道发生了什么事。 It was not a wakelock issue. 这不是一个唤醒问题。 The issue is that, for whatever reason the onStop function was (is still) being called when the phone wakes from sleeping. 问题是,无论出于何种原因,当手机从睡眠状态唤醒时,onStop函数仍被调用。 Since I had a finish() function running it was killing the activity. 因为我有一个finish()函数正在运行,所以它杀死了活动。 I placed the code in the onStop override so that the alarm will stop if the user hits the back or home button so I will need to address that unless someone can enlighten me on why the onStop is called an how to avoid it. 我将代码放置在onStop替代中,以便在用户单击后退或主页按钮时警报将停止,因此除非有人能启发我为什么将onStop称为如何避免它,否则我将需要解决此问题。 Thanks 谢谢

You will need to include this permission in your manifest: 您需要在清单中包括此权限:
uses-permission android:name="android.permission.WAKE_LOCK" or see this it might helpful to you How do I prevent an Android device from going to sleep programmatically? Uses-permission android:name =“ android.permission.WAKE_LOCK”或看到它可能对您有帮助如何防止Android设备以编程方式进入睡眠状态?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当电话进入睡眠状态时,活动OnCreate被呼叫 - Activity OnCreate called when phone goes to sleep Android在进入睡眠状态时会更改活动 - Android changes activity when it goes to sleep 手机睡眠时android显示活动 - android show activity when phone sleep android当手机进入睡眠状态时如何处理android计时器 - android how to deal with android timer when phone goes to sleep 手机进入睡眠状态时,Android File上传服务会停止吗? - Android File upload service stops when phone goes to sleep? 当手机在android中进入睡眠模式时服务停止 - Service get stopped when mobile goes to sleep mode in android Android机会通信与电源管理(电话进入睡眠状态时会发生什么情况) - Android opportunistic communication vs power management (what happens to service when phone goes to sleep) 防止位置管理器在手机进入睡眠状态时停止位置更新 Xamarin.Android - Prevent Location Manager from stopping location updates when phone goes to sleep Xamarin.Android 当手机进入睡眠状态并保存历史记录时完成应用程序 - Finish app when phone goes to sleep and save history 当手机进入睡眠/待机模式时,活动/服务会发生什么? - What happens to Activities/Services when phone goes to sleep/standby mode?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM