Alarm
Alarm
Faculty of Engineering
By
Aug. 2013
1
Services, AlarmManager,
Notifications and Widgets
Android Services
Service
A service is a component which runs in the background, without direct interaction with
the user. The Android platform provides and runs predefined system services and every
Android application can use them.
The Android platform provides pre-defined services, usually exposed via a specific
Manager class. Access to them can be gained via the getSystemService() method.
Defining your own services allows you to design very responsive applications. You can
fetch the application via a service and once the application is started by the user, it can
present fresh data to the user.
<service android:name="MyService"></service>
2
Service Class
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Starting services
An Android component (service, receiver, activity) can start and trigger a service via the
startService(intent) method. This method call starts the service if it is not running.
3
Stopping a service
- You stop a service via the stopService() method. No matter how frequently you
started the service with startService(intent) a call to stopService() stops it.
- A service can stop itself by calling the stopSelf() method.
Service Class
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this,intent.getStringExtra("pass"),Toast.LENGTH_SHORT)
.show();
4
return START_Not_STICKY; }}
Activity Class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
i.putExtra("pass", editText.getText().toString());
startService(i);
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(i);
}
});
<< Project aim: pass entered data & show it at the toast msg when service is started >>
5
Main.xml
<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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text_view_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#FF0000"
android:textSize="20sp"
android:text="Android Simple Service Example" />
<Button
android:id="@+id/stop_service"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Stop Service"
android:layout_below="@+id/start_service"
/>
<Button
android:id="@+id/start_service"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/text_view_header"
android:layout_marginTop="144dp"
android:gravity="center_horizontal"
android:text="Start Service"
/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text_view_header"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:ems="10" />
</RelativeLayout>
6
AndroidManifest.xml
Add this line
For correct scheduling of the Service use the AlarmManager class. The following code
demonstrates how to do this.
// to stop:
timer.cancel();
7
AlarmManager
Many times we want some task to be performed at some later time in future.
For Example: In SMS Scheduler we want a SMS to be sent at some later time, or Task
Reminder in which we want to be reminded about a task at a particular time, to
implement all these things we use AlarmManager class.
<< Project Work: show toast msg “welcome “every 10sec. when service is stated >>
Service Class
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this,"Welcome :)", Toast.LENGTH_SHORT).show();
return START_NOT_STICKY; // no automatic restart
}
8
Activity Class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar cal = Calendar.getInstance();
startService(i);
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
alarm.cancel(pintent);
stopService(i);
}
});
}
}
9
General use of Alarm Manager
One-Shot Alarm
To create a new one-shot Alarm, use the set method and specify an alarm type, a
trigger time, and a Pending Intent to fire when the Alarm triggers. If the trigger time
you specify for the Alarm occurs in the past, the Alarm will be triggered immediately.
There are four alarm types that are available, we will use:
RTC_WAKEUP — wakes the device from sleep to fire the Pending Intent at the clock
time specified.
To set a repeating alarm, use the setRepeating method on the Alarm Manager.
- This methods supports an alarm type, an initial trigger time, and a Pending Intent
to fire when the alarm triggers (as described in the previous section).
- Use setRepeating when you need fine-grained control over the exact interval of
your repeating alarm. The interval value passed in to this method lets you specify
an exact interval for your alarm, down to the millisecond.
10
Example
Layout: - two EditText with whom you can set the delay time for the first alarm and the delay
between alarms in repeating mode
- three Button: one to start a single alarm, one to start repeting alarms and one to stop alarms
in repeating mode
Code:
- BroadcastReceiver: it receives the intent sent as alarms an send a message to an handler
- Handler: it receives a message and if it's an alarm it refresh "Received Alarms" and shows a
toast
- AlarmManager: you ask to it the type of alarm that you desire (one shot or repeating) or
cancel an active repeating alarm
11
public class AlarmManagerTutorialActivity extends Activity {
private static final String ALARM_REFRESH_ACTION =
"it.trento.alchemiasoft.casagranda.simone.alarmmanagertutorial.ALARM_REFRESH_ACTION";
private static final int ALARM_CODE = 20;
private static final long DEFAULT_START_DELAY = 1000;
private static final long DEFAULT_INTERVAL_DELAY = 3000;
private BroadcastReceiver alarmReceiver;
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
private int alarmCounted;
// UI references
private EditText millsStartEditText, millsIntervalEditText, alarmsReceived;
13
Notifications
Notification Manager
Android allows putting notification into the title bar of your application. The user can
expand the notification bar and by selecting the notification the user can trigger another
activity.
Setting up Notifications
Pending Intent
A PendingIntent is a token that you give to another application (e.g. Notification
Manager, Alarm Manager or other 3rd party applications), which allows this
other application to use the permissions of your application to execute a
predefined piece of code.
14
// Text to display in the extended status window
String expandedText = "Extended text";
PendingIntentlaunchIntent=PendingIntent.getActivity(this,0,intent,0);
int notificationID=1;
notificationManager.notify(notificationID, notification);
Canceling Notifications
The user can dismiss all notification or if you set your notification to auto-cancel it is also
removed once the user selects it.
You can also call the cancel() for a specific notification ID on the NotificationManager.
The cancelAll() method call removes all of the notifications you previously issued.
notificationManager.cancel(notificationID);
15
Example
When service
started, it
appears
When expanded
16
ServiceLauncher Class
start.setOnClickListener(startListener);
stop.setOnClickListener(stopListener);
17
NotifyService Class
public class NotifyService extends Service {
int notificationID=1;
private Long counter = 0L;
private NotificationManager nm;
private Timer timer = new Timer();
private final Calendar time = Calendar.getInstance();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Toast.makeText(this,"Service created at " + time.getTime(),
Toast.LENGTH_LONG).show();
showNotification();
incrementCounter();
@Override
public void onDestroy() {
super.onDestroy();
// Cancel the persistent notification.
shutdownCounter();
nm.cancel(notificationID);
Toast.makeText(this, "Service destroyed at " + time.getTime() + ";
counter is at: " + counter, Toast.LENGTH_LONG).show();
counter=null;
}
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// Text to display the apparent name of the notification:Title for the
expanded status
18
// Set the info for the views that show in the notification panel.
// Text to display in the extended status window
String expandedText = "Service started Successfully, Go to stop buttin if
you want to stop it ";
19
App Widgets
Overview about AppWidgets
- Widgets are little applications which can be placed on a widget host, typically the
homescreen or the lockscreen, of your Android device.
- A Widget runs as part of the process of its host. This requires that Widgets
preserve the permissions of their application.
- Widgets use RemoteViews to create there user interface. A RemoteView can be
executed by another process with the same permissions as the original
application. This way the Widget runs with the permissions of its defining
application.
- The user interface for a Widget is defined by a BroadcastReceiver. This
BroadcastReceiver inflates its layout into an object of type RemoteViews. This
RemoteViews object is delivered to Android, which hands it over the
HomeScreen application.
AppWidget Framework
AppWidgetProviderInfo object:
- Describes the metadata for an App Widget, such as the App Widget's layout,
update frequency, and the AppWidgetProvider class.
- This should be defined in XML.
AppWidgetProvider class:
- Defines the basic methods that allow you to programmatically interface with the
App Widget, based on broadcast events. (AppWidgetProvider class is a child class
of BroadcastReceiver class).
- Through it, you will receive broadcasts when the App Widget is updated, enabled,
disabled and deleted.
View layout
- Defines the initial layout for the App Widget, defined in XML.
Additionally, you can implement an App Widget configuration Activity.
- This is an optional Activity that launches when the user adds your App Widget
and allows him or her to modify App Widget settings at create-time.
20
Steps to create a Widget
</receiver>
<receiver
android:name="MyWidgetIntentReceiver"
android:label="widgetBroadcastReceiver" >
<intent-filter>
<action android:name="pl.looksok.intent.action.CHANGE_PICTURE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/demo_widget_provider" />
</receiver>
<< Widget work: change the photo when button pressed >>
21
App Widget layouts are based on RemoteViews, which do not support every kind of
layout or view widget.
@Override
public void onUpdate(Context context, AppWidgetManager
appWidgetManager,
int[] appWidgetIds) { }
MyWidgetProvider Class
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
pushWidgetUpdate(context, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("pl.looksok.intent.action.CHANGE_PICTURE")){
updateWidgetPictureAndButtonListener(context);
}
}
MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(),
remoteViews);
}
23
Download WidgetDemo Code
24