1. Download our Official Android App: Forums for Android!

Apps Foreground Service with Timer problem

Discussion in 'Android Development' started by gijsvb, Jun 4, 2011.

  1. gijsvb

    gijsvb Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    1
    Joined:
    Jun 4, 2011

    Jun 4, 2011
    1
    0
    5
    Hi everyone, I am developing an application that checks connectivity to a server at given interval. I use a foreground service with notifications for this. The problem is that everything works fine as long as the phone is awake (screen turned on). From the moment I turn of the screen by pressing the power button the service starts to behave strange. I made a stripped down version of my service to show you.
    ForegroundService.java:
    Code (Text):
    1.     package service.App;
    2.     import android.R.drawable;
    3.     import android.app.Notification;
    4.     import android.app.NotificationManager;
    5.     import android.app.PendingIntent;
    6.     import android.app.Service;
    7.     import android.content.Context;
    8.     import android.content.Intent;
    9.     import android.media.RingtoneManager;
    10.     import android.net.Uri;
    11.     import android.os.IBinder;
    12.     import android.util.Log;
    13.     import java.io.IOException;
    14.     import java.lang.reflect.InvocationTargetException;
    15.     import java.lang.reflect.Method;
    16.     import java.net.InetAddress;
    17.     import java.net.InetSocketAddress;
    18.     import java.net.Socket;
    19.     import java.net.UnknownHostException;
    20.     import java.sql.Date;
    21.     import java.text.SimpleDateFormat;
    22.     import java.util.Timer;
    23.     import java.util.TimerTask;
    24.      
    25.     public class ForegroundService extends Service {
    26.     static final String ACTION_FOREGROUND = "com.example.android.apis.FOREGROUND";
    27.     static final String ACTION_BACKGROUND = "com.example.android.apis.BACKGROUND";
    28.     private static final Class<?>[] mStartForegroundSignature = new Class[] {int.class, Notification.class };
    29.     private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
    30.     private Method mStartForeground;
    31.     private Method mStopForeground;
    32.     private Object[] mStartForegroundArgs = new Object[2];
    33.     private Object[] mStopForegroundArgs = new Object[1];
    34.     private Timer timer = new Timer();
    35.     long interv=10000;
    36.     int timeout=3000;
    37.     Intent notificationIntent;
    38.     PendingIntent contentIntent;
    39.     Notification notification;
    40.     CharSequence text;
    41.     SimpleDateFormat df;
    42.      
    43.     void invokeMethod(Method method, Object[] args) {
    44.       try {
    45.         mStartForeground.invoke(this, mStartForegroundArgs);
    46.       } catch (InvocationTargetException e) {
    47.         Log.w("ApiDemos", "Unable to invoke method", e);
    48.       } catch (IllegalAccessException e) {
    49.         Log.w("ApiDemos", "Unable to invoke method", e);
    50.       }
    51.     }
    52.      
    53.     void startForegroundCompat(int id, Notification notification) {
    54.       Scan();
    55.       if (mStartForeground != null) {
    56.         mStartForegroundArgs[0] = Integer.valueOf(id);
    57.         mStartForegroundArgs[1] = notification;
    58.         invokeMethod(mStartForeground, mStartForegroundArgs);
    59.         return;
    60.       }
    61.     }
    62.      
    63.     void stopForegroundCompat(int id) {
    64.       if (mStopForeground != null) {
    65.         mStopForegroundArgs[0] = Boolean.TRUE;
    66.         try {
    67.           mStopForeground.invoke(this, mStopForegroundArgs);
    68.         } catch (InvocationTargetException e) {
    69.           Log.w("ApiDemos", "Unable to invoke stopForeground", e);
    70.         } catch (IllegalAccessException e) {
    71.           Log.w("ApiDemos", "Unable to invoke stopForeground", e);
    72.         }
    73.         return;
    74.       }
    75.     }
    76.      
    77.     @Override
    78.     public void onCreate() {
    79.      
    80.       notificationIntent = new Intent(this, ForegroundService.class);
    81.       contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);
    82.       try {
    83.         mStartForeground = getClass().getMethod("startForeground",mStartForegroundSignature);
    84.         mStopForeground = getClass().getMethod("stopForeground",mStopForegroundSignature);
    85.       } catch (NoSuchMethodException e) {
    86.         return;
    87.       }
    88.     }
    89.      
    90.     @Override
    91.     public void onDestroy() {
    92.       stopForegroundCompat(R.string.foreground_service_started);
    93.      
    94.       if (timer != null) {
    95.      
    96.         timer.cancel();
    97.       }
    98.     }
    99.      
    100.     @Override
    101.     public int onStartCommand(Intent intent, int flags, int startId) {
    102.       handleCommand(intent);
    103.       return START_STICKY;
    104.     }
    105.      
    106.     void handleCommand(Intent intent) {
    107.       if (ACTION_FOREGROUND.equals(intent.getAction())) {
    108.         text = getText(R.string.foreground_service_started);
    109.      
    110.         notification = new Notification(R.drawable.icon, text, System
    111.             .currentTimeMillis());
    112.      
    113.         contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
    114.             Start.class), 0);
    115.      
    116.         notification.setLatestEventInfo(this,
    117.             getText(R.string.local_service_label), text, contentIntent);
    118.      
    119.         startForegroundCompat(R.string.foreground_service_started,
    120.             notification);
    121.      
    122.       } else if (ACTION_BACKGROUND.equals(intent.getAction())) {
    123.         stopForegroundCompat(R.string.foreground_service_started);
    124.       }
    125.      
    126.     }
    127.      
    128.     @Override
    129.     public IBinder onBind(Intent intent) {
    130.       return null;
    131.     }
    132.      
    133.      
    134.     private void Scan() {
    135.       timer.scheduleAtFixedRate(new TimerTask() {
    136.      
    137.         @Override
    138.         public void run() {
    139.      
    140.           Socket s = null;
    141.           int p = 81;
    142.           long time;
    143.           String url="www.google.com";
    144.           SimpleDateFormat df;
    145.           InetAddress ipaddress;
    146.             try {
    147.      
    148.               ipaddress = InetAddress.getByName(url);
    149.      
    150.               try {
    151.                 s = new Socket();
    152.                 s.connect(new InetSocketAddress(url, p), timeout);
    153.                 time = System.currentTimeMillis();
    154.                 df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    155.                 Log.i("Server Monitor",
    156.                     "A server is running on port " + p + " "
    157.                         + "@ IP address "
    158.                         + ipaddress.getHostAddress()
    159.                         + ". Date/Time: "
    160.                         + df.format(new Date(time)));
    161.                 s.close();
    162.               } catch (IOException e) {
    163.                 String ns = Context.NOTIFICATION_SERVICE;
    164.                 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    165.                 long when = System.currentTimeMillis();
    166.                 Notification notification = new Notification(drawable.ic_dialog_alert,"Server Monitor", when);
    167.                 Context context = getApplicationContext();
    168.                 CharSequence contentTitle = "Server Monitor";
    169.                 CharSequence contentText = "No server on port." + p;
    170.                 notification.setLatestEventInfo(context,contentTitle, contentText, contentIntent);
    171.                 notification.defaults |= Notification.DEFAULT_SOUND;
    172.                 final int HELLO_ID = 1;
    173.                 mNotificationManager.notify(HELLO_ID, notification);
    174.      
    175.               }
    176.             } catch (UnknownHostException e) {
    177.               String ns = Context.NOTIFICATION_SERVICE;
    178.               NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    179.               long when = System.currentTimeMillis();
    180.               Notification notification = new Notification(drawable.ic_dialog_alert,"Server Monitor", when);
    181.               Context context = getApplicationContext();
    182.               CharSequence contentTitle = "Server Monitor";
    183.               CharSequence contentText = "Could not find host.";
    184.               notification.setLatestEventInfo(context,contentTitle, contentText, contentIntent);
    185.               notification.defaults |= Notification.DEFAULT_SOUND;
    186.               final int HELLO_ID = 1;
    187.               mNotificationManager.notify(HELLO_ID, notification);
    188.      
    189.             }
    190.      
    191.             if (s != null) {
    192.               try {
    193.                 s.close();
    194.               } catch (IOException ioEx) {
    195.                 Log.i("Server Monitor", "Unable to close socket "+ s);
    196.               }
    197.             }
    198.       }
    199.      
    200.       }, 0, interv);
    201.     }
    202.     }
    So this service checks connectivity with http://www.google.com at port 81 every 10 seconds. I put this on port 81 to make it fail and test the notifications. When it fails it shows a notification. From the moment I turn of the screen there are no notifications for one or more minutes, and then it gives me all the notifications at once. Below is the activity that starts the service.
    Start.java:
    Code (Text):
    1.  
    2.     package service.App;
    3.     import service.App.R;
    4.     import service.App.ForegroundService;
    5.     import android.app.Activity;
    6.     import android.content.Intent;
    7.     import android.os.Bundle;
    8.     import android.view.View;
    9.     import android.widget.Button;
    10.      
    11.     public class Start extends Activity{
    12.     private Button ButtonStartService;
    13.     @Override
    14.     public void onCreate(Bundle savedInstanceState) {
    15.         super.onCreate(savedInstanceState);
    16.         setContentView(R.layout.main);
    17.      
    18.         ButtonStartService = (Button)findViewById(R.id.ButtonStartService);
    19.      
    20.         ButtonStartService.setOnClickListener(new View.OnClickListener() {
    21.             public void onClick(View v) {
    22.                 Intent intent = new Intent(ForegroundService.ACTION_FOREGROUND);
    23.                 intent.setClass(Start.this, ForegroundService.class);
    24.                 startService(intent);
    25.             }
    26.      
    27.         });
    28.     }
    29.     }
    So i am doing anything wrong here? This is a really important piece of my application so this bug really has to be fixed. Can someone help me please?
     

    Advertisement

Share This Page

Loading...