Belajar Android Broadcast Receiver

Sekarang kita coba belajar android tentang broadcaset reciver.

1. Buat project dengan nama LearnBroadcastReceiver dengan company domain net.agusharyanto

next terus sampai pada plihan Activity pilih Empty Activity klik next sampai finish.

2.Mari kita siapkan layoutnya, untuk itu edit file activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.agusharyanto.learnbroadcastreceiver.MainActivity">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Broadcast Receiver"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hidup Android Developer "
        android:textColor="#ff87ff09"
        android:textSize="30dp"
        android:layout_above="@+id/imageButton"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp" />
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:src="@mipmap/ic_launcher"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="Broadcast Intent"
        android:onClick="broadcastIntent"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

3. Edit Class MainActivity.java lalu ketikan kode berikut

package net.agusharyanto.learnbroadcastreceiver;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    // broadcast a custom intent.
    public void broadcastIntent(View view){
        Intent intent = new Intent();
        intent.setAction("net.agusharyanto.CUSTOM_INTENT");
        sendBroadcast(intent);
    }
}

4. Buat BroadcastReceiver beri nama MyReceiver

package net.agusharyanto.learnbroadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
    }
}

5.  Pada AndroidManifest.xml setelah tag Activity tambahkan receiver untuk menangkap kejadian.

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="net.agusharyanto.CUSTOM_INTENT"></action>
    </intent-filter>
</receiver>

6. Sekarang mari kita run projectnya. Lalu klik button Broadcast Intent. Maka aka muncul Toast “Intent Detected”.

Sekarang apakah kita bisa juga menangkap kejadian dari android misalnya pada saat Booting selesai.

Tenang saja android sudah menyediakannya

7. Buat BroadCastReceiver untuk menangkap event Boot Complete beri nama dengan BootReceiver lalu ketikan kode berikut.

package net.agusharyanto.learnbroadcastreceiver;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class BootReceiver extends BroadcastReceiver {
    public BootReceiver() {
    }
// perintah untuk trigger event BOOT_COMPLETED
// ./adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -p net.agusharyanto.learnbroadcastreceiver
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("TAG","Booting Completeee");
        Toast.makeText(context, "Booting Completed", Toast.LENGTH_LONG).show();
        addNotification(context);
    }
    private void addNotification(Context context) {
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("Notifications Example")
                        .setContentText("This is a test notification");
        Intent notificationIntent = new Intent(context, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        // Add as notification
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
    }
}

8. Jangan lupa untuk menangkap event ini kita harus menambahkan permissionnya dan mendaftarkan receivernya. Jadi versi lengkap AndroidManifest.xml nya adalh seperti dibawah ini

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.agusharyanto.learnbroadcastreceiver">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".MyReceiver">
            <intent-filter>
                <action android:name="net.agusharyanto.CUSTOM_INTENT"></action>
            </intent-filter>
        </receiver>
        <receiver
            android:name="net.agusharyanto.learnbroadcastreceiver.BootReceiver"
            >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

9. Mari kita run projectnya. Tutup aplikasinya lalu kita matikan hp android lalu nyalakan. Perhatikan apakah notificationnya terlihat setelah boot selesai.

Bertambah lagi bekal kita untuk membuat aplikasi android yang lebih oke.
Semoga bermanfaat
Salam hangat
Developer Android

Agus Haryanto

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>