Creating a Service
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
@Override
public void onCreate() {
// TODO: Actions to perform when service is created.
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Replace with service binding implementation.
return null;
}
}
Starting a Service
// Implicitly start a Service
Intent myIntent = new Intent(MyService.ORDER_PIZZA);
myIntent.putExtra("TOPPING", "Margherita");
startService(myIntent);
// Explicitly start a Service
startService(new Intent(this, MyService.class));
Stopping a Service
ComponentName service = startService(new Intent(this, BaseballWat
// Stop a service using the service name.
stopService(new Intent(this, service.getClass()));
// Stop a service explicitly.
try {
Class serviceClass = Class.forName(service.getClassName());
stopService(new Intent(this, serviceClass));
} catch (ClassNotFoundException e) {}
Binding Activities to Services
private final IBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
The connection between the Service and Activity is represented as a ServiceConnection.
You’ll need to implement a new ServiceConnection, overriding the onServiceConnected and
onServiceDisconnected methods to get a reference to the Service instance once a connection has been
established
// Reference to the service
private MyService serviceBinder;
// Handles the connection between the service and activity
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// Called when the connection is made.
serviceBinder = ((MyService.MyBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// Received when the service unexpectedly disconnects.
serviceBinder = null;
}
};
Intent bindIntent = new Intent(MyActivity.this, MyService.class);
bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
Displaying a Toast
Context context = getApplicationContext();
String msg = "To health and happiness!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, msg, duration);
toast.show();
Customizing a Toast
Context context = getApplicationContext();
String msg = "To the bride and groom!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, msg, duration);
int offsetX = 0;
int offsetY = 0;
toast.setGravity(Gravity.BOTTOM, offsetX, offsetY);
toast.show();
toast.setView(ll);
toast.show();
Using the Notification Manager
String svcName = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager;
notificationManager = (NotificationManager)getSystemService(svcName);
Creating a Notification
int icon = R.drawable.icon;
// Text to display in the status bar when the notification is launched
String tickerText = "Notification";
// The extended status bar orders notification in time order
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Configuring the Extended Status Notification Display
You can configure the appearance of the Notification within the extended status window in two ways:
1. Use the setLatestEventInfo method to update the details displayed in the standard extended
status Notification display.
2. Set the contentView and contentIntent properties to assign a custom UI for the extended
status display using a Remote View.
Setting Notification values
Context context = getApplicationContext();
// Text to display in the extended status window
String expandedText = "Extended status text";
// Title for the expanded status
String expandedTitle = "Notification Title";
// Intent to launch an activity when the extended text is clicked
Intent intent = new Intent(this, MyActivity.class);
PendingIntent launchIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context,expandedTitle,expandedText,launchIntent);
Applying a custom layout to the Notification status window
Notification notification = new Notification(R.drawable.icon,
"Custom Content",
System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(this.getPackageName(),
R.layout.my_status_window_layout);
Intent intent = new Intent(this, MyActivity.class);
PendingIntent.getActivity(this, 0, intent, 0));
notification.contentIntent = pendingIntent;
notification.contentView.setImageViewResource(R.id.status_icon,
R.drawable.icon);
notification.contentView.setTextViewText(R.id.status_text,
"Current Progress:");
notification.contentView.setProgressBar(R.id.status_progress,
100, 50, false);
Triggering a Notification
int notificationRef = 1;
notificationManager.notify(notificationRef, notification);
notificationManager.cancel(notificationRef);
Using the Defaults
Using the defaults property you can combine:
➤ Notification.DEFAULT_LIGHTS
➤ Notification.DEFAULT_SOUND
➤ Notification.DEFAULT_VIBRATE
notification.defaults = Notification.DEFAULT_SOUND |
Notification.DEFAULT_VIBRATE;
Uri ringURI =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.sound = ringURI;
<uses-permission android:name="android.permission.VIBRATE"/>
long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 };
notification.vibrate = vibrate;
The following code snippet shows how to turn on the red device LED:
notification.ledARGB = Color.RED;
notification.ledOffMS = 0;
notification.ledOnMS = 1;
notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;
USING ALARMS
AlarmManager alarms =
(AlarmManager)getSystemService(Context.ALARM_SERVICE);
RTC_WAKEUP Wake the device from sleep to fire the Pending Intent at the clock time specified.
RTC Fire the Pending Intent at the time specified, but do not wake the device.
ELAPSED_REALTIME Fire the Pending Intent based on the amount of time elapsed since the
device was booted, but do not wake the device. The elapsed time includes any period of time
the device was asleep. Note that the time elapsed is calculated based on when the device was
last booted.
ELAPSED_REALTIME_WAKEUP After a specified length of time has passed since device boot,
wake the device from sleep and fire the Pending Intent.
Creating an Alarm
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long timeOrLengthofWait = 10000;
String ALARM_ACTION = "ALARM_ACTION";
Intent intentToFire = new Intent(ALARM_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intentToFire, 0);
alarms.set(alarmType, timeOrLengthofWait, pendingIntent);
alarms.cancel(pendingIntent);
Setting and canceling an Alarm
AlarmManager alarms =
(AlarmManager)getSystemService(Context.ALARM_SERVICE);
String MY_RTC_ALARM = "MY_RTC_ALARM";
String ALARM_ACTION = "MY_ELAPSED_ALARM";
PendingIntent rtcIntent =
PendingIntent.getBroadcast(this, 0,
new Intent(MY_RTC_ALARM), 1);
PendingIntent elapsedIntent =
PendingIntent.getBroadcast(this, 0,
new Intent(ALARM_ACTION), 1);
// Wakeup and fire intent in 5 hours.
Date t = new Date();
t.setTime(java.lang.System.currentTimeMillis() + 60*1000*5);
alarms.set(AlarmManager.RTC_WAKEUP, t.getTime(), rtcIntent);
// Fire intent in 30 mins if already awake.
alarms.set(AlarmManager.ELAPSED_REALTIME, 30*60*1000, elapsedIntent);
// Cancel the first alarm.
alarms.cancel(rtcIntent);
Setting Repeating Alarms
To set a repeating alarm, use the setRepeating or setInexactRepeating method on the Alarm Manager
INTERVAL_FIFTEEN_MINUTES
INTERVAL_HALF_HOUR
INTERVAL_HOUR
INTERVAL_HALF_DAY
INTERVAL_DAY
// Fire an intent exactly every hour if already awake.
alarms.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
60*60*1000, 60*60*1000, elapsedIntent);
// Wakeup and fire an alarm about every hour
alarms.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
60*60*1000, AlarmManager.INTERVAL_DAY,
elapsedIntent);