Broadcast Receiver

Listens out for designated System Broadcast Intents via an IntentFilter (declared in the AndroidManifest.xml) so that your app can respond to changes in the system. It can be triggered even when the app is not running. There are two types:

  • Static (Manifest-declared) – triggered whenever the broadcast intent occurs, even if the app is offline
  • Dynamic (Context-registered) – tied to the app’s lifecycle

It is preferred that dynamic broadcast receivers or job scheduling is used over static broadcast receivers, as abuse of statics could result in multiple apps responding to a system event. For this reason, some broadcast intents will not let you create a corresponding static receiver. These intents have FLAG_RECEIVER_REGISTERED_ONLY flag set.

For a static broadcast receiver you will register the receiver in the AndroidManifest.xml:

<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>

Then implement the receiver like so:

public class MyBroadcastReceiver extends BroadcastReceiver {
        private static final String TAG = "MyBroadcastReceiver";
        @Override
        public void onReceive(Context context, Intent intent) {
            // Do something
        }
    }

For a dynamic receiver you register and un-register the receiver in the onResume() and onPause method overrides respectively:

public class MyBroadcastReceiver extends BroadcastReceiver {
        private static final String TAG = "MyBroadcastReceiver";
        BroadcastReceiver br = new MyBroadcastReceiver();
        @Override
        public void onReceive(Context context, Intent intent) {
            //Do something
        }
    
    @Override
    protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    this.registerReceiver(br, filter);
    @Override
    protected void onPause() {
    super.onPause();
    this.unRegisterReceiver(br);
    }
}

The potential issue with the above example of a Dynamic receiver is that it will only check for changes once onResume has initiated, and so if the system status changes while the app is not visible, it may hold the incorrect status when the app starts. Adding the code to the onCreate and onDestroy methods would result in unnecessary actions occurring in the background when the app is not visible. To overcome this, check for the current system status on onResume in addition to registering the broadcast receiver. See an example here.

ud851-Exercises-student\Lesson10-Hydration-Reminder\T10.05

Intent Service

A Service which runs off a completely separate thread to the main. All IntentService requests are handled on a single background thread and are issued in order. Therefore IntentServices are good for tasks that need to happen in order.

Services must be registered in the AndroidManifest.xml:

        <service
            android:name=".sync.myIntentService"
            android:exported="false"
            ></service>

An Intent Service can be started in a very similar way to an Activity:

Intent myIntent = new Intent(this, myIntentService.class);
startService(myIntent);

Extra data can be attached to the Intent when starting the Service, as with Activities:

Intent myIntent = new Intent(this, myIntentService.class);
myIntent.setAction("Some specific action");
startService(myIntent);

To create the Service, extend IntentService. Override the onHandle Intent method to tell it what to do in the background:

public class MyIntentService extends IntentService {

    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction(); //Add this line if extra data attached
        //Do background work here
    }
}

The IntentService will then stop itself when it is finished.

ud851-Exercises-student\Lesson10-Hydration-Reminder\T10.01

Request Permission

How to request a permission for your app

In the AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.android.datafrominternet">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.example.android.datafrominternet.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

Adding An Activity, Up Navigation, Accessing With Explicit Intents, Passing Data

How to add an Activity to your app and navigate to it using an explicit Intent.

Create an empty Activity through the IDE. IDE will automatically add the essential code to the AndroidManifests.xml file. Make any desirable additions.

        <activity android:name="com.example.android.explicitintent.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="com.example.android.explicitintent.ChildActivity"
            android:label="@string/action_settings" // Name at top of screen for Activity
            android:parentActivityName=".MainActivity"> // Make sure the back arrow functions properly by declaring parent activity
            <meta-data // To support Android 4.0 and lower
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>

In new Activity, enable Up navigation.

getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Or getActionBar() on older versions before support library

In Parent Activity, set up an explicit Intent.

        private Button doSomethingCoolButton = (Button) findViewById(R.id.b_do_something_cool);
        private String text = "Send me!"; // Text to be passed to new Activity
        mDoSomethingCoolButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = MainActivity.this;

                /* This is the class that we want to start (and open) when the button is clicked. */
                Class destinationActivity = ChildActivity.class;

                /*
                 * Here, we create the Intent that will start the Activity we specified above in
                 * the destinationActivity variable. The constructor for an Intent also requires a
                 * context, which we stored in the variable named "context".
                 */
                Intent startChildActivityIntent = new Intent(context, destinationActivity);

                startChildActivityIntent.putExtra(Intent.EXTRA_TEXT, text); // Add text as extra data

                /*
                 * Once the Intent has been created, we can use Activity's method, "startActivity"
                 * to start the ChildActivity.
                 */
                startActivity(startChildActivityIntent);
            }
        });

In new Activity, access and use the extra data.

        mDisplayText = (TextView) findViewById(R.id.tv_display); // Find a TextView

        // Use the getIntent method to store the Intent that started this Activity in a variable
        Intent intent = getIntent();

        // Check if this Intent has the extra text we passed from MainActivity
        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            String enteredText = intent.getStringExtra(Intent.EXTRA_TEXT);
            mDisplayText.setText(enteredText); // Assign text to TextView
        }