[Android] Receive intent on Broadcast Reciever

What is Broadcast Receiver?

--BroadcastReceiver is a mechanism to receive broadcast intents. --In addition to events broadcast on the Android system side of the OS (screen ON / OFF, etc.), you can also generate your own intent and broadcast it with your own application.

What is an intent?

--Intent is each function in the application. For example, a mechanism that bridges applications, applications and widgets, and applications and systems. --You can use the intent without using BroadcastReciever, for example, you can make a phone call or activate the camera. --BroadcastReciever can detect intents that occur when you install an app, for example. For example ... --Detects screen ON / OFF --Detect the battery status --Detects app installation --Detecting vibration, etc.

Let's use

I started the service from the activity → I tried to register the receiver with the service

MyReceiver.java


public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
               Log.d("registerReceiver: ", "ON");
            }
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                Log.d("registerReceiver: ", "OFF");
            }
        }
    }
}

MyActivity.java


public class MyActivity extends Activity {
 
    Button startButton;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startButton = (Button)findViewById(R.id.start_button);
        startButton.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this(), MyService.class));
            } else {
                startService(new Intent(this(), MyService.class));
            }
        }
    }
}

MyService.java


public class MyService extends Service {

    private MyReceiver mReceiver;
    private IntentFilter mIntentFilter;
   
    @Override
    public void onCreate() {
        super.onCreate();
        //Perform Receiver registration
        registerScreenReceiver();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //Release Receiver
        unregisterReceiver(mReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startInForeground();
        return START_STICKY;
    }

    //Register receiver
    private void registerScreenReceiver() {
        mReceiver = new MyReceiver();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, mIntentFilter);
    }

    //Generate notifications to alive the service
    private void startInForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("test notification")
                .setTicker(getResources().getString(R.string.app_name))
                .setContentIntent(pendingIntent);
        Notification notification = builder.build();

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID
                    , NOTIFICATION_CHANNEL_NAME
                    , NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(NOTIFICATION_CHANNEL_DESC);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
        startForeground(NOTIFICATION_ID, notification);
    }
}

Commentary

--In onReceive of MyReceiver, process to output log when intent.getAction () matches the registered intentFilter action --A button is installed in MyActivity. A simple structure that starts a service when a button is pressed --Receiver is registered in MyService. startInForeground is for ForegroundService and implemented for the time being (don't worry too much) --If you turn the screen on / off while the service is running, a log will be output each time.

Remarks

――I often look at the most lifelogs and healthcare apps, so when I was wondering how the data was aggregated, I felt that there were many patterns using intent, so I investigated it. ――There are so many intents other than those introduced this time, so some apps may be useful ...

Recommended Posts

[Android] Receive intent on Broadcast Reciever
[Android] Notes on xml
Customize list view on Android
Multipart transmission library on Android
Use serial communication on Android
ROS app development on Android
Android development ~ Screen transition (intent) ~
Use native code on Android