Advertisement
tariq786

Context_Service.java

Sep 22nd, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.66 KB | None | 0 0
  1. package edu.umass.cs.client;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import android.annotation.SuppressLint;
  6. import android.app.Notification;
  7. import android.app.NotificationManager;
  8. import android.app.PendingIntent;
  9. import android.app.Service;
  10. import android.content.BroadcastReceiver;
  11. import android.content.Context;
  12. import android.content.Intent;
  13. import android.hardware.Sensor;
  14. import android.hardware.SensorEvent;
  15. import android.hardware.SensorEventListener;
  16. import android.hardware.SensorManager;
  17. import android.os.Bundle;
  18. import android.os.Handler;
  19. import android.os.IBinder;
  20. import android.os.Message;
  21. import android.os.Messenger;
  22. import android.os.RemoteException;
  23.  
  24. /**
  25.  *
  26.  * Context_Service: This is a sample class to reads sensor data (accelerometer). Received sensor data
  27.  * filtered, processed to extract features out of it and finally sent to the classification pipeline
  28.  * to detect steps and identify activity.
  29.  *
  30.  * @author CS390MB
  31.  *
  32.  */
  33. public class Context_Service extends Service implements SensorEventListener {
  34.  
  35.     /**
  36.      * Notification manager to display notifications
  37.      */
  38.     private NotificationManager nm;
  39.  
  40.     //added by TBA
  41.     private SensorManager msensorManager;
  42.     private Sensor mAccelerometer;
  43.  
  44.  
  45.     //List of bound clients/activities to this service
  46.     ArrayList<Messenger> mClients = new ArrayList<Messenger>();
  47.  
  48.     //Message codes sent and received by the service
  49.     static final int MSG_REGISTER_CLIENT = 1;
  50.     static final int MSG_UNREGISTER_CLIENT = 2;
  51.     static final int MSG_ACCEL_VALUES = 5;
  52.     static final int MSG_START_ACCELEROMETER = 6;
  53.     static final int MSG_STOP_ACCELEROMETER = 7;
  54.     static final int MSG_ACCELEROMETER_STARTED = 8;
  55.     static final int MSG_ACCELEROMETER_STOPPED = 9;
  56.  
  57.     static Context_Service sInstance = null;
  58.     private static boolean isRunning = false;
  59.     private static boolean isAccelRunning = false;
  60.    
  61.    
  62.     //Messenger used by clients
  63.     final Messenger mMessenger = new Messenger(new IncomingHandler());
  64.  
  65.     /**
  66.      * Handler to handle incoming messages
  67.      */
  68.     @SuppressLint("HandlerLeak")
  69.     class IncomingHandler extends Handler {
  70.         @Override
  71.         public void handleMessage(Message msg) {
  72.             switch (msg.what) {
  73.             case MSG_REGISTER_CLIENT:
  74.                 mClients.add(msg.replyTo);
  75.                 break;
  76.             case MSG_UNREGISTER_CLIENT:
  77.                 mClients.remove(msg.replyTo);
  78.                 break;
  79.             case MSG_START_ACCELEROMETER:
  80.             {
  81.                 isAccelRunning = true;
  82.                 //TODO:Start Accelerometer Here
  83.                 //added by TBA
  84.                 //msensorManager.registerListener((SensorEventListener) this,mAccelerometer,SensorManager.SENSOR_DELAY_GAME);
  85.                 msensorManager.registerListener(sInstance,mAccelerometer,SensorManager.SENSOR_DELAY_GAME);
  86.                 //msensorManager.registerListener(mAccelerometer,SensorManager.SENSOR_DELAY_GAME,this);
  87.                 //Send Message to UI that the accelerometer has been started
  88.                 sendMessageToUI(MSG_ACCELEROMETER_STARTED);
  89.                 showNotification();
  90.                 break;
  91.             }
  92.             case MSG_STOP_ACCELEROMETER:
  93.             {
  94.                 isAccelRunning = false;
  95.                 //TODO:Stop Accelerometer Here
  96.                 //added by TBA
  97.                 msensorManager.unregisterListener(sInstance);
  98.                 //Send Message to UI that the accelerometer has been stopped
  99.                 sendMessageToUI(MSG_ACCELEROMETER_STOPPED);
  100.                 showNotification();
  101.                 break;
  102.             }
  103.             default:
  104.                 super.handleMessage(msg);
  105.             }
  106.         }
  107.     }
  108.  
  109.     //addedy by TBA (09/16/2015)
  110.     @Override
  111.     public void onAccuracyChanged(Sensor sensor, int accuracy)
  112.     {
  113.  
  114.  
  115.     }
  116.     @Override
  117.     public void onSensorChanged(SensorEvent event)
  118.     {
  119.  
  120.         if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
  121.         {
  122.             float accel[] = event.values;
  123.             sendAccelValuesToUI(accel[0],accel[1],accel[2]);
  124.  
  125.         }
  126.     }
  127.  
  128.  
  129.     private void sendMessageToUI(int message) {
  130.         for (int i=mClients.size()-1; i>=0; i--) {
  131.             try {
  132.                 // Send message value
  133.                 mClients.get(i).send(Message.obtain(null, message));
  134.             } catch (RemoteException e) {
  135.                 // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
  136.                 mClients.remove(i);
  137.             }
  138.         }
  139.     }
  140.    
  141.     private void sendAccelValuesToUI(float accX, float accY, float accZ) {
  142.         for (int i=mClients.size()-1; i>=0; i-- ) {
  143.             try {
  144.                
  145.                 //Send Accel Values
  146.                 Bundle b = new Bundle();
  147.                 b.putFloat("accx", accX);
  148.                 b.putFloat("accy", accY);
  149.                 b.putFloat("accz", accZ);
  150.                 Message msg = Message.obtain(null, MSG_ACCEL_VALUES);
  151.                 msg.setData(b);
  152.                 mClients.get(i).send(msg);
  153.  
  154.             } catch (RemoteException e) {
  155.                 // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
  156.                 mClients.remove(i);
  157.             }
  158.         }
  159.     }
  160.    
  161.    
  162.  
  163.     /**
  164.      * On Binding, return a binder
  165.      */
  166.     @Override
  167.     public IBinder onBind(Intent intent) {
  168.         return mMessenger.getBinder();
  169.     }
  170.    
  171.  
  172.     //Start service automatically if we reboot the phone
  173.     public static class Context_BGReceiver extends BroadcastReceiver {
  174.         @Override
  175.         public void onReceive(Context context, Intent intent) {
  176.             Intent bootUp = new Intent(context,Context_Service.class);
  177.             context.startService(bootUp);
  178.         }      
  179.     }
  180.  
  181.     @SuppressWarnings("deprecation")
  182.     private void showNotification() {
  183.         //Cancel previous notification
  184.         if(nm!=null)
  185.             nm.cancel(777);
  186.         else
  187.             nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  188.  
  189.         // The PendingIntent to launch our activity if the user selects this notification
  190.         PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
  191.  
  192.         // Use the commented block of code if your target environment is Android-16 or higher
  193.         //Modify appropriately to show correct notifications
  194.         /*Notification notification = new Notification.Builder(this)
  195.         .setContentTitle("Context Service")
  196.         .setContentText("Running").setSmallIcon(R.drawable.icon)
  197.         .setContentIntent(contentIntent)
  198.         .build();
  199.        
  200.         nm.notify(777, notification); */
  201.        
  202.         //For lower versions of Android, the following code should work
  203.         Notification notification = new Notification();
  204.         notification.icon = R.drawable.icon;
  205.         notification.tickerText = "Context Service Running";
  206.         notification.contentIntent = contentIntent;
  207.         notification.when = System.currentTimeMillis();
  208.         if(isAccelerometerRunning())
  209.             notification.setLatestEventInfo(getApplicationContext(), "Accelerometer Demo", "Accelerometer Running", contentIntent);
  210.         else
  211.             notification.setLatestEventInfo(getApplicationContext(), "Accelerometer Demo", "Accelerometer Not Started", contentIntent);
  212.        
  213.         // Send the notification.
  214.         nm.notify(777, notification);
  215.     }
  216.  
  217.  
  218.  
  219.  
  220.    
  221.  
  222.  
  223.  
  224.  
  225.  
  226.    
  227.  
  228.  
  229.  
  230.     /* getInstance() and isRunning() are required by the */
  231.     static Context_Service getInstance(){
  232.         return sInstance;
  233.     }
  234.  
  235.     protected static boolean isRunning(){
  236.         return isRunning;
  237.     }
  238.    
  239.     protected static boolean isAccelerometerRunning() {
  240.         return isAccelRunning;
  241.     }
  242.  
  243.  
  244.  
  245.     @Override
  246.     public void onCreate() {
  247.         super.onCreate();
  248.         showNotification();
  249.         isRunning = true;
  250.         sInstance = this;
  251.  
  252.         //added by TBA
  253.         msensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
  254.         mAccelerometer = msensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  255.  
  256.     }
  257.    
  258.     @Override
  259.     public void onDestroy() {
  260.         super.onDestroy();
  261.         nm.cancel(777); // Cancel the persistent notification.
  262.         isRunning = false;
  263.         //Don't let Context_Service die!
  264.         Intent mobilityIntent = new Intent(this,Context_Service.class);
  265.         startService(mobilityIntent);
  266.     }
  267.    
  268.  
  269.     @Override
  270.     public int onStartCommand(Intent intent, int flags, int startId) {
  271.         return START_STICKY; // run until explicitly stopped.
  272.     }
  273.  
  274.  
  275. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement