"> ">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

System broadcasts and services. System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE.

Similar presentations


Presentation on theme: "System broadcasts and services. System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE."— Presentation transcript:

1 System broadcasts and services

2 System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE IVE_BOOT_COMPLETED permission. Intent.ACTION_POWER_CONNECTEDPower got connected to the device. Intent.ACTION_POWER_DISCONNECT ED Power got disconnected to the device. Intent.ACTION_BATTERY_LOWTriggered on low battery. Typically used to reduce activities in your app which consume power. Intent.ACTION_BATTERY_OKAYBattery status good again.

3 Registration for the BOOT_COMPLETED <receiver android:name="MyStartServiceReceiver" >

4 The receiver would start the service import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // assumes WordService is a registered service Intent intent = new Intent(context, WordService.class); context.startService(intent); } }

5 Tip If your application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. In this case register it for the android.intent.action.ACTION_EXTERNAL_APPLI CATIONS_AVAILABLE event.

6 Exercise: Define receiver for phone changes Implement receiver  Register your receiver in your AndroidManifest.xml

7 <action android:name = "android.intent.action.PHONE_STATE" >

8 Implements on an Activity @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { String state = extras.getString(TelephonyManager.EXTRA_STATE); Log.w("MY_DEBUG_TAG", state); if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { String phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBE R); Log.w("MY_DEBUG_TAG", phoneNumber); }

9 Validate implementations Install your application and simulate a phone call via the DDMS perspective in Eclipse. Validate that your receiver is called and logs a message to the LogCat view.

10 Exercise: System services and receiver Implement project  Create broadcast receiver class  public class MyBroadcastReceiver extends BroadcastReceiver { }

11 @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Don't panik but your time is up!!!!.“,Toast.LENGTH_LONG).show(); // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVIC E); vibrator.vibrate(2000); }

12 Register this class as a broadcast receiver in AndroidManifest.xml

13 Change the code of your AlarmActivity class public void startAlert(View view) { EditText text = (EditText) findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext( ), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); }

14 Validate implementation Run your application on the device. Set your time and start the alarm. After the defined number of seconds a Toast should be displayed. Keep in mind that the vibration alarm does not work on the Android emulator.

15 Defining custom events and receivers Registering broadcast receiver for custom events  You can register a receiver for your custom actions.

16 Sending broadcast intents The sendBroadcast() allows you to send intents to your registered receivers. Intent intent = new Intent(); intent.setAction("de.vogella.android.mybroadcast"); sendBroadcast(intent); You cannot trigger system broadcasts events. The Android system will prevent this.

17 Tip The receivers are called asynchronous, i.e., the sendBroadcast() method return immediately and does not wait until the receivers have executed.

18 . Local broadcast events with LocalBroadcastManager The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don't leave your application.

19 @Override public void onResume() { super.onResume(); // Register mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this).registerR eceiver(mMessageReceiver, new IntentFilter("my- event")); }

20 Handler for received Intents for the "my-event" event private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getStringExtra("message"); Log.d("receiver", "Got message: " + message); } };

21 @Override protected void onPause() { // Unregister since the activity is not visible LocalBroadcastManager.getInstance(this).unregiste rReceiver(mMessageReceiver); super.onPause();}

22 // This method is assigned to button in the layout// via the onClick property public void onClick(View view) { sendMessage(); } // Send an Intent with an action named "my-event". private void sendMessage() { Intent intent = new Intent("my-event"); // add data intent.putExtra("message", "data"); LocalBroadcastManager.getInstance(this).sendBroadc ast(intent); }

23 Dynamic broadcast receiver registration Dynamically registered receiver  Receiver can be registered via the Android manifest file.  You can also register and unregister a receiver at runtime via the Context.registerReceiver() and Context.unregisterReceiver() m ethods.

24 Warning Do not forget to unregister a dynamically registered receiver by using Context.unregisterReceiver() method. If you forget this, the Android system reports a leaked broadcast receiver error. For instance, if you registered a receive in onResume() methods of your activity, you should unregister it in the onPause() method.

25 You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file. ComponentName receiver = new ComponentName(context, myReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABL ED, PackageManager.DONT_KILL_APP);

26 Sticky (broadcast) intents An intent to trigger a receiver (broadcast intent) is not available anymore after it was sent and processed by the system. If you use the sendStickyBroadcast(Intent) method, the corresponding intent is sticky, meaning the intent you are sending stays around after the broadcast is complete. The Android system uses sticky broadcast for certain system information. For example, the battery status is send as sticky intent and can get received at any time. The following example demonstrates that.

27 // Register for the battery changed event IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); // Intent is sticky so using null as receiver works fine // return value contains the status Intent batteryStatus = this.registerReceiver(null, filter); // Are we charging / charged? int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_ST ATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;

28 boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL; // How are we charging? int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_ PLUGGED, -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

29 You can retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). This also works for a null BroadcastReceiver. In all other ways, this behaves just as sendBroadcast(Intent). Sticky broadcast intents typically require special permissions.


Download ppt "System broadcasts and services. System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE."

Similar presentations


Ads by Google