Example usage for android.util Log getStackTraceString

List of usage examples for android.util Log getStackTraceString

Introduction

In this page you can find the example usage for android.util Log getStackTraceString.

Prototype

public static String getStackTraceString(Throwable tr) 

Source Link

Document

Handy function to get a loggable stack trace from a Throwable

Usage

From source file:org.apache.cordova.core.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 *
 * @param id the raw contact id which is required for linking items to the contact
 * @param contact the contact to be saved
 * @param account the account to be saved under
 *///from   w w w  .ja  v  a  2s .  c o  m
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
    // Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
    // But not needed to update existing values.
    int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();

    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    //Add contact type
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());

    // Modify name
    JSONObject name;
    try {
        String displayName = getJsonString(contact, "displayName");
        name = contact.getJSONObject("name");
        if (displayName != null || name != null) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { id,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });

            if (displayName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
            }

            String familyName = getJsonString(name, "familyName");
            if (familyName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
            }
            String middleName = getJsonString(name, "middleName");
            if (middleName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
            }
            String givenName = getJsonString(name, "givenName");
            if (givenName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
            }
            String honorificPrefix = getJsonString(name, "honorificPrefix");
            if (honorificPrefix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
            }
            String honorificSuffix = getJsonString(name, "honorificSuffix");
            if (honorificSuffix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
            }

            ops.add(builder.build());
        }
    } catch (JSONException e1) {
        Log.d(LOG_TAG, "Could not get name");
    }

    // Modify phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            // Delete all the phones
            if (phones.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a phone
            else {
                for (int i = 0; i < phones.length(); i++) {
                    JSONObject phone = (JSONObject) phones.get(i);
                    String phoneId = getJsonString(phone, "id");
                    // This is a new phone so do a DB insert
                    if (phoneId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                getJsonString(phone, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                getPhoneType(getJsonString(phone, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing phone so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Phone._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { phoneId,
                                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        getJsonString(phone, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                        getPhoneType(getJsonString(phone, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Modify emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            // Delete all the emails
            if (emails.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a email
            else {
                for (int i = 0; i < emails.length(); i++) {
                    JSONObject email = (JSONObject) emails.get(i);
                    String emailId = getJsonString(email, "id");
                    // This is a new email so do a DB insert
                    if (emailId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,
                                getJsonString(email, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE,
                                getContactType(getJsonString(email, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing email so do a DB update
                    else {
                        String emailValue = getJsonString(email, "value");
                        if (!emailValue.isEmpty()) {
                            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                    .withSelection(
                                            ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                                    + ContactsContract.Data.MIMETYPE + "=?",
                                            new String[] { emailId,
                                                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                                    .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                                            getJsonString(email, "value"))
                                    .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                            getContactType(getJsonString(email, "type")))
                                    .build());
                        } else {
                            ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                                    .withSelection(
                                            ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                                    + ContactsContract.Data.MIMETYPE + "=?",
                                            new String[] { emailId,
                                                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                                    .build());
                        }
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            // Delete all the addresses
            if (addresses.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a address
            else {
                for (int i = 0; i < addresses.length(); i++) {
                    JSONObject address = (JSONObject) addresses.get(i);
                    String addressId = getJsonString(address, "id");
                    // This is a new address so do a DB insert
                    if (addressId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                getAddressType(getJsonString(address, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                getJsonString(address, "formatted"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                getJsonString(address, "streetAddress"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                getJsonString(address, "locality"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                getJsonString(address, "region"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                getJsonString(address, "postalCode"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                getJsonString(address, "country"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing address so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { addressId,
                                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                        getAddressType(getJsonString(address, "type")))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                        getJsonString(address, "formatted"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                        getJsonString(address, "streetAddress"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                        getJsonString(address, "locality"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                        getJsonString(address, "region"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                        getJsonString(address, "postalCode"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                        getJsonString(address, "country"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Modify organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            // Delete all the organizations
            if (organizations.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a organization
            else {
                for (int i = 0; i < organizations.length(); i++) {
                    JSONObject org = (JSONObject) organizations.get(i);
                    String orgId = getJsonString(org, "id");
                    // This is a new organization so do a DB insert
                    if (orgId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE,
                                getOrgType(getJsonString(org, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                getJsonString(org, "department"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                getJsonString(org, "name"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE,
                                getJsonString(org, "title"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing organization so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Organization._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { orgId,
                                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                                        getOrgType(getJsonString(org, "type")))
                                .withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                        getJsonString(org, "department"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                        getJsonString(org, "name"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                                        getJsonString(org, "title"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Modify IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            // Delete all the ims
            if (ims.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a im
            else {
                for (int i = 0; i < ims.length(); i++) {
                    JSONObject im = (JSONObject) ims.get(i);
                    String imId = getJsonString(im, "id");
                    // This is a new IM so do a DB insert
                    if (imId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
                                getImType(getJsonString(im, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing IM so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Im._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { imId,
                                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Im.TYPE,
                                        getContactType(getJsonString(im, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify note
    String note = getJsonString(contact, "note");
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                    new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());

    // Modify nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Modify urls
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("urls");
        if (websites != null) {
            // Delete all the websites
            if (websites.length() == 0) {
                Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a website
            else {
                for (int i = 0; i < websites.length(); i++) {
                    JSONObject website = (JSONObject) websites.get(i);
                    String websiteId = getJsonString(website, "id");
                    // This is a new website so do a DB insert
                    if (websiteId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Website.DATA,
                                getJsonString(website, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE,
                                getContactType(getJsonString(website, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing website so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Website._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { websiteId,
                                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Website.DATA,
                                        getJsonString(website, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                                        getContactType(getJsonString(website, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Modify birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
                                new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Modify photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            // Delete all the photos
            if (photos.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a photo
            else {
                for (int i = 0; i < photos.length(); i++) {
                    JSONObject photo = (JSONObject) photos.get(i);
                    String photoId = getJsonString(photo, "id");
                    byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
                    // This is a new photo so do a DB insert
                    if (photoId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
                        contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing photo so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Photo._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { photoId,
                                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
                                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;

    //Modify contact
    try {
        mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    }

    // if the save was a success return the contact ID
    if (retVal) {
        return id;
    } else {
        return null;
    }
}

From source file:com.remobile.contacts.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 *
 * @param id the raw contact id which is required for linking items to the contact
 * @param contact the contact to be saved
 * @param account the account to be saved under
 *///from  w  w w  . j  a v a2 s.  c om
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
    // Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
    // But not needed to update existing values.
    int rawId = (Integer.valueOf(getJsonString(contact, "rawId"))).intValue();

    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    //Add contact type
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());

    // Modify name
    JSONObject name;
    try {
        String displayName = getJsonString(contact, "displayName");
        name = contact.getJSONObject("name");
        if (displayName != null || name != null) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { id,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });

            if (displayName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
            }

            String familyName = getJsonString(name, "familyName");
            if (familyName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
            }
            String middleName = getJsonString(name, "middleName");
            if (middleName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
            }
            String givenName = getJsonString(name, "givenName");
            if (givenName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
            }
            String honorificPrefix = getJsonString(name, "honorificPrefix");
            if (honorificPrefix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
            }
            String honorificSuffix = getJsonString(name, "honorificSuffix");
            if (honorificSuffix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
            }

            ops.add(builder.build());
        }
    } catch (JSONException e1) {
        Log.d(LOG_TAG, "Could not get name");
    }

    // Modify phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            // Delete all the phones
            if (phones.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a phone
            else {
                for (int i = 0; i < phones.length(); i++) {
                    JSONObject phone = (JSONObject) phones.get(i);
                    String phoneId = getJsonString(phone, "id");
                    // This is a new phone so do a DB insert
                    if (phoneId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                getJsonString(phone, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                getPhoneType(getJsonString(phone, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing phone so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Phone._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { phoneId,
                                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        getJsonString(phone, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                        getPhoneType(getJsonString(phone, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Modify emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            // Delete all the emails
            if (emails.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a email
            else {
                for (int i = 0; i < emails.length(); i++) {
                    JSONObject email = (JSONObject) emails.get(i);
                    String emailId = getJsonString(email, "id");
                    // This is a new email so do a DB insert
                    if (emailId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,
                                getJsonString(email, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE,
                                getContactType(getJsonString(email, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing email so do a DB update
                    else {
                        String emailValue = getJsonString(email, "value");
                        if (!emailValue.isEmpty()) {
                            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                    .withSelection(
                                            ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                                    + ContactsContract.Data.MIMETYPE + "=?",
                                            new String[] { emailId,
                                                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                                    .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                                            getJsonString(email, "value"))
                                    .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                            getContactType(getJsonString(email, "type")))
                                    .build());
                        } else {
                            ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                                    .withSelection(
                                            ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                                    + ContactsContract.Data.MIMETYPE + "=?",
                                            new String[] { emailId,
                                                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                                    .build());
                        }
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            // Delete all the addresses
            if (addresses.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a address
            else {
                for (int i = 0; i < addresses.length(); i++) {
                    JSONObject address = (JSONObject) addresses.get(i);
                    String addressId = getJsonString(address, "id");
                    // This is a new address so do a DB insert
                    if (addressId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                getAddressType(getJsonString(address, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                getJsonString(address, "formatted"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                getJsonString(address, "streetAddress"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                getJsonString(address, "locality"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                getJsonString(address, "region"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                getJsonString(address, "postalCode"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                getJsonString(address, "country"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing address so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { addressId,
                                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                        getAddressType(getJsonString(address, "type")))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                        getJsonString(address, "formatted"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                        getJsonString(address, "streetAddress"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                        getJsonString(address, "locality"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                        getJsonString(address, "region"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                        getJsonString(address, "postalCode"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                        getJsonString(address, "country"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Modify organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            // Delete all the organizations
            if (organizations.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a organization
            else {
                for (int i = 0; i < organizations.length(); i++) {
                    JSONObject org = (JSONObject) organizations.get(i);
                    String orgId = getJsonString(org, "id");
                    // This is a new organization so do a DB insert
                    if (orgId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE,
                                getOrgType(getJsonString(org, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                getJsonString(org, "department"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                getJsonString(org, "name"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE,
                                getJsonString(org, "title"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing organization so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Organization._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { orgId,
                                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                                        getOrgType(getJsonString(org, "type")))
                                .withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                        getJsonString(org, "department"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                        getJsonString(org, "name"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                                        getJsonString(org, "title"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Modify IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            // Delete all the ims
            if (ims.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a im
            else {
                for (int i = 0; i < ims.length(); i++) {
                    JSONObject im = (JSONObject) ims.get(i);
                    String imId = getJsonString(im, "id");
                    // This is a new IM so do a DB insert
                    if (imId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
                                getImType(getJsonString(im, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing IM so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Im._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { imId,
                                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Im.TYPE,
                                        getContactType(getJsonString(im, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify note
    String note = getJsonString(contact, "note");
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                    new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());

    // Modify nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Modify urls
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("urls");
        if (websites != null) {
            // Delete all the websites
            if (websites.length() == 0) {
                Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a website
            else {
                for (int i = 0; i < websites.length(); i++) {
                    JSONObject website = (JSONObject) websites.get(i);
                    String websiteId = getJsonString(website, "id");
                    // This is a new website so do a DB insert
                    if (websiteId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Website.DATA,
                                getJsonString(website, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE,
                                getContactType(getJsonString(website, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing website so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Website._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { websiteId,
                                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Website.DATA,
                                        getJsonString(website, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                                        getContactType(getJsonString(website, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Modify birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
                                new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Modify photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            // Delete all the photos
            if (photos.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a photo
            else {
                for (int i = 0; i < photos.length(); i++) {
                    JSONObject photo = (JSONObject) photos.get(i);
                    String photoId = getJsonString(photo, "id");
                    byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
                    // This is a new photo so do a DB insert
                    if (photoId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
                        contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing photo so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Photo._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { photoId,
                                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
                                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;

    //Modify contact
    try {
        mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    }

    // if the save was a success return the contact ID
    if (retVal) {
        return id;
    } else {
        return null;
    }
}

From source file:com.master.metehan.filtereagle.ServiceSinkhole.java

@Override
public void onDestroy() {
    Log.i(TAG, "Destroy");

    commandLooper.quit();//from  w  ww.ja v a 2  s  .c  o  m
    logLooper.quit();
    statsLooper.quit();

    if (registeredInteractiveState) {
        unregisterReceiver(interactiveStateReceiver);
        registeredInteractiveState = false;
    }
    if (registeredPowerSave) {
        unregisterReceiver(powerSaveReceiver);
        registeredPowerSave = false;
    }
    if (registeredUser) {
        unregisterReceiver(userReceiver);
        registeredUser = false;
    }
    if (registeredIdleState) {
        unregisterReceiver(idleStateReceiver);
        registeredIdleState = false;
    }
    if (registeredConnectivityChanged) {
        unregisterReceiver(connectivityChangedReceiver);
        registeredConnectivityChanged = false;
    }
    if (registeredPackageAdded) {
        unregisterReceiver(packageAddedReceiver);
        registeredPackageAdded = false;
    }

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            phone_state = false;
        }
    }

    if (subscriptionsChangedListener != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager sm = SubscriptionManager.from(this);
        sm.removeOnSubscriptionsChangedListener(
                (SubscriptionManager.OnSubscriptionsChangedListener) subscriptionsChangedListener);
        subscriptionsChangedListener = null;
    }

    try {
        if (vpn != null) {
            stopNative(vpn, true, true);
            stopVPN(vpn);
            vpn = null;
            unprepare();
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    jni_done();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    super.onDestroy();
}

From source file:com.zhengde163.netguard.ServiceSinkhole.java

@Override
public void onDestroy() {
    Log.i(TAG, "Destroy");

    commandLooper.quit();/*  w ww . ja v a2  s.  c  o m*/
    logLooper.quit();
    statsLooper.quit();

    if (registeredInteractiveState) {
        unregisterReceiver(interactiveStateReceiver);
        registeredInteractiveState = false;
    }
    if (registeredPowerSave) {
        unregisterReceiver(powerSaveReceiver);
        registeredPowerSave = false;
    }
    if (registeredUser) {
        unregisterReceiver(userReceiver);
        registeredUser = false;
    }
    if (registeredIdleState) {
        unregisterReceiver(idleStateReceiver);
        registeredIdleState = false;
    }
    if (registeredConnectivityChanged) {
        unregisterReceiver(connectivityChangedReceiver);
        registeredConnectivityChanged = false;
    }
    if (registeredPackageAdded) {
        unregisterReceiver(packageAddedReceiver);
        registeredPackageAdded = false;
    }

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            phone_state = false;
        }
    }

    if (subscriptionsChangedListener != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager sm = SubscriptionManager.from(this);
        sm.removeOnSubscriptionsChangedListener(
                (SubscriptionManager.OnSubscriptionsChangedListener) subscriptionsChangedListener);
        subscriptionsChangedListener = null;
    }

    try {
        if (vpn != null) {
            stopNative(vpn, true, true);
            stopVPN(vpn);
            vpn = null;
            unprepare();
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    jni_done();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);
    Intent localIntent = new Intent();
    localIntent.setClass(this, ServiceSinkhole.class); //???Service
    this.startService(localIntent);
    super.onDestroy();
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

public void notifyNewApplication(int uid) {
    if (uid < 0)
        return;// w  w  w.  j a va  2s.c o m

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        // Get application name
        String name = TextUtils.join(", ", Util.getApplicationNames(uid, this));

        // Get application info
        PackageManager pm = getPackageManager();
        String[] packages = pm.getPackagesForUid(uid);
        if (packages == null || packages.length < 1)
            throw new PackageManager.NameNotFoundException(Integer.toString(uid));
        boolean internet = Util.hasInternet(uid, this);

        // Build notification
        Intent main = new Intent(this, ActivityMain.class);
        main.putExtra(ActivityMain.EXTRA_REFRESH, true);
        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
        PendingIntent pi = PendingIntent.getActivity(this, uid, main, PendingIntent.FLAG_UPDATE_CURRENT);

        TypedValue tv = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_security_white_24dp).setContentIntent(pi).setColor(tv.data)
                .setAutoCancel(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            builder.setContentTitle(name).setContentText(getString(R.string.msg_installed_n));
        else
            builder.setContentTitle(getString(R.string.app_name))
                    .setContentText(getString(R.string.msg_installed, name));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET);

        // Get defaults
        SharedPreferences prefs_wifi = getSharedPreferences("wifi", Context.MODE_PRIVATE);
        SharedPreferences prefs_other = getSharedPreferences("other", Context.MODE_PRIVATE);
        boolean wifi = prefs_wifi.getBoolean(packages[0], prefs.getBoolean("whitelist_wifi", true));
        boolean other = prefs_other.getBoolean(packages[0], prefs.getBoolean("whitelist_other", true));

        // Build Wi-Fi action
        Intent riWifi = new Intent(this, ServiceSinkhole.class);
        riWifi.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riWifi.putExtra(ServiceSinkhole.EXTRA_NETWORK, "wifi");
        riWifi.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riWifi.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riWifi.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !wifi);

        PendingIntent piWifi = PendingIntent.getService(this, uid, riWifi, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action wAction = new NotificationCompat.Action.Builder(
                wifi ? R.drawable.wifi_on : R.drawable.wifi_off,
                getString(wifi ? R.string.title_allow_wifi : R.string.title_block_wifi), piWifi).build();
        builder.addAction(wAction);

        // Build mobile action
        Intent riOther = new Intent(this, ServiceSinkhole.class);
        riOther.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riOther.putExtra(ServiceSinkhole.EXTRA_NETWORK, "other");
        riOther.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riOther.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riOther.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !other);
        PendingIntent piOther = PendingIntent.getService(this, uid + 10000, riOther,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action oAction = new NotificationCompat.Action.Builder(
                other ? R.drawable.other_on : R.drawable.other_off,
                getString(other ? R.string.title_allow_other : R.string.title_block_other), piOther).build();
        builder.addAction(oAction);

        // Show notification
        if (internet)
            NotificationManagerCompat.from(this).notify(uid, builder.build());
        else {
            NotificationCompat.BigTextStyle expanded = new NotificationCompat.BigTextStyle(builder);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                expanded.bigText(getString(R.string.msg_installed_n));
            else
                expanded.bigText(getString(R.string.msg_installed, name));
            expanded.setSummaryText(getString(R.string.title_internet));
            NotificationManagerCompat.from(this).notify(uid, expanded.build());
        }

    } catch (PackageManager.NameNotFoundException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

@Override
public void onDestroy() {
    Log.i(TAG, "Destroy");

    commandLooper.quit();/*  w w w .j  a  v a 2s  .  co m*/
    logLooper.quit();
    statsLooper.quit();

    if (registeredInteractiveState) {
        unregisterReceiver(interactiveStateReceiver);
        registeredInteractiveState = false;
    }
    if (registeredPowerSave) {
        unregisterReceiver(powerSaveReceiver);
        registeredPowerSave = false;
    }
    if (registeredUser) {
        unregisterReceiver(userReceiver);
        registeredUser = false;
    }
    if (registeredIdleState) {
        unregisterReceiver(idleStateReceiver);
        registeredIdleState = false;
    }
    if (registeredConnectivityChanged) {
        unregisterReceiver(connectivityChangedReceiver);
        registeredConnectivityChanged = false;
    }
    if (registeredPackageAdded) {
        unregisterReceiver(packageAddedReceiver);
        registeredPackageAdded = false;
    }

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            phone_state = false;
        }
    }

    if (subscriptionsChangedListener != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager sm = SubscriptionManager.from(this);
        sm.removeOnSubscriptionsChangedListener(
                (SubscriptionManager.OnSubscriptionsChangedListener) subscriptionsChangedListener);
        subscriptionsChangedListener = null;
    }

    try {
        if (vpn != null) {
            stopNative(vpn, true);
            stopVPN(vpn);
            vpn = null;
            unprepare();
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    jni_done();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    super.onDestroy();
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

@Override
public void onDestroy() {
    Log.i(TAG, "Destroy");

    commandLooper.quit();/*from   ww w  . ja  v a 2  s. co  m*/
    logLooper.quit();
    statsLooper.quit();

    if (registeredInteractiveState) {
        unregisterReceiver(interactiveStateReceiver);
        registeredInteractiveState = false;
    }
    if (registeredPowerSave) {
        unregisterReceiver(powerSaveReceiver);
        registeredPowerSave = false;
    }
    if (registeredUser) {
        unregisterReceiver(userReceiver);
        registeredUser = false;
    }
    if (registeredIdleState) {
        unregisterReceiver(idleStateReceiver);
        registeredIdleState = false;
    }
    if (registeredConnectivityChanged) {
        unregisterReceiver(connectivityChangedReceiver);
        registeredConnectivityChanged = false;
    }
    if (registeredPackageChanged) {
        unregisterReceiver(packageChangedReceiver);
        registeredPackageChanged = false;
    }

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            phone_state = false;
        }
    }

    if (subscriptionsChangedListener != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager sm = SubscriptionManager.from(this);
        sm.removeOnSubscriptionsChangedListener(
                (SubscriptionManager.OnSubscriptionsChangedListener) subscriptionsChangedListener);
        subscriptionsChangedListener = null;
    }

    try {
        if (vpn != null) {
            stopNative(vpn, true);
            stopVPN(vpn);
            vpn = null;
            unprepare();
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    jni_done();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    super.onDestroy();
}

From source file:com.zoffcc.applications.zanavi.Navit.java

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    try {/*from  ww w  .j  a v a2s .  com*/
        System.out.println("XXIIXX(2):111");
        String mid_str = intent.getExtras().getString("com.zoffcc.applications.zanavi.mid");

        System.out.println("XXIIXX(2):111a:mid_str=" + mid_str);

        if (mid_str != null) {
            if (mid_str.equals("201:UPDATE-APP")) {
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
            } else if (mid_str.startsWith("202:UPDATE-MAP:")) {
                // System.out.println("need to update1:" + mid_str);
                // System.out.println("need to update2:" + mid_str.substring(15));

                auto_start_update_map(mid_str.substring(15));
            }
        }

        System.out.println("XXIIXX(2):111b:mid_str=" + mid_str);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("XXIIXX(2):111:EEEE");
    }

    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----
    try {
        System.out.println("XXIIXX(2):" + intent);
        Bundle bundle77 = intent.getExtras();
        System.out.println("XXIIXX(2):" + intent_flags_to_string(intent.getFlags()));
        if (bundle77 == null) {
            System.out.println("XXIIXX(2):" + "null");
        } else {
            for (String key : bundle77.keySet()) {
                Object value = bundle77.get(key);
                System.out.println("XXIIXX(2):"
                        + String.format("%s %s (%s)", key, value.toString(), value.getClass().getName()));
            }
        }
    } catch (Exception ee22) {
        String exst = Log.getStackTraceString(ee22);
        System.out.println("XXIIXX(2):ERR:" + exst);
    }
    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----

    Log.e("Navit", "3:**1**A " + intent.getAction());
    Log.e("Navit", "3:**1**D " + intent.getDataString());
    Log.e("Navit", "3:**1**S " + intent.toString());
    try {
        Log.e("Navit", "3:**1**S " + intent.getExtras().describeContents());
    } catch (Exception ee3) {
    }

    // if (Navit.startup_intent == null)
    {
        try {
            // make a copy of the given intent object
            // Navit.startup_intent = intent.cloneFilter();
            Navit.startup_intent = intent;

            Log.e("Navit", "3a:**1**001");
            Bundle extras2 = intent.getExtras();
            Log.e("Navit", "3a:**1**002");
            try {
                Navit.startup_intent.putExtras(extras2);
                Log.e("Navit", "3a:**1**003");
            } catch (Exception e4) {
                if (startup_intent.getDataString() != null) {
                    // we have a "geo:" thingy intent, use it
                    // or "gpx file"
                    Log.e("Navit", "3c:**1**A " + startup_intent.getAction());
                    Log.e("Navit", "3c:**1**D " + startup_intent.getDataString());
                    Log.e("Navit", "3c:**1**S " + startup_intent.toString());
                } else {
                    Log.e("Navit", "3X:**1**X ");
                    Navit.startup_intent = null;
                }

                // hack! remeber timstamp, and only allow 4 secs. later in onResume to set target!
                Navit.startup_intent_timestamp = System.currentTimeMillis();

                return;
            }

            // Intent { act=android.intent.action.VIEW
            // cat=[android.intent.category.DEFAULT]
            // dat=file:///mnt/sdcard/zanavi_pos_recording_347834278.gpx
            // cmp=com.zoffcc.applications.zanavi/.Navit }

            // hack! remeber timstamp, and only allow 4 secs. later in onResume to set target!
            Navit.startup_intent_timestamp = System.currentTimeMillis();
            Log.e("Navit", "3a:**1**A " + startup_intent.getAction());
            Log.e("Navit", "3a:**1**D " + startup_intent.getDataString());
            Log.e("Navit", "3a:**1**S " + startup_intent.toString());
            if (extras2 != null) {
                long l = extras2.getLong("com.zoffcc.applications.zanavi.ZANAVI_INTENT_type");
                // System.out.println("DH:a007 l=" + l);
                if (l != 0L) {
                    if (l == Navit.NAVIT_START_INTENT_DRIVE_HOME) {
                        // Log.e("Navit", "2:**1** started via drive home");
                        // we have been called from "drive home" widget

                        // drive home

                        // check if we have a home location
                        int home_id = find_home_point();

                        if (home_id != -1) {
                            Message msg7 = progress_handler.obtainMessage();
                            Bundle b7 = new Bundle();
                            msg7.what = 2; // long Toast message
                            b7.putString("text", Navit.get_text("driving to Home Location")); //TRANS
                            msg7.setData(b7);
                            progress_handler.sendMessage(msg7);

                            // clear any previous destinations
                            Message msg2 = new Message();
                            Bundle b2 = new Bundle();
                            b2.putInt("Callback", 7);
                            msg2.setData(b2);
                            NavitGraphics.callback_handler.sendMessage(msg2);

                            // set position to middle of screen -----------------------
                            // set position to middle of screen -----------------------
                            // set position to middle of screen -----------------------
                            //               Message msg67 = new Message();
                            //               Bundle b67 = new Bundle();
                            //               b67.putInt("Callback", 51);
                            //               b67.putInt("x", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getWidth() / 2));
                            //               b67.putInt("y", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getHeight() / 2));
                            //               msg67.setData(b67);
                            //               N_NavitGraphics.callback_handler.sendMessage(msg67);
                            // set position to middle of screen -----------------------
                            // set position to middle of screen -----------------------
                            // set position to middle of screen -----------------------

                            try {
                                Thread.sleep(60);
                            } catch (Exception e) {
                            }

                            route_wrapper(map_points.get(home_id).point_name, 0, 0, false,
                                    map_points.get(home_id).lat, map_points.get(home_id).lon, true);

                            //                        Navit.destination_set();
                            //
                            //                        // set destination to home location
                            //                        String lat = String.valueOf(map_points.get(home_id).lat);
                            //                        String lon = String.valueOf(map_points.get(home_id).lon);
                            //                        String q = map_points.get(home_id).point_name;
                            //
                            //                        // System.out.println("lat=" + lat + " lon=" + lon + " name=" + q);
                            //
                            //                        Message msg55 = new Message();
                            //                        Bundle b55 = new Bundle();
                            //                        b55.putInt("Callback", 3);
                            //                        b55.putString("lat", lat);
                            //                        b55.putString("lon", lon);
                            //                        b55.putString("q", q);
                            //                        msg55.setData(b55);
                            //                        NavitGraphics.callback_handler.sendMessage(msg55);

                            final Thread zoom_to_route_001 = new Thread() {
                                int wait = 1;
                                int count = 0;
                                int max_count = 60;

                                @Override
                                public void run() {
                                    while (wait == 1) {
                                        try {
                                            if ((NavitGraphics.navit_route_status == 17)
                                                    || (NavitGraphics.navit_route_status == 33)) {
                                                zoom_to_route();
                                                wait = 0;
                                            } else {
                                                wait = 1;
                                            }

                                            count++;
                                            if (count > max_count) {
                                                wait = 0;
                                            } else {
                                                Thread.sleep(400);
                                            }
                                        } catch (Exception e) {
                                        }
                                    }
                                }
                            };
                            zoom_to_route_001.start();

                            //               try
                            //               {
                            //                  show_geo_on_screen(Float.parseFloat(lat), Float.parseFloat(lon));
                            //               }
                            //               catch (Exception e2)
                            //               {
                            //                  e2.printStackTrace();
                            //               }

                            try {
                                Navit.follow_button_on();
                            } catch (Exception e2) {
                                e2.printStackTrace();
                            }
                        } else {
                            // no home location set
                            Message msg = progress_handler.obtainMessage();
                            Bundle b = new Bundle();
                            msg.what = 2; // long Toast message
                            b.putString("text", Navit.get_text("No Home Location set")); //TRANS
                            msg.setData(b);
                            progress_handler.sendMessage(msg);
                        }

                    }
                } else {
                    if (startup_intent.getDataString() != null) {
                        // we have a "geo:" thingy intent, use it
                        // or "gpx file"
                    } else {
                        Navit.startup_intent = null;
                    }
                }
            } else {
                if (startup_intent.getDataString() != null) {
                    // we have a "geo:" thingy intent, use it
                } else {
                    Navit.startup_intent = null;
                }
            }
        } catch (Exception e99) {
            Navit.startup_intent = null;
        }

    }

}

From source file:com.zoffcc.applications.zanavi.Navit.java

@SuppressLint("NewApi")
@Override/*from   ww  w  . j  a v a 2s  .c  o m*/
public void onResume() {
    // if (Navit.METHOD_DEBUG) Navit.my_func_name(0);

    // System.gc();
    super.onResume();

    //      // --- alive timestamp ---
    //      app_status_lastalive = System.currentTimeMillis();
    //      System.out.println("app_status_string set:[onResume]:app_status_lastalive=" + app_status_lastalive);
    //      PreferenceManager.getDefaultSharedPreferences(this).edit().putLong(PREF_KEY_LASTALIVE, app_status_lastalive).commit();
    //      // --- alive timestamp ---

    // hide main progress bar ------------
    if (Navit.progressbar_main_activity.getVisibility() == View.VISIBLE) {
        Navit.progressbar_main_activity.setProgress(0);
        Navit.progressbar_main_activity.setVisibility(View.GONE);
    }
    // hide main progress bar ------------

    try {
        sensorManager.registerListener(lightSensorEventListener, lightSensor, (int) (8 * 1000000)); // updates approx. every 8 seconds
    } catch (Exception e) {
    }

    // get the intent fresh !! ----------
    startup_intent = this.getIntent();
    // get the intent fresh !! ----------

    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------
    try {
        intro_flag_nomaps = false;
        if (!have_maps_installed()) {
            if ((!NavitMapDownloader.download_active) && (!NavitMapDownloader.download_active_start)) {
                intro_flag_nomaps = true;
            }
        }
    } catch (Exception e) {
    }

    try {
        intro_flag_indexmissing = false;
        allow_use_index_search();
        if (Navit_index_on_but_no_idx_files) {
            if (!NavitMapDownloader.download_active_start) {
                intro_flag_indexmissing = true;
            }
        }

    } catch (Exception e) {
    }

    intro_flag_firststart = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PREF_KEY_FIRST_START,
            true);
    if (intro_flag_firststart) {
        intro_flag_update = false;
    }

    if (EasyPermissions.hasPermissions(this, perms)) {
        // have permissions!
        intro_flag_permissions = false;
    } else {
        // ask for permissions
        intro_flag_permissions = true;
    }

    // only show in onCreate() ------
    //      if (intro_show_count > 0)
    //      {
    //         intro_flag_info = false;
    //         intro_flag_firststart = false;
    //         intro_flag_update = false;
    //      }
    // only show in onCreate() ------

    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------
    // ------------- get all the flags for intro pages -------------

    // -------------- INTRO --------------
    // -------------- INTRO --------------
    // -------------- INTRO --------------
    if (Navit.CIDEBUG == 0) // -MAT-INTRO-
    {
        //         intro_flag_nomaps = true;
        //         intro_flag_info = true;
        //         intro_flag_firststart = false;
        //         intro_flag_update = false;
        //         intro_flag_indexmissing = false;
        //        intro_flag_crash = true;

        if (intro_flag_crash || intro_flag_firststart || intro_flag_indexmissing || intro_flag_info
                || intro_flag_nomaps || intro_flag_permissions || intro_flag_update) {

            System.out.println("flags=" + "intro_flag_crash:" + intro_flag_crash + " intro_flag_firststart:"
                    + intro_flag_firststart + " intro_flag_indexmissing:" + intro_flag_indexmissing
                    + " intro_flag_info:" + intro_flag_info + " intro_flag_nomaps:" + intro_flag_nomaps
                    + " intro_flag_permissions:" + intro_flag_permissions + " intro_flag_update:"
                    + intro_flag_update);

            // intro pages
            System.out.println("ZANaviMainIntroActivity:" + "start count=" + intro_show_count);
            intro_show_count++;
            Intent intent = new Intent(this, ZANaviMainIntroActivityStatic.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivityForResult(intent, ZANaviIntro_id);
        }
    }
    //      // -------------- INTRO --------------
    //      // -------------- INTRO --------------
    //      // -------------- INTRO --------------

    PackageInfo pkgInfo;
    Navit_Plugin_001_Installed = false;
    try {
        // is the donate version installed?
        pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_msg", 0);
        String sharedUserId = pkgInfo.sharedUserId;
        System.out.println("str nd=" + sharedUserId);
        if (sharedUserId.equals("com.zoffcc.applications.zanavi")) {
            System.out.println("##plugin 001##");
            Navit_Plugin_001_Installed = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----

    try {
        System.out.println("XXIIXX:111");
        String mid_str = this.getIntent().getExtras().getString("com.zoffcc.applications.zanavi.mid");
        System.out.println("XXIIXX:111a:mid_str=" + mid_str);

        if (mid_str != null) {
            if (mid_str.equals("201:UPDATE-APP")) {
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
                // a new ZANavi version is available, show something to the user here -------------------
            } else if (mid_str.startsWith("202:UPDATE-MAP:")) {
                System.out.println("need to update1:" + mid_str);
                System.out.println("need to update2:" + mid_str.substring(15));

                auto_start_update_map(mid_str.substring(15));
            }
        }

        System.out.println("XXIIXX:111b:mid_str=" + mid_str);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("XXIIXX:111:EEEE");
    }

    try {
        System.out.println("XXIIXX:" + this.getIntent());
        Bundle bundle77 = this.getIntent().getExtras();
        System.out.println("XXIIXX:" + intent_flags_to_string(this.getIntent().getFlags()));
        if (bundle77 == null) {
            System.out.println("XXIIXX:" + "null");
        } else {
            for (String key : bundle77.keySet()) {
                Object value = bundle77.get(key);
                System.out.println("XXIIXX:"
                        + String.format("%s %s (%s)", key, value.toString(), value.getClass().getName()));
            }
        }
    } catch (Exception ee22) {
        String exst = Log.getStackTraceString(ee22);
        System.out.println("XXIIXX:ERR:" + exst);
    }
    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----
    // ---- Intent dump ----

    is_paused = false;

    Navit_doubleBackToExitPressedOnce = false;

    app_window = getWindow();

    Log.e("Navit", "OnResume");

    while (Global_Init_Finished == 0) {
        Log.e("Navit", "OnResume:Global_Init_Finished==0 !!!!!");
        try {
            Thread.sleep(30, 0); // sleep
        } catch (InterruptedException e) {
        }
    }

    //InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    cwthr.NavitActivity2(1);

    try {
        NSp.resume_me();
    } catch (Exception e) {
        e.printStackTrace();
    }

    NavitVehicle.turn_on_sat_status();

    try {
        if (wl != null) {
            //            try
            //            {
            //               wl.release();
            //            }
            //            catch (Exception e2)
            //            {
            //            }
            wl.acquire();
            Log.e("Navit", "WakeLock: acquire 2");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Intent caller = this.getIntent();
    //System.out.println("A=" + caller.getAction() + " D=" + caller.getDataString());
    //System.out.println("C=" + caller.getComponent().flattenToString());

    if (unsupported) {
        class CustomListener implements View.OnClickListener {
            private final Dialog dialog;

            public CustomListener(Dialog dialog) {
                this.dialog = dialog;
            }

            @Override
            public void onClick(View v) {

                // Do whatever you want here

                // If you want to close the dialog, uncomment the line below
                //dialog.dismiss();
            }
        }

        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("WeltBild Tablet");
        dialog.setCancelable(false);
        dialog.setMessage("Your device is not supported!");
        dialog.show();
        //Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        //theButton.setOnClickListener(new CustomListener(dialog));
    }

    // reset "maps too old" flag
    Navit_maps_too_old = false;

    if (Navit_maps_loaded == false) {
        Navit_maps_loaded = true;
        // activate all maps
        Log.e("Navit", "**** LOAD ALL MAPS **** start");
        Message msg3 = new Message();
        Bundle b3 = new Bundle();
        b3.putInt("Callback", 20);
        msg3.setData(b3);
        NavitGraphics.callback_handler.sendMessage(msg3);
        Log.e("Navit", "**** LOAD ALL MAPS **** end");
    }

    try {
        NavitGraphics.no_maps_container.setVisibility(View.INVISIBLE);

        //         if (!have_maps_installed())
        //         {
        //            // System.out.println("MMMM=no maps installed");
        //            // show semi transparent box "no maps installed" ------------------
        //            // show semi transparent box "no maps installed" ------------------
        //            NavitGraphics.no_maps_container.setVisibility(View.VISIBLE);
        //            try
        //            {
        //               NavitGraphics.no_maps_container.setActivated(true);
        //            }
        //            catch (NoSuchMethodError e)
        //            {
        //            }
        //
        //            show_case_001();
        //
        //            // show semi transparent box "no maps installed" ------------------
        //            // show semi transparent box "no maps installed" ------------------
        //         }
        //         else
        //         {
        //            NavitGraphics.no_maps_container.setVisibility(View.INVISIBLE);
        //            try
        //            {
        //               NavitGraphics.no_maps_container.setActivated(false);
        //            }
        //            catch (NoSuchMethodError e)
        //            {
        //            }
        //         }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        // draw map no-async
        Message msg = new Message();
        Bundle b = new Bundle();
        b.putInt("Callback", 64);
        msg.setData(b);
        NavitGraphics.callback_handler.sendMessage(msg);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String intent_data = null;
    try {
        //Log.e("Navit", "**9**A " + startup_intent.getAction());
        //Log.e("Navit", "**9**D " + startup_intent.getDataString());

        int type = 1; // default = assume it's a map coords intent

        try {
            String si = startup_intent.getDataString();
            String tmp2 = si.split(":", 2)[0];
            Log.e("Navit", "**9a**A " + startup_intent.getAction());
            Log.e("Navit", "**9a**D " + startup_intent.getDataString() + " " + tmp2);
            if (tmp2.equals("file")) {
                Log.e("Navit", "**9b**D " + startup_intent.getDataString() + " " + tmp2);
                if (si.toLowerCase().endsWith(".gpx")) {
                    Log.e("Navit", "**9c**D " + startup_intent.getDataString() + " " + tmp2);
                    type = 4;
                }
            }
        } catch (Exception e2) {
        }

        if (type != 4) {
            Bundle extras = startup_intent.getExtras();
            // System.out.println("DH:001");
            if (extras != null) {
                // System.out.println("DH:002");
                long l = extras.getLong("com.zoffcc.applications.zanavi.ZANAVI_INTENT_type");
                // System.out.println("DH:003 l=" + l);
                if (l != 0L) {
                    // System.out.println("DH:004");
                    if (l == Navit.NAVIT_START_INTENT_DRIVE_HOME) {
                        // System.out.println("DH:005");
                        type = 2; // call from drive-home-widget
                    }
                    // ok, now remove that key
                    extras.remove("com.zoffcc.applications.zanavi");
                    startup_intent.replaceExtras((Bundle) null);
                    // System.out.println("DH:006");
                }
            }
        }

        // ------------------------  BIG LOOP  ------------------------
        // ------------------------  BIG LOOP  ------------------------
        if (type == 2) {
            // drive home

            // check if we have a home location
            int home_id = find_home_point();

            if (home_id != -1) {
                Message msg7 = progress_handler.obtainMessage();
                Bundle b7 = new Bundle();
                msg7.what = 2; // long Toast message
                b7.putString("text", Navit.get_text("driving to Home Location")); //TRANS
                msg7.setData(b7);
                progress_handler.sendMessage(msg7);

                // clear any previous destinations
                Message msg2 = new Message();
                Bundle b2 = new Bundle();
                b2.putInt("Callback", 7);
                msg2.setData(b2);
                NavitGraphics.callback_handler.sendMessage(msg2);

                // set position to middle of screen -----------------------
                // set position to middle of screen -----------------------
                // set position to middle of screen -----------------------
                //               Message msg67 = new Message();
                //               Bundle b67 = new Bundle();
                //               b67.putInt("Callback", 51);
                //               b67.putInt("x", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getWidth() / 2));
                //               b67.putInt("y", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getHeight() / 2));
                //               msg67.setData(b67);
                //               N_NavitGraphics.callback_handler.sendMessage(msg67);
                // set position to middle of screen -----------------------
                // set position to middle of screen -----------------------
                // set position to middle of screen -----------------------

                try {
                    Thread.sleep(60);
                } catch (Exception e) {
                }

                Navit.destination_set();

                // set destination to home location
                //               String lat = String.valueOf(map_points.get(home_id).lat);
                //               String lon = String.valueOf(map_points.get(home_id).lon);
                //               String q = map_points.get(home_id).point_name;
                route_wrapper(map_points.get(home_id).point_name, 0, 0, false, map_points.get(home_id).lat,
                        map_points.get(home_id).lon, true);

                final Thread zoom_to_route_001 = new Thread() {
                    int wait = 1;
                    int count = 0;
                    int max_count = 60;

                    @Override
                    public void run() {
                        while (wait == 1) {
                            try {
                                if ((NavitGraphics.navit_route_status == 17)
                                        || (NavitGraphics.navit_route_status == 33)) {
                                    zoom_to_route();
                                    wait = 0;
                                } else {
                                    wait = 1;
                                }

                                count++;
                                if (count > max_count) {
                                    wait = 0;
                                } else {
                                    Thread.sleep(400);
                                }
                            } catch (Exception e) {
                            }
                        }
                    }
                };
                zoom_to_route_001.start();

                //               try
                //               {
                //                  show_geo_on_screen(Float.parseFloat(lat), Float.parseFloat(lon));
                //               }
                //               catch (Exception e2)
                //               {
                //                  e2.printStackTrace();
                //               }

                try {
                    Navit.follow_button_on();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            } else {
                // no home location set
                Message msg = progress_handler.obtainMessage();
                Bundle b = new Bundle();
                msg.what = 2; // long Toast message
                b.putString("text", Navit.get_text("No Home Location set")); //TRANS
                msg.setData(b);
                progress_handler.sendMessage(msg);
            }
        } else if (type == 4) {

            if (startup_intent != null) {
                // Log.e("Navit", "**7**A " + startup_intent.getAction() + System.currentTimeMillis() + " " + Navit.startup_intent_timestamp);
                if (System.currentTimeMillis() <= Navit.startup_intent_timestamp + 4000L) {
                    Log.e("Navit", "**7**A " + startup_intent.getAction());
                    Log.e("Navit", "**7**D " + startup_intent.getDataString());
                    intent_data = startup_intent.getDataString();
                    try {
                        intent_data = java.net.URLDecoder.decode(intent_data, "UTF-8");
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                    // we consumed the intent, so reset timestamp value to avoid double consuming of event
                    Navit.startup_intent_timestamp = 0L;

                    if (intent_data != null) {
                        // file:///mnt/sdcard/zanavi_pos_recording_347834278.gpx
                        String tmp1;
                        tmp1 = intent_data.split(":", 2)[1].substring(2);

                        Log.e("Navit", "**7**f=" + tmp1);

                        // convert gpx file ---------------------
                        convert_gpx_file_real(tmp1);
                    }
                }
            }
        } else if (type == 1) {
            if (startup_intent != null) {
                if (System.currentTimeMillis() <= Navit.startup_intent_timestamp + 4000L) {
                    Log.e("Navit", "**2**A " + startup_intent.getAction());
                    Log.e("Navit", "**2**D " + startup_intent.getDataString());
                    intent_data = startup_intent.getDataString();
                    // we consumed the intent, so reset timestamp value to avoid double consuming of event
                    Navit.startup_intent_timestamp = 0L;

                    if (intent_data != null) {
                        // set position to middle of screen -----------------------
                        // set position to middle of screen -----------------------
                        // set position to middle of screen -----------------------
                        //                     Message msg67 = new Message();
                        //                     Bundle b67 = new Bundle();
                        //                     b67.putInt("Callback", 51);
                        //                     b67.putInt("x", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getWidth() / 2));
                        //                     b67.putInt("y", (int) (NavitGraphics.Global_dpi_factor * Navit.NG__map_main.view.getHeight() / 2));
                        //                     msg67.setData(b67);
                        //                     N_NavitGraphics.callback_handler.sendMessage(msg67);
                        // set position to middle of screen -----------------------
                        // set position to middle of screen -----------------------
                        // set position to middle of screen -----------------------
                    }
                } else {
                    Log.e("Navit", "timestamp for navigate_to expired! not using data");
                }
            }

            System.out.println("SUI:000a " + intent_data);

            if ((intent_data != null) && ((substring_without_ioobe(intent_data, 0, 18)
                    .equals("google.navigation:"))
                    || (substring_without_ioobe(intent_data, 0, 23).equals("http://maps.google.com/"))
                    || (substring_without_ioobe(intent_data, 0, 24).equals("https://maps.google.com/")))) {

                System.out.println("SUI:000b");

                // better use regex later, but for now to test this feature its ok :-)
                // better use regex later, but for now to test this feature its ok :-)

                // g: google.navigation:///?ll=49.4086,17.4855&entry=w&opt=
                // d: google.navigation:q=blabla-strasse # (this happens when you are offline, or from contacts)
                // b: google.navigation:q=48.25676,16.643
                // a: google.navigation:ll=48.25676,16.643&q=blabla-strasse
                // e: google.navigation:ll=48.25676,16.643&title=blabla-strasse
                //    sample: -> google.navigation:ll=48.026096,16.023993&title=N%C3%B6stach+43%2C+2571+N%C3%B6stach&entry=w
                //            -> google.navigation:ll=48.014413,16.005579&title=Hainfelder+Stra%C3%9Fe+44%2C+2571%2C+Austria&entry=w
                // f: google.navigation:ll=48.25676,16.643&...
                // c: google.navigation:ll=48.25676,16.643
                // h: http://maps.google.com/?q=48.222210,16.387058&z=16
                // i: https://maps.google.com/?q=48.222210,16.387058&z=16
                // i:,h: https://maps.google.com/maps/place?ftid=0x476d07075e933fc5:0xccbeba7fe1e3dd36&q=48.222210,16.387058&ui=maps_mini
                //
                // ??!!new??!!: http://maps.google.com/?cid=10549738100504591748&hl=en&gl=gb

                String lat;
                String lon;
                String q;

                String temp1 = null;
                String temp2 = null;
                String temp3 = null;
                boolean parsable = false;
                boolean unparsable_info_box = true;
                try {
                    intent_data = java.net.URLDecoder.decode(intent_data, "UTF-8");
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                // DEBUG
                // DEBUG
                // DEBUG
                // intent_data = "google.navigation:q=Wien Burggasse 27";
                // intent_data = "google.navigation:q=48.25676,16.643";
                // intent_data = "google.navigation:ll=48.25676,16.643&q=blabla-strasse";
                // intent_data = "google.navigation:ll=48.25676,16.643";
                // DEBUG
                // DEBUG
                // DEBUG

                try {
                    Log.e("Navit", "found DEBUG 1: " + intent_data.substring(0, 20));
                    Log.e("Navit", "found DEBUG 2: " + intent_data.substring(20, 22));
                    Log.e("Navit", "found DEBUG 3: " + intent_data.substring(20, 21));
                    Log.e("Navit", "found DEBUG 4: " + intent_data.split("&").length);
                    Log.e("Navit", "found DEBUG 4.1: yy"
                            + intent_data.split("&")[1].substring(0, 1).toLowerCase() + "yy");
                    Log.e("Navit", "found DEBUG 5: xx" + intent_data.split("&")[1] + "xx");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (!Navit.NavitStartupAlreadySearching) {
                    if (intent_data.length() > 19) {
                        // if h: then show target
                        if (substring_without_ioobe(intent_data, 0, 23).equals("http://maps.google.com/")) {
                            Uri uri = Uri.parse(intent_data);
                            Log.e("Navit", "target found (h): " + uri.getQueryParameter("q"));
                            parsable = true;
                            intent_data = "google.navigation:ll=" + uri.getQueryParameter("q") + "&q=Target";
                        }
                        // if i: then show target
                        else if (substring_without_ioobe(intent_data, 0, 24)
                                .equals("https://maps.google.com/")) {
                            Uri uri = Uri.parse(intent_data);
                            Log.e("Navit", "target found (i): " + uri.getQueryParameter("q"));
                            parsable = true;
                            intent_data = "google.navigation:ll=" + uri.getQueryParameter("q") + "&q=Target";
                        }
                        // if d: then start target search
                        else if ((substring_without_ioobe(intent_data, 0, 20).equals("google.navigation:q="))
                                && ((!substring_without_ioobe(intent_data, 20, 21).equals('+'))
                                        && (!substring_without_ioobe(intent_data, 20, 21).equals('-'))
                                        && (!substring_without_ioobe(intent_data, 20, 22)
                                                .matches("[0-9][0-9]")))) {
                            Log.e("Navit", "target found (d): " + intent_data.split("q=", -1)[1]);
                            Navit.NavitStartupAlreadySearching = true;
                            start_targetsearch_from_intent(intent_data.split("q=", -1)[1]);
                            // dont use this here, already starting search, so set to "false"
                            parsable = false;
                            unparsable_info_box = false;
                        }
                        // if b: then remodel the input string to look like a:
                        else if (substring_without_ioobe(intent_data, 0, 20).equals("google.navigation:q=")) {
                            intent_data = "ll=" + intent_data.split("q=", -1)[1] + "&q=Target";
                            Log.e("Navit", "target found (b): " + intent_data);
                            parsable = true;
                        }
                        // if g: [google.navigation:///?ll=49.4086,17.4855&...] then remodel the input string to look like a:
                        else if (substring_without_ioobe(intent_data, 0, 25)
                                .equals("google.navigation:///?ll=")) {
                            intent_data = "google.navigation:ll="
                                    + intent_data.split("ll=", -1)[1].split("&", -1)[0] + "&q=Target";
                            Log.e("Navit", "target found (g): " + intent_data);
                            parsable = true;
                        }
                        // if e: then remodel the input string to look like a:
                        else if ((substring_without_ioobe(intent_data, 0, 21).equals("google.navigation:ll="))
                                && (intent_data.split("&").length > 1)
                                && (substring_without_ioobe(intent_data.split("&")[1], 0, 1).toLowerCase()
                                        .equals("f"))) {
                            int idx = intent_data.indexOf("&");
                            intent_data = substring_without_ioobe(intent_data, 0, idx) + "&q=Target";
                            Log.e("Navit", "target found (e): " + intent_data);
                            parsable = true;
                        }
                        // if f: then remodel the input string to look like a:
                        else if ((substring_without_ioobe(intent_data, 0, 21).equals("google.navigation:ll="))
                                && (intent_data.split("&").length > 1)) {
                            int idx = intent_data.indexOf("&");
                            intent_data = intent_data.substring(0, idx) + "&q=Target";
                            Log.e("Navit", "target found (f): " + intent_data);
                            parsable = true;
                        }
                        // already looks like a: just set flag
                        else if ((substring_without_ioobe(intent_data, 0, 21).equals("google.navigation:ll="))
                                && (intent_data.split("&q=").length > 1)) {
                            // dummy, just set the flag
                            Log.e("Navit", "target found (a): " + intent_data);
                            Log.e("Navit", "target found (a): " + intent_data.split("&q=").length);
                            parsable = true;
                        }
                        // if c: then remodel the input string to look like a:
                        else if ((substring_without_ioobe(intent_data, 0, 21).equals("google.navigation:ll="))
                                && (intent_data.split("&q=").length < 2)) {

                            intent_data = intent_data + "&q=Target";
                            Log.e("Navit", "target found (c): " + intent_data);
                            parsable = true;
                        }
                    }
                } else {
                    Log.e("Navit", "already started search from startup intent");
                    parsable = false;
                    unparsable_info_box = false;
                }

                if (parsable) {
                    // now string should be in form --> a:
                    // now split the parts off
                    temp1 = intent_data.split("&q=", -1)[0];
                    try {
                        temp3 = temp1.split("ll=", -1)[1];
                        temp2 = intent_data.split("&q=", -1)[1];
                    } catch (Exception e) {
                        // java.lang.ArrayIndexOutOfBoundsException most likely
                        // so let's assume we dont have '&q=xxxx'
                        temp3 = temp1;
                    }

                    if (temp2 == null) {
                        // use some default name
                        temp2 = "Target";
                    }

                    lat = temp3.split(",", -1)[0];
                    lon = temp3.split(",", -1)[1];
                    q = temp2;
                    // is the "search name" url-encoded? i think so, lets url-decode it here
                    q = URLDecoder.decode(q);
                    // System.out.println();

                    Navit.remember_destination(q, lat, lon);
                    Navit.destination_set();

                    Message msg = new Message();
                    Bundle b = new Bundle();
                    b.putInt("Callback", 3);
                    b.putString("lat", lat);
                    b.putString("lon", lon);
                    b.putString("q", q);
                    msg.setData(b);
                    NavitGraphics.callback_handler.sendMessage(msg);

                    final Thread zoom_to_route_002 = new Thread() {
                        int wait = 1;
                        int count = 0;
                        int max_count = 60;

                        @Override
                        public void run() {
                            while (wait == 1) {
                                try {
                                    if ((NavitGraphics.navit_route_status == 17)
                                            || (NavitGraphics.navit_route_status == 33)) {
                                        zoom_to_route();
                                        wait = 0;
                                    } else {
                                        wait = 1;
                                    }

                                    count++;
                                    if (count > max_count) {
                                        wait = 0;
                                    } else {
                                        Thread.sleep(400);
                                    }
                                } catch (Exception e) {
                                }
                            }
                        }
                    };
                    zoom_to_route_002.start();

                    //                  try
                    //                  {
                    //                     Thread.sleep(400);
                    //                  }
                    //                  catch (InterruptedException e)
                    //                  {
                    //                  }
                    //
                    //                  //                  try
                    //                  //                  {
                    //                  //                     show_geo_on_screen(Float.parseFloat(lat), Float.parseFloat(lon));
                    //                  //                  }
                    //                  //                  catch (Exception e2)
                    //                  //                  {
                    //                  //                     e2.printStackTrace();
                    //                  //                  }

                    try {
                        Navit.follow_button_on();
                    } catch (Exception e2)

                    {
                        e2.printStackTrace();
                    }
                } else {
                    if (unparsable_info_box && !searchBoxShown) {
                        try {
                            searchBoxShown = true;
                            String searchString = intent_data.split("q=")[1];
                            searchString = searchString.split("&")[0];
                            searchString = URLDecoder.decode(searchString); // decode the URL: e.g. %20 -> space
                            Log.e("Navit", "Search String :" + searchString);
                            executeSearch(searchString);
                        } catch (Exception e) {
                            // safety net
                            try {
                                Log.e("Navit", "problem with startup search 7 str=" + intent_data);
                            } catch (Exception e2) {
                                e2.printStackTrace();
                            }
                        }
                    }
                }
            } else if ((intent_data != null)
                    && (substring_without_ioobe(intent_data, 0, 10).equals("geo:0,0?q="))) {
                // g: geo:0,0?q=wien%20burggasse

                System.out.println("SUI:001");

                boolean parsable = false;
                boolean unparsable_info_box = true;
                try {
                    intent_data = java.net.URLDecoder.decode(intent_data, "UTF-8");
                } catch (Exception e1) {
                    e1.printStackTrace();

                }

                System.out.println("SUI:002");

                if (!Navit.NavitStartupAlreadySearching) {
                    if (intent_data.length() > 10) {
                        // if g: then start target search
                        Log.e("Navit", "target found (g): " + intent_data.split("q=", -1)[1]);
                        Navit.NavitStartupAlreadySearching = true;
                        start_targetsearch_from_intent(intent_data.split("q=", -1)[1]);
                        // dont use this here, already starting search, so set to "false"
                        parsable = false;
                        unparsable_info_box = false;
                    }
                } else {
                    Log.e("Navit", "already started search from startup intent");
                    parsable = false;
                    unparsable_info_box = false;
                }

                if (unparsable_info_box && !searchBoxShown) {
                    try {
                        searchBoxShown = true;
                        String searchString = intent_data.split("q=")[1];
                        searchString = searchString.split("&")[0];
                        searchString = URLDecoder.decode(searchString); // decode the URL: e.g. %20 -> space
                        Log.e("Navit", "Search String :" + searchString);
                        executeSearch(searchString);
                    } catch (Exception e) {
                        // safety net
                        try {
                            Log.e("Navit", "problem with startup search 88 str=" + intent_data);
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                    }
                }

            } else if ((intent_data != null) && (substring_without_ioobe(intent_data, 0, 4).equals("geo:"))) {
                // g: geo:16.8,46.3?z=15

                System.out.println("SUI:002a");

                boolean parsable = false;
                boolean unparsable_info_box = true;

                String tmp1;
                String tmp2;
                String tmp3;
                float lat1 = 0;
                float lon1 = 0;
                int zoom1 = 15;

                try {
                    intent_data = java.net.URLDecoder.decode(intent_data, "UTF-8");
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                if (!Navit.NavitStartupAlreadySearching) {
                    try {
                        tmp1 = intent_data.split(":", 2)[1];
                        tmp2 = tmp1.split("\\?", 2)[0];
                        tmp3 = tmp1.split("\\?", 2)[1];
                        lat1 = Float.parseFloat(tmp2.split(",", 2)[0]);
                        lon1 = Float.parseFloat(tmp2.split(",", 2)[1]);
                        zoom1 = Integer.parseInt(tmp3.split("z=", 2)[1]);
                        parsable = true;
                    } catch (Exception e4) {
                        e4.printStackTrace();
                    }
                }

                if (parsable) {
                    // geo: intent -> only show destination on map!

                    // set nice zoomlevel before we show destination
                    //                  int zoom_want = zoom1;
                    //                  //
                    //                  Message msg = new Message();
                    //                  Bundle b = new Bundle();
                    //                  b.putInt("Callback", 33);
                    //                  b.putString("s", Integer.toString(zoom_want));
                    //                  msg.setData(b);
                    //                  try
                    //                  {
                    //                     N_NavitGraphics.callback_handler.sendMessage(msg);
                    //                     Navit.GlobalScaleLevel = Navit_SHOW_DEST_ON_MAP_ZOOMLEVEL;
                    //                     if ((zoom_want > 8) && (zoom_want < 17))
                    //                     {
                    //                        Navit.GlobalScaleLevel = (int) (Math.pow(2, (18 - zoom_want)));
                    //                        System.out.println("GlobalScaleLevel=" + Navit.GlobalScaleLevel);
                    //                     }
                    //                  }
                    //                  catch (Exception e)
                    //                  {
                    //                     e.printStackTrace();
                    //                  }
                    //                  if (PREF_save_zoomlevel)
                    //                  {
                    //                     setPrefs_zoomlevel();
                    //                  }
                    // set nice zoomlevel before we show destination

                    try {
                        Navit.follow_button_off();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }

                    show_geo_on_screen(lat1, lon1);
                    //                  final Thread zoom_to_route_003 = new Thread()
                    //                  {
                    //                     @Override
                    //                     public void run()
                    //                     {
                    //                        try
                    //                        {
                    //                           Thread.sleep(200);
                    //                           show_geo_on_screen(lat1, lon1);
                    //                        }
                    //                        catch (Exception e)
                    //                        {
                    //                        }
                    //                     }
                    //                  };
                    //                  zoom_to_route_003.start();

                }
            }
        }

        System.out.println("SUI:099 XX" + substring_without_ioobe(intent_data, 0, 10) + "XX");

        // clear intent
        startup_intent = null;
        // ------------------------  BIG LOOP  ------------------------
        // ------------------------  BIG LOOP  ------------------------
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("SUI:199");
    }

    // clear intent
    startup_intent = null;

    // hold all map drawing -----------
    Message msg = new Message();
    Bundle b = new Bundle();
    b.putInt("Callback", 69);
    msg.setData(b);
    try {
        NavitGraphics.callback_handler.sendMessage(msg);
    } catch (Exception e) {
    }
    // hold all map drawing -----------

    getPrefs();
    activatePrefs();
    sun_moon__mLastCalcSunMillis = -1L;

    push_pin_view = (ImageView) findViewById(R.id.bottom_slide_left_side);
    if (p.PREF_follow_gps) {
        push_pin_view.setImageResource(R.drawable.pin1_down);
    } else {
        push_pin_view.setImageResource(R.drawable.pin1_up);
    }

    // paint for bitmapdrawing on map
    if (p.PREF_use_anti_aliasing) {
        NavitGraphics.paint_for_map_display.setAntiAlias(true);
    } else {
        NavitGraphics.paint_for_map_display.setAntiAlias(false);
    }
    if (p.PREF_use_map_filtering) {
        NavitGraphics.paint_for_map_display.setFilterBitmap(true);
    } else {
        NavitGraphics.paint_for_map_display.setFilterBitmap(false);
    }

    // activate gps AFTER 3g-location
    NavitVehicle.turn_on_precise_provider();

    // allow all map drawing -----------
    msg = new Message();
    b = new Bundle();
    b.putInt("Callback", 70);
    msg.setData(b);
    try {
        NavitGraphics.callback_handler.sendMessage(msg);
    } catch (Exception e) {
    }
    // allow all map drawing -----------

    // --- disabled --- NavitVehicle.set_last_known_pos_fast_provider();

    try {
        //Simulate = new SimGPS(NavitVehicle.vehicle_handler_);
        //Simulate.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        watchmem = new WatchMem();
        watchmem.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // ----- check if we have some index files downloaded -----

    if (api_version_int < 11) {
        if (Navit.have_maps_installed()) {
            if (Navit_maps_too_old) {
                TextView no_maps_text = (TextView) this.findViewById(R.id.no_maps_text);
                no_maps_text.setText("\n\n\n" + Navit.get_text("Some Maps are too old!") + "\n"
                        + Navit.get_text("Please update your maps") + "\n\n");

                try {
                    NavitGraphics.no_maps_container.setVisibility(View.VISIBLE);
                    try {
                        NavitGraphics.no_maps_container.setActivated(true);
                    } catch (NoSuchMethodError e) {
                    }
                    NavitGraphics.no_maps_container.bringToFront();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                allow_use_index_search();
                if (Navit_index_on_but_no_idx_files) {
                    TextView no_maps_text = (TextView) this.findViewById(R.id.no_maps_text);
                    no_maps_text.setText("\n\n\n" + Navit.get_text("No Index for some Maps") + "\n"
                            + Navit.get_text("Please update your maps") + "\n\n");

                    try {
                        NavitGraphics.no_maps_container.setVisibility(View.VISIBLE);
                        try {
                            NavitGraphics.no_maps_container.setActivated(true);
                        } catch (NoSuchMethodError e) {
                        }
                        NavitGraphics.no_maps_container.bringToFront();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        NavitGraphics.no_maps_container.setVisibility(View.INVISIBLE);
                        try {
                            NavitGraphics.no_maps_container.setActivated(false);
                        } catch (NoSuchMethodError e) {
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    } else {
        try {
            NavitGraphics.no_maps_container.setVisibility(View.INVISIBLE);
            try {
                NavitGraphics.no_maps_container.setActivated(false);
            } catch (NoSuchMethodError e) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // ----- check if we have some index files downloaded -----

    // ---- DEBUG ----
    // ---- DEBUG ----
    // ---- DEBUG ----
    try {
        if (!NavitVehicle.is_pos_recording) {
            if (p.PREF_enable_debug_write_gpx) {
                NavitVehicle.pos_recording_start();
                NavitVehicle.pos_recording_add(0, 0, 0, 0, 0, 0);
            }
        }
    } catch (Exception e) {
    }
    // ---- DEBUG ----
    // ---- DEBUG ----
    // ---- DEBUG ----

    // glSurfaceView.onResume();

    // if (Navit.METHOD_DEBUG) Navit.my_func_name(1);

    if (Navit.CIDEBUG == 1) {
        new Thread() {
            public void run() {
                try {
                    System.out.println("DR_run_all_yaml_tests --> want");

                    if (CIRUN == false) {
                        System.out.println("DR_run_all_yaml_tests --> do");
                        CIRUN = true;
                        Thread.sleep(20000); // 20 secs.
                        ZANaviDebugReceiver.DR_run_all_yaml_tests();
                    }
                } catch (Exception e) {
                }
            }
        }.start();
    }
}