Capture the moment the cell phone screen was turned on and when it was deleted

1

Hello!    I am building a project similar to an alarm clock but I am having some difficulties trying to use the broadcastreceiver class. Problem:     I want to capture the date and the exact time that the cell phone screen was lit, that is, if the user just pressed the button to light the screen and see if it has notification, I would like to capture that moment and later insert it into the database. Likewise, I also want to capture the moment when the screen is deleted, practically following the same idea regarding the screen being connected, when it is deleted I want to take the system time to later save to the database.

But so far I've been able to use 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 moment from the user, but I can not 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!

    
asked by anonymous 31.03.2018 / 15:49

2 answers

1

You should create and register a BroadcastReceiver that listens for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON events.

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

        }

    }

}
    
31.03.2018 / 16:07
0

Thanks a lot for the help, and finally got what I wanted, capture the SCREEN_ON and SCREEN_OFF event and I would like to share the complete code so that you can help others who need it, follow the complete code of an app that will vibrate when you capture both events: In 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>

follows Activity 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 the 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 has been removed from the following link: link Thanks to the StackOverflow community for help!

    
04.04.2018 / 02:07