In this tutorial, we will learn how you can update the user interface whenver the system minute changes, using a BroadcastReceiver in Android Studio. You can use this, if you want to do something once per minute, exactly when the seconds reach 60.
In MainActivity.java class file write these lines of codes:-
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView counterText;
private BroadcastReceiver minuteUpdateReceiver;
private int counter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterText = (TextView) findViewById(R.id.counter_text);
}
public void startMinuteUpdater() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
minuteUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
counter++;
counterText.setText("" + counter);
}
};
registerReceiver(minuteUpdateReceiver, intentFilter);
}
@Override
protected void onResume() {
super.onResume();
startMinuteUpdater();
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(minuteUpdateReceiver);
}
}
In activity_main.xml write these lines of codes:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.application.exampleapp.MainActivity">
<TextView
android:id="@+id/counter_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="60sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Comments