[embedyt] https://www.youtube.com/watch?v=8FJ3oOpHszc[/embedyt]
ExampleBroadcastReceiver.javaAndroidManifest.xml
package com.codinginflow.broadcastexample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.widget.Toast; public class ExampleBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Toast.makeText(context, "Boot completed", Toast.LENGTH_SHORT).show(); } if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { Toast.makeText(context, "Connectivity changed", Toast.LENGTH_SHORT).show(); } } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.codinginflow.broadcastexample"> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <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=".ExampleBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest>