Example usage for android.appwidget AppWidgetManager INVALID_APPWIDGET_ID

List of usage examples for android.appwidget AppWidgetManager INVALID_APPWIDGET_ID

Introduction

In this page you can find the example usage for android.appwidget AppWidgetManager INVALID_APPWIDGET_ID.

Prototype

int INVALID_APPWIDGET_ID

To view the source code for android.appwidget AppWidgetManager INVALID_APPWIDGET_ID.

Click Source Link

Document

A sentinel value that the AppWidget manager will never return as a appWidgetId.

Usage

From source file:de.eidottermihi.rpicheck.widget.OverclockingWidget.java

@Override
public void onReceive(Context context, Intent intent) {
    LoggingHelper.initLogging(context);/*from w  w  w  . j a  v  a  2 s. c o m*/
    String action = intent.getAction();
    LOGGER.debug("Receiving Intent: action={}", action);
    if (action.equals(ACTION_WIDGET_UPDATE_ONE_MANUAL)) {
        int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            super.onReceive(context, intent);
        } else {
            if (this.deviceDb == null) {
                this.deviceDb = new DeviceDbHelper(context);
            }
            updateAppWidget(context, widgetId, this.deviceDb, false);
        }
    } else {
        super.onReceive(context, intent);
    }
}

From source file:com.shafiq.myfeedle.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);//from  ww  w  . ja va2s  .c o m
    mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE);
            mServiceName = Myfeedle.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID);
            mMyfeedleWebView = new MyfeedleWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mMyfeedleWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            // case MYSPACE:
            //     mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET);
            //     asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case FOURSQUARE:
                mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Myfeedle.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            // case IDENTICA:
            //     mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET);
            //     asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case GOOGLEPLUS:
                mMyfeedleWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            // case CHATTER:
            //     mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
            //     break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:com.songcode.materialnotes.ui.NoteEditActivity.java

private boolean initActivityState(Intent intent) {
    /**// www .jav  a2  s .c o m
     * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
     * then jump to the NotesListActivity
     */
    mWorkingNote = null;
    if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
        long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
        mUserQuery = "";

        /**
         * Starting from the searched result
         */
        if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
            noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
            mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
        }

        if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
            Intent jump = new Intent(this, NotesListActivity.class);
            startActivity(jump);
            showToast(R.string.error_note_not_exist);
            finish();
            return false;
        } else {
            mWorkingNote = WorkingNote.load(this, noteId);
            if (mWorkingNote == null) {
                Log.e(TAG, "load note failed with note id" + noteId);
                finish();
                return false;
            }
        }
    } else if (TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
        // New note
        long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
        int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, Notes.TYPE_WIDGET_INVALIDE);
        int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, ResourceParser.getDefaultBgId(this));

        // Parse call-record note
        String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
        if (callDate != 0 && phoneNumber != null) {
            if (TextUtils.isEmpty(phoneNumber)) {
                Log.w(TAG, "The call record number is null");
            }
            long noteId = 0;
            if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), phoneNumber,
                    callDate)) > 0) {
                mWorkingNote = WorkingNote.load(this, noteId);
                if (mWorkingNote == null) {
                    Log.e(TAG, "load call note failed with note id" + noteId);
                    finish();
                    return false;
                }
            } else {
                mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, bgResId);
                mWorkingNote.convertToCallNote(phoneNumber, callDate);
            }
        } else {
            mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, bgResId);
        }
    } else {
        Log.e(TAG, "Intent not specified action, should not support");
        finish();
        return false;
    }

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
            | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    mWorkingNote.setOnSettingStatusChangedListener(this);
    return true;
}

From source file:com.piusvelte.sonet.core.SonetService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else/* ww w  .j  ava2 s. com*/
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(SonetService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(SonetService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(SonetService.this), values,
                                        Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(SonetService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Sonet.default_message_bg_color;
                                int profile_bg_color = Sonet.default_message_bg_color;
                                int friend_bg_color = Sonet.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Sonet.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(SonetService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(SonetService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(SonetService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(SonetService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Sonet.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(SonetService.this, widget,
                                                    Sonet.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(SonetService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(SonetService.this), values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(SonetService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(SonetService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(SonetService.this, 0, (Sonet
                                            .getPackageIntent(SonetService.this, SonetNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else/*from  w ww .  j av a2 s  .  c o m*/
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(MyfeedleService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(MyfeedleService.this),
                                        values, Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(MyfeedleService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Myfeedle.default_message_bg_color;
                                int profile_bg_color = Myfeedle.default_message_bg_color;
                                int friend_bg_color = Myfeedle.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Myfeedle.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(MyfeedleService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(MyfeedleService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(MyfeedleService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(MyfeedleService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(MyfeedleService.this, widget,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(MyfeedleService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this),
                                        values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(MyfeedleService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(MyfeedleService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(MyfeedleService.this, 0,
                                            (Myfeedle.getPackageIntent(MyfeedleService.this,
                                                    MyfeedleNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}

From source file:cn.code.notes.gtask.data.SqlNote.java

public boolean setContent(JSONObject js) {
    try {//from w  w  w . ja  va 2s.com
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            Log.w(TAG, "cannot set system folder");
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            // for folder we can only update the snnipet and type
            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
            JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
            long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
            if (mIsCreate || mId != id) {
                mDiffNoteValues.put(NoteColumns.ID, id);
            }
            mId = id;

            long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
            if (mIsCreate || mAlertDate != alertDate) {
                mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
            }
            mAlertDate = alertDate;

            int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID)
                    : ResourceParser.getDefaultBgId(mContext);
            if (mIsCreate || mBgColorId != bgColorId) {
                mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
            }
            mBgColorId = bgColorId;

            long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mCreatedDate != createDate) {
                mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
            }
            mCreatedDate = createDate;

            int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT)
                    : 0;
            if (mIsCreate || mHasAttachment != hasAttachment) {
                mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
            }
            mHasAttachment = hasAttachment;

            long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mModifiedDate != modifiedDate) {
                mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
            }
            mModifiedDate = modifiedDate;

            long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
            if (mIsCreate || mParentId != parentId) {
                mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
            }
            mParentId = parentId;

            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;

            int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
                    : AppWidgetManager.INVALID_APPWIDGET_ID;
            if (mIsCreate || mWidgetId != widgetId) {
                mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
            }
            mWidgetId = widgetId;

            int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE)
                    : Notes.TYPE_WIDGET_INVALIDE;
            if (mIsCreate || mWidgetType != widgetType) {
                mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
            }
            mWidgetType = widgetType;

            long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID)
                    ? note.getLong(NoteColumns.ORIGIN_PARENT_ID)
                    : 0;
            if (mIsCreate || mOriginParent != originParent) {
                mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
            }
            mOriginParent = originParent;

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                SqlData sqlData = null;
                if (data.has(DataColumns.ID)) {
                    long dataId = data.getLong(DataColumns.ID);
                    for (SqlData temp : mDataList) {
                        if (dataId == temp.getId()) {
                            sqlData = temp;
                        }
                    }
                }

                if (sqlData == null) {
                    sqlData = new SqlData(mContext);
                    mDataList.add(sqlData);
                }

                sqlData.setContent(data);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.piusvelte.taplock.client.core.TapLockService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
            if (state == BluetoothAdapter.STATE_ON) {
                if (mStartedBT) {
                    if (mUIInterface != null) {
                        try {
                            mUIInterface.setMessage("Bluetooth enabled");
                        } catch (RemoteException e) {
                            Log.e(TAG, e.getMessage());
                        }/*from ww w. ja  v a 2  s .com*/
                    }
                    if ((mQueueAddress != null) && (mQueueState != null))
                        requestWrite(mQueueAddress, mQueueState, mQueuePassphrase);
                    else if (mRequestDiscovery && !mBtAdapter.isDiscovering())
                        mBtAdapter.startDiscovery();
                    else if (mUIInterface != null) {
                        try {
                            mUIInterface.setBluetoothEnabled();
                        } catch (RemoteException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    }
                }
            } else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
                if (mUIInterface != null) {
                    try {
                        mUIInterface.setMessage("Bluetooth disabled");
                    } catch (RemoteException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
                stopThreads();
            }
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                // connect if configured
                String address = device.getAddress();
                for (JSONObject deviceJObj : mDevices) {
                    try {
                        if (deviceJObj.getString(KEY_ADDRESS).equals(address)) {
                            // if queued
                            mDeviceFound = (mQueueAddress != null) && mQueueAddress.equals(address)
                                    && (mQueueState != null);
                            break;
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
            } else if (mRequestDiscovery && (mUIInterface != null)) {
                String unpairedDevice = TapLock
                        .createDevice(device.getName(), device.getAddress(), DEFAULT_PASSPHRASE).toString();
                try {
                    mUIInterface.setUnpairedDevice(unpairedDevice);
                } catch (RemoteException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            if (mDeviceFound) {
                requestWrite(mQueueAddress, mQueueState, mQueuePassphrase);
                mDeviceFound = false;
            } else if (mRequestDiscovery) {
                mRequestDiscovery = false;
                if (mUIInterface != null) {
                    try {
                        mUIInterface.setDiscoveryFinished();
                    } catch (RemoteException e) {
                        Log.e(TAG, e.toString());
                    }
                }
            }
        } else if (ACTION_TOGGLE.equals(action) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) {
            String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
            requestWrite(address, ACTION_TOGGLE, null);
        } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
            // create widget
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (intent.hasExtra(EXTRA_DEVICE_NAME)) {
                    // add a widget
                    String deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME);
                    for (int i = 0, l = mDevices.size(); i < l; i++) {
                        String name = null;
                        try {
                            name = mDevices.get(i).getString(KEY_NAME);
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                        if ((name != null) && name.equals(deviceName)) {
                            JSONObject deviceJObj = mDevices.remove(i);
                            JSONArray widgetsJArr;
                            if (deviceJObj.has(KEY_WIDGETS)) {
                                try {
                                    widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS);
                                } catch (JSONException e) {
                                    widgetsJArr = new JSONArray();
                                }
                            } else
                                widgetsJArr = new JSONArray();
                            widgetsJArr.put(appWidgetId);
                            try {
                                deviceJObj.put(KEY_WIDGETS, widgetsJArr);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            mDevices.add(i, deviceJObj);
                            TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices);
                            break;
                        }
                    }
                }
                buildWidget(appWidgetId);
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) {
                int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
                if (appWidgetIds != null) {
                    for (int appWidgetId : appWidgetIds)
                        buildWidget(appWidgetId);
                }
            }
        } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
            int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            Log.d(TAG, "delete appWidgetId: " + appWidgetId);
            for (int i = 0, l = mDevices.size(); i < l; i++) {
                JSONObject deviceJObj = mDevices.get(i);
                if (deviceJObj.has(KEY_WIDGETS)) {
                    JSONArray widgetsJArr = null;
                    try {
                        widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (widgetsJArr != null) {
                        boolean wasUpdated = false;
                        JSONArray newWidgetsJArr = new JSONArray();
                        for (int widgetIdx = 0, wdigetsLen = widgetsJArr
                                .length(); widgetIdx < wdigetsLen; widgetIdx++) {
                            int widgetId;
                            try {
                                widgetId = widgetsJArr.getInt(widgetIdx);
                            } catch (JSONException e) {
                                widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
                                e.printStackTrace();
                            }
                            Log.d(TAG, "eval widgetId: " + widgetId);
                            if ((widgetId != AppWidgetManager.INVALID_APPWIDGET_ID)
                                    && (widgetId == appWidgetId)) {
                                Log.d(TAG, "skip: " + widgetId);
                                wasUpdated = true;
                            } else {
                                Log.d(TAG, "include: " + widgetId);
                                newWidgetsJArr.put(widgetId);
                            }
                        }
                        if (wasUpdated) {
                            try {
                                deviceJObj.put(KEY_WIDGETS, newWidgetsJArr);
                                mDevices.remove(i);
                                mDevices.add(i, deviceJObj);
                                TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE),
                                        mDevices);
                                Log.d(TAG, "stored: " + deviceJObj.toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    JSONArray widgetsJArr = new JSONArray();
                    try {
                        deviceJObj.put(KEY_WIDGETS, widgetsJArr);
                        mDevices.remove(i);
                        mDevices.add(i, deviceJObj);
                        TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return START_STICKY;
}

From source file:nl.hnogames.domoticz.Widgets.SmallWidgetConfigurationActivity.java

private void showAppWidget(DevicesInfo mSelectedSwitch, String password, String value, int layoutId) {
    mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    Intent intent = getIntent();/*  w ww  . j  a  v  a  2s. c om*/
    Bundle extras = intent.getExtras();
    int idx = mSelectedSwitch.getIdx();
    if (extras != null) {
        mAppWidgetId = extras.getInt(EXTRA_APPWIDGET_ID, INVALID_APPWIDGET_ID);

        if (UsefulBits.isEmpty(mSelectedSwitch.getType())) {
            Log.i(TAG, "Widget without a type saved");
            mSharedPrefs.setSmallWidgetIDX(mAppWidgetId, idx, false, password, value, layoutId);
        } else {
            if (mSelectedSwitch.getType().equals(DomoticzValues.Scene.Type.GROUP)
                    || mSelectedSwitch.getType().equals(DomoticzValues.Scene.Type.SCENE)) {
                Log.i(TAG, "Widget Scene saved " + mSelectedSwitch.getType());
                mSharedPrefs.setSmallWidgetIDX(mAppWidgetId, idx, true, password, value, layoutId);
            } else {
                Log.i(TAG, "Widget saved " + mSelectedSwitch.getType());
                mSharedPrefs.setSmallWidgetIDX(mAppWidgetId, idx, false, password, value, layoutId);
            }
        }

        Intent startService = new Intent(SmallWidgetConfigurationActivity.this,
                WidgetProviderSmall.UpdateWidgetService.class);
        startService.putExtra(EXTRA_APPWIDGET_ID, mAppWidgetId);
        startService.setAction("FROM CONFIGURATION ACTIVITY");
        startService(startService);
        setResult(RESULT_OK, startService);
        finish();
    }

    if (mAppWidgetId == INVALID_APPWIDGET_ID) {
        Log.i(TAG, "I am invalid");
        finish();
    }
}

From source file:nl.hnogames.domoticz.Widgets.SecurityWidgetConfigurationActivity.java

private void showAppWidget(DevicesInfo mSelectedSwitch, String value, String pin, int layout) {
    mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    Intent intent = getIntent();/*from   www  .j  a  v a2  s . c om*/
    Bundle extras = intent.getExtras();
    int idx = mSelectedSwitch.getIdx();

    if (extras != null) {
        mAppWidgetId = extras.getInt(EXTRA_APPWIDGET_ID, INVALID_APPWIDGET_ID);
        mSharedPrefs.setSecurityWidgetIDX(mAppWidgetId, idx, value, pin, layout);
        Intent startService = new Intent(SecurityWidgetConfigurationActivity.this,
                SecurityWidgetProvider.UpdateSecurityWidgetService.class);
        startService.putExtra(EXTRA_APPWIDGET_ID, mAppWidgetId);
        startService.setAction("FROM CONFIGURATION ACTIVITY");
        startService(startService);
        setResult(RESULT_OK, startService);
        finish();
    }
    if (mAppWidgetId == INVALID_APPWIDGET_ID) {
        Log.i(TAG, "I am invalid");
        finish();
    }
}

From source file:nl.hnogames.domoticz.Widgets.WidgetConfigurationActivity.java

private void showAppWidget(DevicesInfo mSelectedSwitch, String password, String value, int layoutId) {
    mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    Intent intent = getIntent();/*from www .j  a  va 2  s .  com*/
    Bundle extras = intent.getExtras();
    int idx = mSelectedSwitch.getIdx();
    if (extras != null) {
        mAppWidgetId = extras.getInt(EXTRA_APPWIDGET_ID, INVALID_APPWIDGET_ID);
        if (UsefulBits.isEmpty(mSelectedSwitch.getType())) {
            Log.i(TAG, "Widget without a type saved");
            mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, false, password, value, layoutId);
        } else {
            if (mSelectedSwitch.getType().equals(DomoticzValues.Scene.Type.GROUP)
                    || mSelectedSwitch.getType().equals(DomoticzValues.Scene.Type.SCENE)) {
                Log.i(TAG, "Widget Scene saved " + mSelectedSwitch.getType());
                mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, true, password, value, layoutId);
            } else {
                Log.i(TAG, "Widget saved " + mSelectedSwitch.getType());
                mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, false, password, value, layoutId);
            }
        }
        Intent startService = new Intent(WidgetConfigurationActivity.this,
                WidgetProviderLarge.UpdateWidgetService.class);
        startService.putExtra(EXTRA_APPWIDGET_ID, mAppWidgetId);
        startService.setAction("FROM CONFIGURATION ACTIVITY");
        startService(startService);
        setResult(RESULT_OK, startService);
        finish();
    }
    if (mAppWidgetId == INVALID_APPWIDGET_ID) {
        Log.i(TAG, "I am invalid");
        finish();
    }
}