void invokeMethod(Method method, Object[] args) {
   try {
     method.invoke(this, args);
   } catch (InvocationTargetException e) {
     // Should not happen.
     Log.w(e, "Unable to invoke method");
   } catch (IllegalAccessException e) {
     // Should not happen.
     Log.w(e, "Unable to invoke method");
   }
 }
  private void dumpInstalledLinphoneInformation() {
    PackageInfo info = null;
    try {
      info = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (NameNotFoundException nnfe) {
    }

    if (info != null) {
      Log.i("Linphone version is ", info.versionCode);
    } else {
      Log.i("Linphone version is unknown");
    }
  }
  public void onRegistrationStateChanged(final RegistrationState state, final String message) {
    if (instance == null) {
      Log.i("Service not ready, discarding registration state change to ", state.toString());
      return;
    }
    //		if (state == RegistrationState.RegistrationOk &&
    // LinphoneManager.getLc().getDefaultProxyConfig().isRegistered()) {
    //			sendNotification(IC_LEVEL_ORANGE, R.get("string", "notification_registered"));
    //		}

    //		if (state == RegistrationState.RegistrationFailed || state ==
    // RegistrationState.RegistrationCleared) {
    //			sendNotification(IC_LEVEL_OFFLINE, R.get("string", "notification_register_failure"));
    //		}

    if (state == RegistrationState.RegistrationOk
        || state == RegistrationState.RegistrationFailed) {
      mHandler.post(
          new Runnable() {
            public void run() {
              ALModuleProxy.onRegistrationStateChanged(state, message);
              //					if (LinphoneActivity.isInstanciated())
              //							LinphoneActivity.instance().onRegistrationStateChanged(state, message);
            }
          });
    }
  }
  @Override
  public void onTextReceived(LinphoneAddress from, String message) {
    //		Object[] obj = {from.toString(), message};
    Log.d("ALModule", "onTextReceived");
    Log.d("ALModule", from.toString());
    Log.d("ALModule", message);

    JSONObject json;
    String type = null;

    try {
      json = new JSONObject(message);
      type = json.getString("type");
    } catch (JSONException e) {
      //	e.printStackTrace();
      json = null;
      type = null;
    }

    if (json != null && type != null) {
      if (type.equals("invite") == true) {
        try {

          String fromUrl = json.getString("fromUrl");
          String fromName = json.getString("fromName");
          String callType = json.getString("callType");

          postInfo(fromUrl, fromName, callType);
        } catch (JSONException e) {
          e.printStackTrace();
        }

        return;
      }
    }

    //
    ALModuleProxy alModuleProxy = ALModuleProxy.getInstance();
    if (alModuleProxy != null) {
      KrollDict dict = new KrollDict();
      dict.put("from", from.toString());
      dict.put("message", message);
      alModuleProxy.fireEvent(dict, "TextReceived");
    }
  }
 private void dumpDeviceInformation() {
   StringBuilder sb = new StringBuilder();
   sb.append("DEVICE=").append(Build.DEVICE).append("\n");
   sb.append("MODEL=").append(Build.MODEL).append("\n");
   // MANUFACTURER doesn't exist in android 1.5.
   // sb.append("MANUFACTURER=").append(Build.MANUFACTURER).append("\n");
   sb.append("SDK=").append(Build.VERSION.SDK);
   Log.i(sb.toString());
 }
        @Override
        public void handleMessage(Message msg) {
          Bundle bundle = msg.getData();
          String type = (String) bundle.get("type");

          Log.d("myHandler:type = " + type);

          if (type.equals("invite") == true) {
            String fromUrl = bundle.getString("fromUrl");
            String fromName = bundle.getString("fromName");
            String callType = bundle.getString("callType");

            userNameText = fromName;
            callTypeText = callType;

            Log.d("myHandler:fromUrl = " + fromUrl);
            Log.d("myHandler:fromName = " + fromName);

            try {

              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpGet hg = new HttpGet(fromUrl);
              HttpResponse httpResponse = httpClient.execute(hg);

              if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Bitmap bmp = BitmapFactory.decodeStream(httpResponse.getEntity().getContent());
                hg.abort();

                Log.d("myHandler:complete!!!");
                userImage = bmp;
              }
            } catch (ClientProtocolException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            } catch (IllegalStateException e) {
              e.printStackTrace();
            }
          }
        }
 public void onRingerPlayerCreated(MediaPlayer mRingerPlayer) {
   String uriString =
       PreferenceManager.getDefaultSharedPreferences(this)
           .getString(
               getString(R.get("string", "pref_audio_ringtone")),
               android.provider.Settings.System.DEFAULT_RINGTONE_URI.toString());
   try {
     if (uriString.startsWith("content://")) {
       mRingerPlayer.setDataSource(this, Uri.parse(uriString));
     } else {
       FileInputStream fis = new FileInputStream(uriString);
       mRingerPlayer.setDataSource(fis.getFD());
     }
   } catch (IOException e) {
     Log.e(e, "Cannot set ringtone");
   }
 }
  public void onCallStateChanged(final LinphoneCall call, final State state, final String message) {
    if (instance == null) {
      Log.i("Service not ready, discarding call state change to ", state.toString());
      return;
    }
    if (state == LinphoneCall.State.IncomingReceived) {
      onIncomingReceived();
    }

    if (state == State.CallUpdatedByRemote) {
      // If the correspondent proposes video while audio call
      boolean remoteVideo = call.getRemoteParams().getVideoEnabled();
      boolean localVideo = call.getCurrentParamsCopy().getVideoEnabled();
      boolean autoAcceptCameraPolicy = LinphoneManager.getInstance().isAutoAcceptCamera();
      if (remoteVideo && !localVideo && !autoAcceptCameraPolicy) {
        try {
          LinphoneManager.getLc().deferCallUpdate(call);

          if (incallListener() != null) incallListener().onCallStateChanged(call, state, message);
        } catch (LinphoneCoreException e) {
          e.printStackTrace();
        }
      }
    }

    if (state == State.StreamsRunning) {
      // Workaround bug current call seems to be updated after state changed to streams running
      //	refreshIncallIcon(call);
      mWifiLock.acquire();
    } else {
      //	refreshIncallIcon(LinphoneManager.getLc().getCurrentCall());
    }
    if ((state == State.CallEnd || state == State.Error)
        && LinphoneManager.getLc().getCallsNb() < 1) {
      mWifiLock.release();
    }
    //		mHandler.post(new Runnable() {
    //			public void run() {
    //				if (guiListener() != null)
    //					guiListener().onCallStateChanged(call, state, message);
    //			}
    //		});
  }
  @Override
  public void onCreate() {
    super.onCreate();

    android.util.Log.d("LinphoneService", "onCreate()");

    // In case restart after a crash. Main in LinphoneActivity
    LinphonePreferenceManager.getInstance(this);

    // Set default preferences
    PreferenceManager.setDefaultValues(this, R.get("xml", "preferences"), true);

    //		mNotificationTitle = getString(R.get("string", "app_name"));

    // Dump some debugging information to the logs
    Log.i(START_LINPHONE_LOGS);
    dumpDeviceInformation();
    dumpInstalledLinphoneInformation();

    //		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    //		mNM.cancel(INCALL_NOTIF_ID); // in case of crash the icon is not removed
    //		mNotif = new Notification(R.get("drawable", "status_level"), "",
    // System.currentTimeMillis());
    //		mNotif.iconLevel=IC_LEVEL_ORANGE;
    //		mNotif.flags |= Notification.FLAG_ONGOING_EVENT;

    //		Intent notifIntent = new Intent();
    //		notifIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    //		notifIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
    // Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    //		notifIntent.setClassName(ALModuleProxy.PKG_NAME, ALModuleProxy.PKG_NAME + "." +
    // ALModuleProxy.ACT_NAME);
    //		notifIntent.setAction(Intent.ACTION_MAIN);
    //		mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, 0);
    //		mNotif.setLatestEventInfo(this, mNotificationTitle,"", mNotifContentIntent);

    LinphoneManager.createAndStart(this, this);
    LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Online);
    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    mWifiLock =
        mWifiManager.createWifiLock(
            WifiManager.WIFI_MODE_FULL_HIGH_PERF, this.getPackageName() + "-wifi-call-lock");
    mWifiLock.setReferenceCounted(false);
    instance = this; // instance is ready once linphone manager has been created

    // Retrieve methods to publish notification and keep Android
    // from killing us and keep the audio quality high.
    if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) {
      try {
        mSetForeground = getClass().getMethod("setForeground", mSetFgSign);
      } catch (NoSuchMethodException e) {
        Log.e(e, "Couldn't find foreground method");
      }
    } else {
      try {
        mStartForeground = getClass().getMethod("startForeground", mStartFgSign);
        mStopForeground = getClass().getMethod("stopForeground", mStopFgSign);
      } catch (NoSuchMethodException e) {
        Log.e(e, "Couldn't find startGoreground or stopForeground");
      }
    }

    //		startForegroundCompat(NOTIF_ID, mNotif);

    LinphoneManager.setOnTextReceivedListener(this);

    if (!mTestDelayElapsed) {
      // Only used when testing. Simulates a 5 seconds delay for launching service
      mHandler.postDelayed(
          new Runnable() {
            @Override
            public void run() {
              mTestDelayElapsed = true;
            }
          },
          5000);
    }
  }