Capture the moment the mobile screen was lit and when it was deleted

Asked

Viewed 112 times

1

Hello ! I’m building a project similar to an alarm clock but I’m having a hard time trying to use the broadcastreceiver class. Problem: I want to capture the date and the exact time that the mobile screen was lit, IE, if the user just press the button to turn on the screen and see if there is notification, I would like to capture this moment to later insert in the database. In the same way also want to capture the moment when the screen is erased, following practically the same idea in relation to the screen being turned on, when being erased I want to take the time of the system to later save in the database.

But so far I managed to use the broadcastReceiver just to make the phone vibrate, in the example below I’m trying to turn on and unlock the screen, what I really want is to capture this direct moment of the user, but I’m not able to even know where to start:

Broadcastactivity

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    //EXEMPLO PARA FAZER O CELULAR VIBRAR
    /*Toast.makeText(context, "Não entre em panico amigo!", Toast.LENGTH_SHORT).show();

    //Vibrando o celular
    Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(2000);*/

    //EXEMPLO PARA FAZER A TELA SER LIGADA E DESTRAVADA
    Intent intentTela = new Intent(context, MainActivity.class);
    intentTela.putExtra(MainActivity.EXTRA_LIGAR_E_DESTRAVAR_TELA, true);
    context.startActivity(intentTela);

}
}

Sample screen:

public class MainActivity extends AppCompatActivity {
//ATRIBUTOS
EditText etTime;
Button btOk;
public static final String EXTRA_LIGAR_E_DESTRAVAR_TELA = ChamadaActivity.class.getPackage().getName() + ".LIGAR_E_DESTRAVAR_TELA";


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

    if (true == getIntent().getBooleanExtra(EXTRA_LIGAR_E_DESTRAVAR_TELA, false)){
        //Combinando duas flags
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    }

}

public void configAlarm(View view){
    etTime = findViewById(R.id.time);
    int tempo = Integer.parseInt(etTime.getText().toString());

    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 1, intent, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (tempo * 1000), pendingIntent);

    Toast.makeText(this, "Alarm marcado para " + tempo + " segundos", Toast.LENGTH_LONG).show();


}
}

xml main:

<?xml version="1.0" encoding="utf-8"?>

<EditText
    android:id="@+id/time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="32dp"
    android:text="Button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/time"
    android:onClick="configAlarm"/>
   </android.support.constraint.ConstraintLayout>

Manifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.VIBRATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name=".MyBroadcastReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
        </intent-filter>
    </receiver>

    <activity android:name=".ChamadaActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Thank you for your attention!

2 answers

1


You must create and register a Broadcastreceiver that listens to events Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON.

Example:

public class ScreenOnOffReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {


        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

            //A tela foi apagada

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

            //A tela foi acesa

        }

    }

}
  • I changed the code as you mentioned but sorry beautiful ignorance but now I do not know how to call the broadcast class, the way it was left it just does nothing, Could you give me an example of Activity + the broadcast call when the screen is turned on or off by calling the Vibrator class for example? Or some site where I can find more information to help me get better ?

  • https://androidexample.com/Screen_Wake_Sleep_Event_Listner_Service_-_Android_example/index.php? view=article_discription&aid=91#

0

Thank you so much for your help, and I finally got what I wanted, capturing the SCREEN_ON and SCREEN_OFF event and so I’d like to share the full code so I can help other people who need it, follow the full code of an app that will vibrate when capturing both events: In the Manifest add the following permissions: Androidmanifest.xml

    <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

and at the end of the TAG application after the Activity tag that will receive the events add the following code:

<service android:name="com.nomedopacote.LockService">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </service>

the following Activitys code: Mainactivity.class

public class MainActivity extends AppCompatActivity {

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

    //starting the service Class
    startService(new Intent(getApplicationContext(), LockService.class));

}
}

In the Service class that will call broadcast

Lockservice.class

public class LockService extends Service {

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

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);

    //Calling the BroadCast
    final BroadcastReceiver mReceiver = new ScreenReceiver();
    registerReceiver(mReceiver, filter);

    return super.onStartCommand(intent, flags, startId);
}

//AINDA NÃO SEI PARA QUE SERVE
public class LocalBinder extends Binder{
    LockService getService(){
        return LockService.this;
    }
}

}

Screenreceiver.class - where the magic rolls

public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

@Override
public void onReceive(Context context, Intent intent) {
    Log.e("test", "onReceive Broadcast");

    SimpleDateFormat Dformat = new SimpleDateFormat("dd-MM-yyyy-HH:mm:ss");
    Date date = new Date();

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    Date data_atual = cal.getTime();
    String sysdate  = Dformat.format(data_atual);

    //Validating screen status
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
        //Vibrate test
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);

        wasScreenOn = false;
        Log.e("hora OFF", sysdate);

    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
        //Vibrate test
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(1000);

        wasScreenOn = true;
        Log.e("hora ON", sysdate);

    } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
        Toast.makeText(context, "USER PRESENT", Toast.LENGTH_SHORT).show();
    }

}
}

The inspiring code was taken from the following link: http://usefulcodeforandroid.blogspot.com.br/2013/07/detect-android-actionscreenoff.html I thank the Stackoverflow community for their help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.