Ejemplo n.º 1
0
 public void testConstructorAndEquals() {
   Messenger messenger = new Messenger(mHandler);
   Messenger objMessenger = new Messenger(mHandler);
   assertTrue(messenger.equals(objMessenger));
   messenger = new Messenger(mIBinder);
   assertFalse(messenger.equals(objMessenger));
 }
  public void calcular(View v) {
    if (mServicioUnido && mServicio != null && camposValidos()) {
      try {
        Message msg =
            Message.obtain(
                null,
                CalcularServicio.MSG_GENERAR_AREA,
                (int) Float.parseFloat(etAltura.getText().toString()),
                (int) Float.parseFloat(etBase.getText().toString()));
        msg.replyTo = mMessenger;
        mServicio.send(msg);

        Message msg2 =
            Message.obtain(
                null,
                CalcularServicio.MSG_GENERAR_VOLUMEN,
                (int) Float.parseFloat(etAltura.getText().toString()),
                (int) Float.parseFloat(etBase.getText().toString()));
        msg2.replyTo = mMessenger;
        mServicio.send(msg2);
      } catch (RemoteException e) {
        toastErrorConexion();
      }
    }
  }
Ejemplo n.º 3
0
  /**
   * Helper method for sending messages to the scheduler
   *
   * @param msg message to be sent
   * @throws MeasurementError
   */
  private void sendMessage(Message msg) throws MeasurementError {
    Messenger messenger = getScheduler();
    if (messenger != null) {
      // Append client key to every msg sent from API
      Bundle data = msg.getData();
      if (data == null) {
        data = new Bundle();
        msg.setData(data);
      }
      data.putString(UpdateIntent.CLIENTKEY_PAYLOAD, clientKey);

      try {
        messenger.send(msg);
      } catch (RemoteException e) {
        String err = "remote scheduler failed!";
        Logger.e(err);
        throw new MeasurementError(err);
      }
    } else {
      String err =
          "API didn't bind to a scheduler. Message will be temporarily"
              + " queued and sent after scheduler bound";
      Logger.e(err);
      this.pendingMsg.offer(msg);
    }
  }
Ejemplo n.º 4
0
 @Override
 public void onClick(View v) {
   Intent intent;
   switch (v.getId()) {
     case R.id.btn_login:
       Utils.alertToast(getBaseContext(), tag, "开启Service");
       intent = new Intent(this, ChatService.class);
       startService(intent);
       Message msg = Message.obtain(null, Common.LOGIN);
       Bundle b = new Bundle();
       b.putInt("account", Integer.parseInt(et_account.getText().toString()));
       b.putString("password", et_password.getText().toString());
       msg.setData(b);
       try {
         rMessenger.send(msg);
       } catch (RemoteException e) {
         e.printStackTrace();
       }
       break;
     case R.id.btn_regist:
       Utils.alertToast(getBaseContext(), tag, "开启Service");
       intent = new Intent(this, ChatService.class);
       startService(intent);
       Message test_message = Message.obtain(null, PackageType.TEST);
       try {
         rMessenger.send(test_message);
       } catch (RemoteException e) {
         e.printStackTrace();
       }
       break;
   }
 }
        public void onServiceConnected(ComponentName className, IBinder service) {
          // This is called when the connection with the service has been
          // established, giving us the service object we can use to
          // interact with the service.  We are communicating with our
          // service through an IDL interface, so get a client-side
          // representation of that from the raw service object.
          mService = new Messenger(service);
          Log.d(TAG, "Service Attached.");
          if (mAction == "com.xwell.usbcan.CANVOLUMEDOWN") {
            try {
              Message msg = Message.obtain(null, USBCANMonitor.MSG_VOLUME_DOWN);
              if (mService != null) mService.send(msg);
              finish();
            } catch (RemoteException e) {
              // There is nothing special we need to do if the service
              // has crashed.
            }
          }

          if (mAction == "com.xwell.usbcan.CANVOLUMEUP") {
            try {
              Message msg = Message.obtain(null, USBCANMonitor.MSG_VOLUME_UP);
              if (mService != null) mService.send(msg);
              finish();
            } catch (RemoteException e) {
              // There is nothing special we need to do if the service
              // has crashed.
            }
          }
        }
Ejemplo n.º 6
0
 public void testWriteToParcel() {
   Parcel parcel = Parcel.obtain();
   mMessenger.writeToParcel(parcel, 0);
   parcel.setDataPosition(0);
   Messenger messenger = Messenger.CREATOR.createFromParcel(parcel);
   assertTrue(messenger.equals(mMessenger));
   parcel.recycle();
 }
  @Override
  protected void onHandleIntent(Intent intent) {
    Uri data = intent.getData();
    String urlPath = intent.getStringExtra("urlPath");
    String fileName = data.getPath();
    File output = new File(Environment.getExternalStorageDirectory(), fileName);

    if (output.exists()) {
      output.delete();
    }
    InputStream stream = null;
    FileOutputStream fos = null;
    try {

      URL url = new URL(urlPath);
      stream = url.openConnection().getInputStream();
      InputStreamReader reader = new InputStreamReader(stream);
      fos = new FileOutputStream(output.getPath());
      int next = -1;
      while ((next = reader.read()) != -1) {
        fos.write(next);
      }
      result = Activity.RESULT_OK;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    Bundle extras = intent.getExtras();
    if (extras != null) {
      Messenger messenger = (Messenger) extras.get("messenger");
      Message msg = Message.obtain();
      msg.arg1 = result;
      msg.obj = output.getAbsolutePath();
      try {
        messenger.send(msg);
      } catch (android.os.RemoteException e1) {
        Log.e("DownloadService", "Erro ao enviar mesagem", e1);
      }
    }
  }
Ejemplo n.º 8
0
 /**
  * Replies to our Service saying this task is completed
  *
  * @param response The response message to send
  */
 protected void sendReply() {
   Messenger replyTo = msg.replyTo;
   if (replyTo != null) {
     try {
       replyTo.send(msg);
     } catch (Exception e) { // Mostly RemoteException
       try {
         msg.what = 666; // Some error code
         replyTo.send(msg);
       } catch (RemoteException e1) {
         /** Nothing we can do */
       }
     }
   }
 }
 void doUnbindService() {
   Log.d(TAG, "doUnbindService..mIsBound=" + mIsBound);
   if (mIsBound) {
     // If we have received the service, and hence registered with
     // it, then now is the time to unregister.
     if (mService != null) {
       try {
         Message msg = Message.obtain(null, AdkService.MSG_UNREGISTER_CLIENT);
         msg.replyTo = mMessenger;
         mService.send(msg);
       } catch (RemoteException e) {
         // There is nothing special we need to do if the service
         // has crashed.
       }
       mService = null;
     }
     Log.d(TAG, "doUnbindService..2");
     /* */
     if (mUsbReceiver != null) unregisterReceiver(mUsbReceiver);
     /*  */
     if (mConnection != null) unbindService(mConnection);
     Log.d(TAG, "doUnbindService..3");
     mIsBound = false;
   }
 }
 public void onServiceConnected(ComponentName className, IBinder service) {
   Log.d(TAG, "-ServiceConnection-onServiceConnected");
   // This is called when the connection with the service has been
   // established, giving us the service object we can use to
   // interact with the service.  We are communicating with our
   // service through an IDL interface, so get a client-side
   // representation of that from the raw service object.
   mService = new Messenger(service);
   //			mCallbackText.setText("Attached.");
   // We want to monitor the service for as long as we are
   // connected to it.
   try {
     Message msg = Message.obtain(null, AdkService.MSG_REGISTER_CLIENT);
     msg.replyTo = mMessenger;
     mService.send(msg);
     // Give it some value as an example.
     //				msg = Message.obtain(null,
     //						AdkService.MSG_SET_VALUE, this.hashCode(), 0);
     //				mService.send(msg);
   } catch (RemoteException e) {
     // In this case the service has crashed before we could even
     // do anything with it; we can count on soon being
     // disconnected (and then reconnected if it can be restarted)
     // so there is no need to do anything here.
   }
   sendUsbFileDescriptor();
   // As part of the sample, tell the user what happened.
   Toast.makeText(AdkWikiActivity.this, "AdkService Connected", Toast.LENGTH_SHORT).show();
 }
Ejemplo n.º 11
0
  public int clientHandleState(Messenger mService, Message msg, Activity parent) {
    switch (msg.arg1) {
      case MSG_NOT_SUPPORTED:
        return NOT_SUPPORTED;

      case MSG_DEVICE_NOT_ENABLED: // not enabled
        if (firstTimeEnableDevice) {
          firstTimeEnableDevice = false;
          Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
          parent.startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
        }
        return NOT_ENABLED;

      case MSG_NOT_CONNECTED_TO_DEVICE: // Enabled but not connected
        Message ret = listBluetoothDevices(parent);
        if (ret != null) {
          try {
            mService.send(ret);
          } catch (RemoteException e) {
            e.printStackTrace();
          }
        }
        return NOT_CONNECTED;

      case MSG_CONNECTED_TO_DEVICE: // Connected
        return CONNECTED;
    }
    return 0;
  }
Ejemplo n.º 12
0
  // obsługa przycisku zatwierdz
  public void sendSmsByManager() {
    try {

      smsModel.setPhone(phoneNumber.getText().toString());
      smsModel.setSms(smsBody.getText().toString() + " ");
      dateTextView.setText("");
      timeTextView.setText("");
      phoneNumber.setText("");
      smsBody.setText("");
      if (Patterns.PHONE.matcher(smsModel.getPhone()).matches()) {
        Message msg = Message.obtain(null, SMSService.SEND_SMS, 0, 0);
        Bundle bundle = new Bundle();
        bundle.putParcelable("sms", smsModel);
        msg.setData(bundle);
        try {
          messenger.send(msg);
        } catch (RemoteException e) {
          e.printStackTrace();
        }
      } else {
        Toast.makeText(getApplicationContext(), R.string.invalidPhone, Toast.LENGTH_LONG).show();
      }

    } catch (Exception ex) {
      Toast.makeText(getApplicationContext(), R.string.failedToSendSms, Toast.LENGTH_LONG).show();
      ex.printStackTrace();
    }
  }
 /**
  * Tells the <code>IBeaconService</code> to start looking for iBeacons that match the passed
  * <code>Region</code> object, and providing updates on the estimated distance very seconds while
  * iBeacons in the Region are visible. Note that the Region's unique identifier must be retained
  * to later call the stopRangingBeaconsInRegion method.
  *
  * @param region
  * @see IBeaconManager#setRangeNotifier(RangeNotifier)
  * @see IBeaconManager#stopRangingBeaconsInRegion(Region region)
  * @see RangeNotifier
  * @see Region
  */
 public void startRangingBeaconsInRegion(Region region) throws RemoteException {
   Message msg = Message.obtain(null, IBeaconService.MSG_START_RANGING, 0, 0);
   StartRMData obj = new StartRMData(new RegionData(region), rangingCallbackAction());
   msg.obj = obj;
   msg.replyTo = rangingCallback;
   serviceMessenger.send(msg);
 }
 /**
  * Tells the <code>IBeaconService</code> to start looking for iBeacons that match the passed
  * <code>Region</code> object. Note that the Region's unique identifier must be retained to later
  * call the stopMonitoringBeaconsInRegion method.
  *
  * @param region
  * @see IBeaconManager#setMonitorNotifier(MonitorNotifier)
  * @see IBeaconManager#stopMonitoringBeaconsInRegion(Region region)
  * @see MonitorNotifier
  * @see Region
  */
 public void startMonitoringBeaconsInRegion(Region region) throws RemoteException {
   Message msg = Message.obtain(null, IBeaconService.MSG_START_MONITORING, 0, 0);
   StartRMData obj = new StartRMData(new RegionData(region), monitoringCallbackAction());
   msg.obj = obj;
   msg.replyTo = null; // TODO: remove this when we are converted to Intents
   serviceMessenger.send(msg);
 }
Ejemplo n.º 15
0
  /**
   * メッセージの送信
   *
   * @param v
   */
  public void send(View v) {
    try {

      // メッセージの送信
      // _messenger.send(Message.obtain());

      // メッセージとデータの送信
      // _messenger.send(Message.obtain(null, TestService.M_SEND_STRING, "hoge"));

      // メッセージにBundleを付与して送信
      TestData data = new TestData();
      data.setName("piyo");
      data.setValue("huga");
      Bundle arg = new Bundle();
      arg.putSerializable("testData", data);
      Message msg = Message.obtain(null, TestService.M_SEND_BUNDLE);
      msg.setData(arg);

      // コールバックを設定
      // msg.replyTo = _replyMessanger;

      _messenger.send(msg);

    } catch (RemoteException e) {
      e.printStackTrace();
      Toast.makeText(getApplicationContext(), "メッセージの送信に失敗しました。", Toast.LENGTH_SHORT).show();
    }
  }
Ejemplo n.º 16
0
        public void onServiceConnected(ComponentName className, IBinder service) {
          // This is called when the connection with the service has been
          // established, giving us the service object we can use to
          // interact with the service.  We are communicating with our
          // service through an IDL interface, so get a client-side
          // representation of that from the raw service object.
          mService = new Messenger(service);
          // mCallbackText.setText("Attached.");

          // We want to monitor the service for as long as we are
          // connected to it.
          try {
            Message msg = Message.obtain(null, UploadingService.MSG_REGISTER_CLIENT);
            Bundle params = new Bundle();
            params.putString("CLASS_NAME", mHostToken);
            msg.setData(params);
            msg.replyTo = mMessenger;
            mService.send(msg);

          } catch (RemoteException e) {
            // In this case the service has crashed before we could even
            // do anything with it; we can count on soon being
            // disconnected (and then reconnected if it can be restarted)
            // so there is no need to do anything here.
          }

          mIsBound = true;
        }
Ejemplo n.º 17
0
  private void sendLocation(Location location) {
    LOGGER.debug("Location changed: {}", location);
    for (int i = mClients.size() - 1; i >= 0; i--) {

      try {
        // Send data as an Integer
        mClients.get(i).send(Message.obtain(null, MSG_LOCATION_CHANGED, location));

      } catch (RemoteException e) {
        // 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.
        mClients.remove(i);
      }
    }

    Message message = Message.obtain();
    message.obj = location;

    try {
      mMessenger.send(message);
    } catch (RemoteException e) {
      LOGGER.error("Error sending location", e);
    }
  }
Ejemplo n.º 18
0
 /**
  * Tells the <code>IBeaconService</code> to stop looking for iBeacons that match the passed <code>
  * Region</code> object. Note that the Region's unique identifier is used to match it to and
  * existing monitored Region.
  *
  * @see BLEManager#setMonitorNotifier(MonitorNotifier)
  * @see BLEManager#startMonitoringBeaconsInRegion(Region region)
  * @see MonitorNotifier
  * @see Region
  * @param region
  */
 @TargetApi(18)
 public void stopMonitoringBeaconsInRegion(String region) throws RemoteException {
   if (android.os.Build.VERSION.SDK_INT < 18) {
     Log.w(TAG, "Not supported prior to API 18.  Method invocation will be ignored");
     return;
   }
   if (serviceMessenger == null) {
     throw new RemoteException(
         "The IBeaconManager is not bound to the service.  Call iBeaconManager.bind(IBeaconConsumer consumer) and wait for a callback to onIBeaconServiceConnect()");
   }
   Message msg = Message.obtain(null, BLEService.MSG_STOP_MONITORING, 0, 0);
   StartRMData obj =
       new StartRMData(
           region, callbackPackageName(), this.getScanPeriod(), this.getBetweenScanPeriod());
   msg.obj = obj;
   serviceMessenger.send(msg);
   synchronized (monitoredRegions) {
     String regionToRemove = null;
     for (String monitoredRegion : monitoredRegions) {
       if (region.equals(monitoredRegion)) {
         regionToRemove = monitoredRegion;
       }
     }
     monitoredRegions.remove(regionToRemove);
   }
 }
Ejemplo n.º 19
0
    /**
     * Download the designated image and reply to the DownloadActivity via the Messenger sent with
     * the Intent.
     */
    private void downloadImageAndReply(Intent intent) {
      // Download the requested image.
      String pathname = downloadImage(DownloadService.this, intent.getData().toString());

      // Call factory method to create Message.
      Message message = makeReplyMessage(pathname);

      // Extract the Messenger.
      Messenger messenger = (Messenger) intent.getExtras().get("MESSENGER");

      try {
        // Send pathname to back to the DownloadActivity.
        messenger.send(message);
      } catch (RemoteException e) {
        Log.e(getClass().getName(), "Exception while sending.", e);
      }
    }
Ejemplo n.º 20
0
  /**
   * Send the data to all clients.
   *
   * @param intvaluetosend The value to send.
   */
  private void sendLocationToMap(String instance) {
    Iterator<Messenger> messengerIterator = mClients.iterator();
    while (messengerIterator.hasNext()) {
      Messenger messenger = messengerIterator.next();
      try {
        // Send data as a String
        Bundle bundle = new Bundle();
        bundle.putString("str", instance);
        Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
        msg.setData(bundle);
        messenger.send(msg);

      } catch (RemoteException e) {
        // The client is dead. Remove it from the list.
        mClients.remove(messenger);
      }
    }
  }
 @Override
 protected void onPause() {
   Logs.d(this, "onPause");
   if (mService != null && mService.getBinder() != null) {
     // unbindService(myConnection);
     doUnbindService();
   }
   super.onPause();
 }
Ejemplo n.º 22
0
 // pass msgs inward
 public void recvMsg(Message m) {
   if (mClientMessenger != null)
     try {
       Log.d(TAG, "forward a msg to clientMessenger");
       mClientMessenger.send(m);
     } catch (RemoteException e) {
       Log.e(TAG, "failed to forward msg to local messenger recver: " + e.getMessage());
     }
 }
  public void sendToService(Bundle bundle, int msgActionSend) {
    Message message = Message.obtain(null, msgActionSend);
    message.setData(bundle);

    try {
      mService.send(message);
    } catch (RemoteException e) {
      e.printStackTrace();
    }
  }
 public void onServiceConnected(ComponentName className, IBinder service) {
   serviceMessenger = new Messenger(service);
   try {
     Message msg = Message.obtain(null, WebSocketService.MSG_REGISTER_CLIENT);
     msg.replyTo = messenger;
     serviceMessenger.send(msg);
   } catch (RemoteException e) {
     // In this case the service has crashed before we could even do anything with it
   }
 }
  private void sendUsbFileDescriptor() {
    Log.d(TAG, "sendUsbFileDescriptor");
    try {
      Message msg = Message.obtain(null, AdkService.MSG_SET_USBFILEDESCRIPTOR);
      msg.obj = this.mFileDescriptor;
      mService.send(msg);
    } catch (Exception e) {

    }
  }
  public void sendCommandToService(String cmd, String val) {
    Log.d(TAG, "sendCommandToService(" + cmd + "," + val + ")");
    try {
      Message msg = Message.obtain(null, AdkService.MSG_EXEC_COMMAND);
      msg.obj = new StringMsg(cmd, val);
      mService.send(msg);
    } catch (Exception e) {

    }
  } /* */
 protected void sendIPCMessage(int what) {
   Message msg = mServiceHandler.obtainMessage(what);
   msg.replyTo = serviceMessenger;
   try {
     debug("sending IPC Message ID: " + what);
     engineMessenger.send(msg);
   } catch (Exception x) {
     debug("sendIPCEvent " + x.getClass().getSimpleName() + ", " + x.getMessage());
   }
 }
Ejemplo n.º 28
0
  @Override
  protected void onHandleIntent(Intent intent) {
    PhotoList list = null;
    OAuth oAuth = null;
    try {
      oAuth = new Gson().fromJson(intent.getStringExtra(IntentKeys.OAUTH), OAuth.class);
    } catch (Exception e) {

    }
    if (oAuth != null) {
      OAuthToken token = oAuth.getToken();
      Flickr f =
          FlickrHelper.getInstance()
              .getFlickrAuthed(token.getOauthToken(), token.getOauthTokenSecret());
      Set<String> extras = new HashSet<String>();
      extras.add("url_sq");
      extras.add("url_l");
      extras.add("views");
      extras.add("geo");
      User user = oAuth.getUser();
      try {
        list = f.getPeopleInterface().getPhotos(user.getId(), extras, 40, 1);
        result = Activity.RESULT_OK;
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    Bundle extras = intent.getExtras();
    if (extras != null) {
      Messenger messenger = (Messenger) extras.get(IntentKeys.MESSENGER);
      Message msg = Message.obtain();
      msg.arg1 = result;
      msg.obj = list;

      try {
        messenger.send(msg);
      } catch (android.os.RemoteException e1) {
        Logger.e(TAG, "Exception sending message", e1);
      }
    }
  }
 private void selfDestryService() {
   try {
     if (msgCenter != null) {
       Message msg = Message.obtain(null, MAVLinkClient.MSG_SELF_DESTRY_SERVICE);
       msgCenter.send(msg);
     }
   } catch (RemoteException e) {
     e.printStackTrace();
   }
 }
 /** send result to the source activity */
 private void sendResult(ArrayList<String> matches, boolean enabled, boolean canceled) {
   if (matches == null) {
     matches = new ArrayList<String>();
   }
   Intent fromIntent = getIntent();
   Messenger msger = fromIntent.getParcelableExtra("VOICE_RESULT_MESSENGER");
   Message msg = new Message();
   Bundle bundle = new Bundle();
   bundle.putBoolean("VOICE_RECOGNITION_CANCELED", canceled);
   bundle.putBoolean("VOICE_RECOGNITION_ENABLED", enabled);
   bundle.putStringArrayList("VOICE_RESULT", matches);
   msg.setData(bundle);
   try {
     msger.send(msg);
   } catch (RemoteException e) {
     e.printStackTrace();
   }
   finish();
 }