1: package com.intertech.service;
2:
3: import java.util.concurrent.ExecutionException;
4: import java.util.concurrent.TimeUnit;
5: import java.util.concurrent.TimeoutException;
6:
7: import android.app.Notification;
8: import android.app.NotificationManager;
9: import android.app.PendingIntent;
10: import android.app.Service;
11: import android.content.Context;
12: import android.content.Intent;
13: import android.os.IBinder;
14: import android.util.Log;
15:
16: public class ConnectionCheckerService extends Service {
17:
18: private ConnectionTask task;
19:
20: @Override
21: public IBinder onBind(Intent arg0) {
22: return null;
23: }
24:
25: @Override
26: public void onCreate() {
27: super.onCreate();
28: Log.v("ConnectionChecker", "Connection Checker created");
29: }
30:
31: @Override
32: public int onStartCommand(Intent intent, int flags, int startId) {
33: Log.v("ConnectionChecker", "Connection Checker started");
34: task = new ConnectionTask();
35: task.execute();
36: notifyConnectionStatus();
37: return super.onStartCommand(intent, flags, startId);
38: }
39:
40: @Override
41: public void onDestroy() {
42: task.cancel(true);
43: Log.v("ConnectionChecker", "Stopping ConnectionChecker");
44: super.onDestroy();
45: }
46:
47: private void notifyConnectionStatus() {
48: Log.v("ConnectionChecker", "Getting task results.");
49: while (true) {
50: try {
51: Boolean result = task.get(1000, TimeUnit.MILLISECONDS);
52: Context context = getApplicationContext();
53: PendingIntent contentIntent = PendingIntent.getService(context,
54: 0, null, 0);
55: Notification notification = new Notification(R.drawable.icon,
56: "Connection Status", System.currentTimeMillis());
57: if (result) {
58: notification.setLatestEventInfo(context,
59: "Connection Service",
60: "Intertech connection available!", contentIntent);
61: } else {
62: notification
63: .setLatestEventInfo(context, "Connection Service",
64: "Intertech connection not available",
65: contentIntent);
66: }
67: NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
68: notificationManager.notify(1, notification);
69: Log.v("ConnectionChecker", "Task results displayed.");
70: break;
71: } catch (TimeoutException e) {
72: Log.v("ConnectionChecker", "Task work not completed.");
73: } catch (InterruptedException e) {
74: Log.v("ConnectionChecker", "Task work interrupted.");
75: break;
76: } catch (ExecutionException e) {
77: Log.v("ConnectionChecker", "Task work failed.");
78: break;
79: }
80: }
81: task.cancel(true);
82: }
83: }