Example usage for android.content Intent getData

List of usage examples for android.content Intent getData

Introduction

In this page you can find the example usage for android.content Intent getData.

Prototype

public @Nullable Uri getData() 

Source Link

Document

Retrieve data this intent is operating on.

Usage

From source file:com.amaze.filemanager.activities.MainActivity.java

protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    if (requestCode == RC_SIGN_IN && !mGoogleApiKey && mGoogleApiClient != null) {
        new Thread(new Runnable() {
            @Override//  ww w .j  ava  2  s. c om
            public void run() {
                mIntentInProgress = false;
                mGoogleApiKey = true;
                // !mGoogleApiClient.isConnecting
                if (mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                } else
                    mGoogleApiClient.disconnect();

            }
        }).run();
    } else if (requestCode == image_selector_request_code) {
        if (Sp != null && intent != null && intent.getData() != null) {
            if (Build.VERSION.SDK_INT >= 19)
                getContentResolver().takePersistableUriPermission(intent.getData(),
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Sp.edit().putString("drawer_header_path", intent.getData().toString()).commit();
            setDrawerHeaderBackground();
        }
    } else if (requestCode == 3) {
        String p = Sp.getString("URI", null);
        Uri oldUri = null;
        if (p != null)
            oldUri = Uri.parse(p);
        Uri treeUri = null;
        if (responseCode == Activity.RESULT_OK) {
            // Get Uri from Storage Access Framework.
            treeUri = intent.getData();
            // Persist URI - this is required for verification of writability.
            if (treeUri != null)
                Sp.edit().putString("URI", treeUri.toString()).commit();
        }
        // If not confirmed SAF, or if still not writable, then revert settings.
        if (responseCode != Activity.RESULT_OK) {
            /* DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false,
                currentFolder);||!FileUtil.isWritableNormalOrSaf(currentFolder)
            */
            if (treeUri != null)
                Sp.edit().putString("URI", oldUri.toString()).commit();
            return;
        }

        // After confirmation, update stored value of folder.
        // Persist access permissions.
        final int takeFlags = intent.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
        switch (operation) {
        case DataUtils.DELETE://deletion
            new DeleteTask(null, mainActivity).execute((oparrayList));
            break;
        case DataUtils.COPY://copying
            Intent intent1 = new Intent(con, CopyService.class);
            intent1.putExtra("FILE_PATHS", (oparrayList));
            intent1.putExtra("COPY_DIRECTORY", oppathe);
            startService(intent1);
            break;
        case DataUtils.MOVE://moving
            new MoveFiles((oparrayList), ((Main) getFragment().getTab()),
                    ((Main) getFragment().getTab()).getActivity(), 0)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, path);
            break;
        case DataUtils.NEW_FOLDER://mkdir
            Main ma1 = ((Main) getFragment().getTab());
            mainActivityHelper.mkDir(RootHelper.generateBaseFile(new File(oppathe), true), ma1);
            break;
        case DataUtils.RENAME:
            mainActivityHelper.rename(HFile.LOCAL_MODE, (oppathe), (oppathe1), mainActivity, rootmode);
            Main ma2 = ((Main) getFragment().getTab());
            ma2.updateList();
            break;
        case DataUtils.NEW_FILE:
            Main ma3 = ((Main) getFragment().getTab());
            mainActivityHelper.mkFile(new HFile(HFile.LOCAL_MODE, oppathe), ma3);

            break;
        case DataUtils.EXTRACT:
            mainActivityHelper.extractFile(new File(oppathe));
            break;
        case DataUtils.COMPRESS:
            mainActivityHelper.compressFiles(new File(oppathe), oparrayList);
        }
        operation = -1;
    }
}

From source file:com.ichi2.anki2.DeckPicker.java

/** Called when the activity is first created. */
@Override/*from   www.j  a v  a2  s.  com*/
protected void onCreate(Bundle savedInstanceState) throws SQLException {
    Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate");
    Intent intent = getIntent();
    if (!isTaskRoot()) {
        Log.i(AnkiDroidApp.TAG,
                "DeckPicker - onCreate: Detected multiple instance of this activity, closing it and return to root activity");
        Intent reloadIntent = new Intent(DeckPicker.this, DeckPicker.class);
        reloadIntent.setAction(Intent.ACTION_MAIN);
        if (intent != null && intent.getExtras() != null) {
            reloadIntent.putExtras(intent.getExtras());
        }
        if (intent != null && intent.getData() != null) {
            reloadIntent.setData(intent.getData());
        }
        reloadIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        reloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        finish();
        startActivityIfNeeded(reloadIntent, 0);
    }
    if (intent.getData() != null) {
        mImportPath = getIntent().getData().getEncodedPath();
    }

    // need to start this here in order to avoid showing deckpicker before splashscreen
    if (AnkiDroidApp.colIsOpen()) {
        setTitle(getResources().getString(R.string.app_name));
    } else {
        setTitle("");
        mOpenCollectionHandler.onPreExecute();
    }

    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    // mStartedByBigWidget = intent.getIntExtra(EXTRA_START, EXTRA_START_NOTHING);

    SharedPreferences preferences = restorePreferences();

    // activate broadcast messages if first start of a day
    if (mLastTimeOpened < UIUtils.getDayStart()) {
        preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
    }
    preferences.edit().putLong("lastTimeOpened", System.currentTimeMillis()).commit();

    // if (intent != null && intent.hasExtra(EXTRA_DECK_ID)) {
    // openStudyOptions(intent.getLongExtra(EXTRA_DECK_ID, 1));
    // }

    BroadcastMessages.checkForNewMessages(this);

    View mainView = getLayoutInflater().inflate(R.layout.deck_picker, null);
    setContentView(mainView);

    // check, if tablet layout
    View studyoptionsFrame = findViewById(R.id.studyoptions_fragment);
    mFragmented = studyoptionsFrame != null && studyoptionsFrame.getVisibility() == View.VISIBLE;

    Themes.setContentStyle(mFragmented ? mainView : mainView.findViewById(R.id.deckpicker_view),
            Themes.CALLER_DECKPICKER);

    registerExternalStorageListener();

    if (!mFragmented) {
        mAddButton = (ImageButton) findViewById(R.id.deckpicker_add);
        mAddButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addNote();
            }
        });

        mCardsButton = (ImageButton) findViewById(R.id.deckpicker_card_browser);
        mCardsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openCardBrowser();
            }
        });

        mStatsButton = (ImageButton) findViewById(R.id.statistics_all_button);
        mStatsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(DIALOG_SELECT_STATISTICS_TYPE);
            }
        });

        mSyncButton = (ImageButton) findViewById(R.id.sync_all_button);
        mSyncButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sync();
            }
        });
    }

    mInvalidateMenu = false;
    mDeckList = new ArrayList<HashMap<String, String>>();
    mDeckListView = (ListView) findViewById(R.id.files);
    mDeckListAdapter = new SimpleAdapter(this, mDeckList, R.layout.deck_item,
            new String[] { "name", "new", "lrn", "rev", // "complMat", "complAll",
                    "sep", "dyn" },
            new int[] { R.id.DeckPickerName, R.id.deckpicker_new, R.id.deckpicker_lrn, R.id.deckpicker_rev, // R.id.deckpicker_bar_mat, R.id.deckpicker_bar_all,
                    R.id.deckpicker_deck, R.id.DeckPickerName });
    mDeckListAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object data, String text) {
            if (view.getId() == R.id.deckpicker_deck) {
                if (text.equals("top")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_top);
                    return true;
                } else if (text.equals("bot")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_bottom);
                    return true;
                } else if (text.equals("ful")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_full);
                    return true;
                } else if (text.equals("cen")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_center);
                    return true;
                }
            } else if (view.getId() == R.id.DeckPickerName) {
                if (text.equals("d0")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.non_dyn_deck));
                    return true;
                } else if (text.equals("d1")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.dyn_deck));
                    return true;
                }
            }
            // } else if (view.getId() == R.id.deckpicker_bar_mat || view.getId() == R.id.deckpicker_bar_all) {
            // if (text.length() > 0 && !text.equals("-1.0")) {
            // View parent = (View)view.getParent().getParent();
            // if (text.equals("-2")) {
            // parent.setVisibility(View.GONE);
            // } else {
            // Utils.updateProgressBars(view, (int) UIUtils.getDensityAdjustedValue(DeckPicker.this, 3.4f),
            // (int) (Double.parseDouble(text) * ((View)view.getParent().getParent().getParent()).getHeight()));
            // if (parent.getVisibility() == View.INVISIBLE) {
            // parent.setVisibility(View.VISIBLE);
            // parent.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // }
            // }
            // }
            // return true;
            // } else if (view.getVisibility() == View.INVISIBLE) {
            // if (!text.equals("-1")) {
            // view.setVisibility(View.VISIBLE);
            // view.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // return false;
            // }
            // } else if (text.equals("-1")){
            // view.setVisibility(View.INVISIBLE);
            // return false;
            return false;
        }
    });
    mDeckListView.setOnItemClickListener(mDeckSelHandler);
    mDeckListView.setAdapter(mDeckListAdapter);

    if (mFragmented) {
        mDeckListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    registerForContextMenu(mDeckListView);

    showStartupScreensAndDialogs(preferences, 0);

    if (mSwipeEnabled) {
        gestureDetector = new GestureDetector(new MyGestureDetector());
        mDeckListView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
    }
}

From source file:com.nit.vicky.DeckPicker.java

/** Called when the activity is first created. */
@Override//ww  w  .j  a  v  a  2 s .  c  om
protected void onCreate(Bundle savedInstanceState) throws SQLException {
    // Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate");
    Intent intent = getIntent();
    if (!isTaskRoot()) {
        // Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate: Detected multiple instance of this activity, closing it and return to root activity");
        Intent reloadIntent = new Intent(DeckPicker.this, DeckPicker.class);
        reloadIntent.setAction(Intent.ACTION_MAIN);
        if (intent != null && intent.getExtras() != null) {
            reloadIntent.putExtras(intent.getExtras());
        }
        if (intent != null && intent.getData() != null) {
            reloadIntent.setData(intent.getData());
        }
        reloadIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        reloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        finish();
        startActivityIfNeeded(reloadIntent, 0);
    }
    if (intent.getData() != null) {
        mImportPath = getIntent().getData().getEncodedPath();
    }

    // need to start this here in order to avoid showing deckpicker before splashscreen
    if (AnkiDroidApp.colIsOpen()) {
        setTitle(getResources().getString(R.string.app_name));
    } else {
        setTitle("");
        mOpenCollectionHandler.onPreExecute();
    }

    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    // mStartedByBigWidget = intent.getIntExtra(EXTRA_START, EXTRA_START_NOTHING);

    SharedPreferences preferences = restorePreferences();

    // activate broadcast messages if first start of a day
    if (mLastTimeOpened < UIUtils.getDayStart()) {
        preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
    }
    preferences.edit().putLong("lastTimeOpened", System.currentTimeMillis()).commit();

    // if (intent != null && intent.hasExtra(EXTRA_DECK_ID)) {
    // openStudyOptions(intent.getLongExtra(EXTRA_DECK_ID, 1));
    // }

    //BroadcastMessages.checkForNewMessages(this);

    View mainView = getLayoutInflater().inflate(R.layout.deck_picker, null);
    setContentView(mainView);

    // check, if tablet layout
    View studyoptionsFrame = findViewById(R.id.studyoptions_fragment);
    mFragmented = studyoptionsFrame != null && studyoptionsFrame.getVisibility() == View.VISIBLE;

    Themes.setContentStyle(mFragmented ? mainView : mainView.findViewById(R.id.deckpicker_view),
            Themes.CALLER_DECKPICKER);

    registerExternalStorageListener();

    if (!mFragmented) {
        mAddButton = (ImageButton) findViewById(R.id.deckpicker_add);
        mAddButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addNote();
            }
        });

        mCardsButton = (ImageButton) findViewById(R.id.deckpicker_card_browser);
        mCardsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openCardBrowser();
            }
        });

        mStatsButton = (ImageButton) findViewById(R.id.statistics_all_button);
        mStatsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(DIALOG_SELECT_STATISTICS_TYPE);
            }
        });

        mSyncButton = (ImageButton) findViewById(R.id.sync_all_button);
        mSyncButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sync();
            }
        });
    }

    mInvalidateMenu = false;
    mDeckList = new ArrayList<HashMap<String, String>>();
    mDeckListView = (ListView) findViewById(R.id.files);
    mDeckListAdapter = new SimpleAdapter(this, mDeckList, R.layout.deck_item,
            new String[] { "name", "new", "lrn", "rev", // "complMat", "complAll",
                    "sep", "dyn" },
            new int[] { R.id.DeckPickerName, R.id.deckpicker_new, R.id.deckpicker_lrn, R.id.deckpicker_rev, // R.id.deckpicker_bar_mat, R.id.deckpicker_bar_all,
                    R.id.deckpicker_deck, R.id.DeckPickerName });
    mDeckListAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object data, String text) {
            if (view.getId() == R.id.deckpicker_deck) {
                if (text.equals("top")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_top);
                    return true;
                } else if (text.equals("bot")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_bottom);
                    return true;
                } else if (text.equals("ful")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_full);
                    return true;
                } else if (text.equals("cen")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_center);
                    return true;
                }
            } else if (view.getId() == R.id.DeckPickerName) {
                if (text.equals("d0")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.non_dyn_deck));
                    return true;
                } else if (text.equals("d1")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.dyn_deck));
                    return true;
                }
            }
            // } else if (view.getId() == R.id.deckpicker_bar_mat || view.getId() == R.id.deckpicker_bar_all) {
            // if (text.length() > 0 && !text.equals("-1.0")) {
            // View parent = (View)view.getParent().getParent();
            // if (text.equals("-2")) {
            // parent.setVisibility(View.GONE);
            // } else {
            // Utils.updateProgressBars(view, (int) UIUtils.getDensityAdjustedValue(DeckPicker.this, 3.4f),
            // (int) (Double.parseDouble(text) * ((View)view.getParent().getParent().getParent()).getHeight()));
            // if (parent.getVisibility() == View.INVISIBLE) {
            // parent.setVisibility(View.VISIBLE);
            // parent.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // }
            // }
            // }
            // return true;
            // } else if (view.getVisibility() == View.INVISIBLE) {
            // if (!text.equals("-1")) {
            // view.setVisibility(View.VISIBLE);
            // view.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // return false;
            // }
            // } else if (text.equals("-1")){
            // view.setVisibility(View.INVISIBLE);
            // return false;
            return false;
        }
    });
    mDeckListView.setOnItemClickListener(mDeckSelHandler);
    mDeckListView.setAdapter(mDeckListAdapter);

    if (mFragmented) {
        mDeckListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    registerForContextMenu(mDeckListView);

    showStartupScreensAndDialogs(preferences, 0);

    if (mSwipeEnabled) {
        gestureDetector = new GestureDetector(new MyGestureDetector());
        mDeckListView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
    }
}

From source file:com.phonegap.CameraLauncher.java

/**
 * Called when the camera view exits. /*from w ww . ja v a2 s.c  om*/
 * 
 * @param requestCode      The request code originally supplied to startActivityForResult(), 
 *                      allowing you to identify who this result came from.
 * @param resultCode      The integer result code returned by the child activity through its setResult().
 * @param intent         An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;

    // If CAMERA
    if (srcType == CAMERA) {

        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Read in bitmap of captured image
                Bitmap bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.ctx.getContentResolver(), imageUri);

                // If sending base64 image back
                if (destType == DATA_URL) {
                    this.processPicture(bitmap);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    // Create entry in media store for image
                    // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
                    ContentValues values = new ContentValues();
                    values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    Uri uri = null;
                    try {
                        uri = this.ctx.getContentResolver()
                                .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                    } catch (UnsupportedOperationException e) {
                        System.out.println("Can't write to external media storage.");
                        try {
                            uri = this.ctx.getContentResolver().insert(
                                    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException ex) {
                            System.out.println("Can't write to internal media storage.");
                            this.failPicture("Error capturing image - no media storage found.");
                            return;
                        }
                    }

                    // Add compressed version of captured image to returned media store Uri
                    OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                    os.close();

                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }
                bitmap.recycle();
                bitmap = null;
                System.gc();
            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();
            android.content.ContentResolver resolver = this.ctx.getContentResolver();
            // If sending base64 image back
            if (destType == DATA_URL) {
                try {
                    Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
                    this.processPicture(bitmap);
                    bitmap.recycle();
                    bitmap = null;
                    System.gc();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    this.failPicture("Error retrieving image.");
                }
            }

            // If sending filename back
            else if (destType == FILE_URI) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

public static Fragment createFragmentForIntent(final Context context, final int linkId, final Intent intent) {
    intent.setExtrasClassLoader(context.getClassLoader());
    final Bundle extras = intent.getExtras();
    final Uri uri = intent.getData();
    final Fragment fragment;
    if (uri == null)
        return null;
    final Bundle args = new Bundle();
    if (extras != null) {
        args.putAll(extras);//  w w w  . ja  va 2  s  .c  om
    }
    switch (linkId) {
    case LINK_ID_STATUS: {
        fragment = new StatusFragment();
        if (!args.containsKey(EXTRA_STATUS_ID)) {
            final String param_status_id = uri.getQueryParameter(QUERY_PARAM_STATUS_ID);
            args.putLong(EXTRA_STATUS_ID, ParseUtils.parseLong(param_status_id));
        }
        break;
    }
    case LINK_ID_USER: {
        fragment = new UserFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String param_user_id = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(param_user_id));
        }
        break;
    }
    case LINK_ID_USER_LIST_MEMBERSHIPS: {
        fragment = new UserListMembershipsListFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        }
        break;
    }
    case LINK_ID_USER_TIMELINE: {
        fragment = new UserTimelineFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        }
        if (isEmpty(paramScreenName) && isEmpty(paramUserId))
            return null;
        break;
    }
    case LINK_ID_USER_MEDIA_TIMELINE: {
        fragment = new UserMediaTimelineFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        }
        if (isEmpty(paramScreenName) && isEmpty(paramUserId))
            return null;
        break;
    }
    case LINK_ID_USER_FAVORITES: {
        fragment = new UserFavoritesFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        }
        if (!args.containsKey(EXTRA_SCREEN_NAME) && !args.containsKey(EXTRA_USER_ID))
            return null;
        break;
    }
    case LINK_ID_USER_FOLLOWERS: {
        fragment = new UserFollowersFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String param_user_id = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(param_user_id));
        }
        if (isEmpty(paramScreenName) && isEmpty(param_user_id))
            return null;
        break;
    }
    case LINK_ID_USER_FRIENDS: {
        fragment = new UserFriendsFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String param_user_id = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(param_user_id));
        }
        if (isEmpty(paramScreenName) && isEmpty(param_user_id))
            return null;
        break;
    }
    case LINK_ID_USER_BLOCKS: {
        fragment = new UserBlocksListFragment();
        break;
    }
    case LINK_ID_MUTES_USERS: {
        fragment = new MutesUsersListFragment();
        break;
    }
    case LINK_ID_DIRECT_MESSAGES_CONVERSATION: {
        fragment = new MessagesConversationFragment();
        final String paramRecipientId = uri.getQueryParameter(QUERY_PARAM_RECIPIENT_ID);
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final long conversationId = ParseUtils.parseLong(paramRecipientId);
        if (conversationId > 0) {
            args.putLong(EXTRA_RECIPIENT_ID, conversationId);
        } else if (paramScreenName != null) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        break;
    }
    case LINK_ID_USER_LIST: {
        fragment = new UserListFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        final String paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID);
        final String paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME);
        if (isEmpty(paramListId)
                && (isEmpty(paramListName) || isEmpty(paramScreenName) && isEmpty(paramUserId)))
            return null;
        args.putLong(EXTRA_LIST_ID, ParseUtils.parseLong(paramListId));
        args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        args.putString(EXTRA_LIST_NAME, paramListName);
        break;
    }
    case LINK_ID_USER_LISTS: {
        fragment = new UserListsFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (!args.containsKey(EXTRA_USER_ID)) {
            args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        }
        if (isEmpty(paramScreenName) && isEmpty(paramUserId))
            return null;
        break;
    }
    case LINK_ID_USER_LIST_TIMELINE: {
        fragment = new UserListTimelineFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        final String paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID);
        final String paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME);
        if (isEmpty(paramListId)
                && (isEmpty(paramListName) || isEmpty(paramScreenName) && isEmpty(paramUserId)))
            return null;
        args.putLong(EXTRA_LIST_ID, ParseUtils.parseLong(paramListId));
        args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        args.putString(EXTRA_LIST_NAME, paramListName);
        break;
    }
    case LINK_ID_USER_LIST_MEMBERS: {
        fragment = new UserListMembersFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        final String paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID);
        final String paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME);
        if (isEmpty(paramListId)
                && (isEmpty(paramListName) || isEmpty(paramScreenName) && isEmpty(paramUserId)))
            return null;
        args.putLong(EXTRA_LIST_ID, ParseUtils.parseLong(paramListId));
        args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        args.putString(EXTRA_LIST_NAME, paramListName);
        break;
    }
    case LINK_ID_USER_LIST_SUBSCRIBERS: {
        fragment = new UserListSubscribersFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        final String paramUserId = uri.getQueryParameter(QUERY_PARAM_USER_ID);
        final String paramListId = uri.getQueryParameter(QUERY_PARAM_LIST_ID);
        final String paramListName = uri.getQueryParameter(QUERY_PARAM_LIST_NAME);
        if (isEmpty(paramListId)
                && (isEmpty(paramListName) || isEmpty(paramScreenName) && isEmpty(paramUserId)))
            return null;
        args.putLong(EXTRA_LIST_ID, ParseUtils.parseLong(paramListId));
        args.putLong(EXTRA_USER_ID, ParseUtils.parseLong(paramUserId));
        args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        args.putString(EXTRA_LIST_NAME, paramListName);
        break;
    }
    case LINK_ID_SAVED_SEARCHES: {
        fragment = new SavedSearchesListFragment();
        break;
    }
    case LINK_ID_USER_MENTIONS: {
        fragment = new UserMentionsFragment();
        final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
        if (!args.containsKey(EXTRA_SCREEN_NAME) && !isEmpty(paramScreenName)) {
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        if (isEmpty(args.getString(EXTRA_SCREEN_NAME)))
            return null;
        break;
    }
    case LINK_ID_INCOMING_FRIENDSHIPS: {
        fragment = new IncomingFriendshipsFragment();
        break;
    }
    case LINK_ID_USERS: {
        fragment = new UsersListFragment();
        break;
    }
    case LINK_ID_STATUSES: {
        fragment = new StatusesListFragment();
        break;
    }
    case LINK_ID_STATUS_RETWEETERS: {
        fragment = new StatusRetweetersListFragment();
        if (!args.containsKey(EXTRA_STATUS_ID)) {
            final String paramStatusId = uri.getQueryParameter(QUERY_PARAM_STATUS_ID);
            args.putLong(EXTRA_STATUS_ID, ParseUtils.parseLong(paramStatusId));
        }
        break;
    }
    case LINK_ID_STATUS_FAVORITERS: {
        fragment = new StatusFavoritersListFragment();
        if (!args.containsKey(EXTRA_STATUS_ID)) {
            final String paramStatusId = uri.getQueryParameter(QUERY_PARAM_STATUS_ID);
            args.putLong(EXTRA_STATUS_ID, ParseUtils.parseLong(paramStatusId));
        }
        break;
    }
    case LINK_ID_STATUS_REPLIES: {
        fragment = new StatusRepliesListFragment();
        if (!args.containsKey(EXTRA_STATUS_ID)) {
            final String paramStatusId = uri.getQueryParameter(QUERY_PARAM_STATUS_ID);
            args.putLong(EXTRA_STATUS_ID, ParseUtils.parseLong(paramStatusId));
        }
        if (!args.containsKey(EXTRA_SCREEN_NAME)) {
            final String paramScreenName = uri.getQueryParameter(QUERY_PARAM_SCREEN_NAME);
            args.putString(EXTRA_SCREEN_NAME, paramScreenName);
        }
        break;
    }
    case LINK_ID_SEARCH: {
        final String param_query = uri.getQueryParameter(QUERY_PARAM_QUERY);
        if (isEmpty(param_query))
            return null;
        args.putString(EXTRA_QUERY, param_query);
        fragment = new SearchFragment();
        break;
    }
    default: {
        return null;
    }
    }
    final String paramAccountId = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_ID);
    if (paramAccountId != null) {
        args.putLong(EXTRA_ACCOUNT_ID, ParseUtils.parseLong(paramAccountId));
    } else {
        final String paramAccountName = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_NAME);
        if (paramAccountName != null) {
            args.putLong(EXTRA_ACCOUNT_ID, getAccountId(context, paramAccountName));
        } else {
            final long accountId = getDefaultAccountId(context);
            if (isMyAccount(context, accountId)) {
                args.putLong(EXTRA_ACCOUNT_ID, accountId);
            }
        }
    }
    fragment.setArguments(args);
    return fragment;
}

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/*from   w  w  w.j  a v  a 2 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(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 ww w.j  ava 2 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:com.hichinaschool.flashcards.anki.DeckPicker.java

/** Called when the activity is first created. */
@Override//from   w w  w.  ja v a  2 s  .co m
protected void onCreate(Bundle savedInstanceState) throws SQLException {
    // Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate");
    Intent intent = getIntent();
    if (!isTaskRoot()) {
        // Log.i(AnkiDroidApp.TAG, "DeckPicker - onCreate: Detected multiple instance of this activity, closing it and return to root activity");
        Intent reloadIntent = new Intent(DeckPicker.this, DeckPicker.class);
        reloadIntent.setAction(Intent.ACTION_MAIN);
        if (intent != null && intent.getExtras() != null) {
            reloadIntent.putExtras(intent.getExtras());
        }
        if (intent != null && intent.getData() != null) {
            reloadIntent.setData(intent.getData());
        }
        reloadIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        reloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        finish();
        startActivityIfNeeded(reloadIntent, 0);
    }
    if (intent.getData() != null) {
        mImportPath = getIntent().getData().getEncodedPath();
    }

    // need to start this here in order to avoid showing deckpicker before splashscreen
    if (AnkiDroidApp.colIsOpen()) {
        setTitle(getResources().getString(R.string.app_name));
    } else {
        setTitle("");
        mOpenCollectionHandler.onPreExecute();
    }

    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    // mStartedByBigWidget = intent.getIntExtra(EXTRA_START, EXTRA_START_NOTHING);

    SharedPreferences preferences = restorePreferences();

    // activate broadcast messages if first start of a day
    if (mLastTimeOpened < UIUtils.getDayStart()) {
        preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
    }
    preferences.edit().putLong("lastTimeOpened", System.currentTimeMillis()).commit();

    // if (intent != null && intent.hasExtra(EXTRA_DECK_ID)) {
    // openStudyOptions(intent.getLongExtra(EXTRA_DECK_ID, 1));
    // }

    //   BroadcastMessages.checkForNewMessages(this);

    View mainView = getLayoutInflater().inflate(R.layout.deck_picker, null);
    setContentView(mainView);

    // check, if tablet layout
    View studyoptionsFrame = findViewById(R.id.studyoptions_fragment);
    mFragmented = studyoptionsFrame != null && studyoptionsFrame.getVisibility() == View.VISIBLE;

    Themes.setContentStyle(mFragmented ? mainView : mainView.findViewById(R.id.deckpicker_view),
            Themes.CALLER_DECKPICKER);

    registerExternalStorageListener();

    if (!mFragmented) {
        //            mAddButton = (ImageButton) findViewById(R.id.deckpicker_add);
        //            mAddButton.setOnClickListener(new OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    addNote();
        //                }
        //            });
        //
        //            mCardsButton = (ImageButton) findViewById(R.id.deckpicker_card_browser);
        //            mCardsButton.setOnClickListener(new OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    openCardBrowser();
        //                }
        //            });
        //
        //            mStatsButton = (ImageButton) findViewById(R.id.statistics_all_button);
        //            mStatsButton.setOnClickListener(new OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    showDialog(DIALOG_SELECT_STATISTICS_TYPE);
        //                }
        //            });
        //
        //            mSyncButton = (ImageButton) findViewById(R.id.sync_all_button);
        //            mSyncButton.setOnClickListener(new OnClickListener() {
        //                @Override
        //                public void onClick(View v) {
        //                    sync();
        //                }
        //            });
    }

    mInvalidateMenu = false;
    mDeckList = new ArrayList<HashMap<String, String>>();
    mDeckListView = (ListView) findViewById(R.id.files);
    //   mDeckListAdapter = new SimpleAdapter(this, mDeckList, R.layout.deck_item, new String[] { "name", "new", "lrn",
    //      "rev", // "complMat", "complAll",
    //      "sep", "dyn" }, new int[] { R.id.DeckPickerName, R.id.deckpicker_new, R.id.deckpicker_lrn,
    //      R.id.deckpicker_rev, // R.id.deckpicker_bar_mat, R.id.deckpicker_bar_all,
    //      R.id.deckpicker_deck, R.id.DeckPickerName });

    mDeckListAdapter = new SimpleAdapter(this, mDeckList, R.layout.deck_item,
            new String[] { "name", "new", "lrn", "rev", "sep", "dyn", "url" },
            new int[] { R.id.DeckPickerName, R.id.deckpicker_new, R.id.deckpicker_lrn, R.id.deckpicker_rev,
                    R.id.deckpicker_deck, R.id.DeckPickerName, R.id.deckpicker_url });

    mDeckListAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(final View view, final Object data, String text) {
            if (view.getId() == R.id.deckpicker_url) {
                // If "url" field has text, it means the deck must be downloaded
                // so we put the downloadButton visible and add its listener
                if (!text.equals("")) {

                    final View parentView = (View) view.getParent();
                    Button downloadButton = (Button) parentView.findViewById(R.id.deckpicker_button);

                    downloadButton.setVisibility(View.VISIBLE);
                    parentView.findViewById(R.id.deckpicker_new).setVisibility(View.GONE);
                    parentView.findViewById(R.id.deckpicker_rev).setVisibility(View.GONE);
                    parentView.findViewById(R.id.deckpicker_lrn).setVisibility(View.GONE);

                    downloadButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //   ListView lv = (ListView) parentView.getParent().getParent();
                            //                        int i;
                            //                        for (i = 0; i < mDeckList.size(); i++) {
                            //                           if (mDeckListView.getItemAtPosition(i).equals(view)){
                            //                              mDeckLastItemSelected = i;
                            //                           }
                            //                        }

                            // Gets url from the selected deck and download it
                            TextView txt = (TextView) ((View) view.getParent())
                                    .findViewById(R.id.deckpicker_url);
                            String url = txt.getText().toString();
                            Connection.downloadSharedDeck(mDownloadDeckListener,
                                    new Connection.Payload(new Object[] { url }));
                        }
                    });
                } else {
                    Button downloadButton = (Button) ((View) view.getParent())
                            .findViewById(R.id.deckpicker_button);
                    downloadButton.setVisibility(View.GONE);
                    ((View) view.getParent()).findViewById(R.id.deckpicker_new).setVisibility(View.VISIBLE);
                    ((View) view.getParent()).findViewById(R.id.deckpicker_rev).setVisibility(View.VISIBLE);
                    ((View) view.getParent()).findViewById(R.id.deckpicker_lrn).setVisibility(View.VISIBLE);
                }
            }
            if (view.getId() == R.id.deckpicker_deck) {
                if (text.equals("top")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_top);
                    return true;
                } else if (text.equals("bot")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_bottom);
                    return true;
                } else if (text.equals("ful")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_full);
                    return true;
                } else if (text.equals("cen")) {
                    view.setBackgroundResource(R.drawable.white_deckpicker_center);
                    return true;
                }
            } else if (view.getId() == R.id.DeckPickerName) {
                if (text.equals("d0")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.non_dyn_deck));
                    return true;
                } else if (text.equals("d1")) {
                    ((TextView) view).setTextColor(getResources().getColor(R.color.dyn_deck));
                    return true;
                }
            }
            // } else if (view.getId() == R.id.deckpicker_bar_mat || view.getId() == R.id.deckpicker_bar_all) {
            // if (text.length() > 0 && !text.equals("-1.0")) {
            // View parent = (View)view.getParent().getParent();
            // if (text.equals("-2")) {
            // parent.setVisibility(View.GONE);
            // } else {
            // Utils.updateProgressBars(view, (int) UIUtils.getDensityAdjustedValue(DeckPicker.this, 3.4f),
            // (int) (Double.parseDouble(text) * ((View)view.getParent().getParent().getParent()).getHeight()));
            // if (parent.getVisibility() == View.INVISIBLE) {
            // parent.setVisibility(View.VISIBLE);
            // parent.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // }
            // }
            // }
            // return true;
            // } else if (view.getVisibility() == View.INVISIBLE) {
            // if (!text.equals("-1")) {
            // view.setVisibility(View.VISIBLE);
            // view.setAnimation(ViewAnimation.fade(ViewAnimation.FADE_IN, 500, 0));
            // return false;
            // }
            // } else if (text.equals("-1")){
            // view.setVisibility(View.INVISIBLE);
            // return false;
            return false;
        }
    });
    mDeckListView.setOnItemClickListener(mDeckSelHandler);
    mDeckListView.setAdapter(mDeckListAdapter);

    if (mFragmented) {
        mDeckListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    registerForContextMenu(mDeckListView);

    showStartupScreensAndDialogs(preferences, 0);

    if (mSwipeEnabled) {
        gestureDetector = new GestureDetector(new MyGestureDetector());
        mDeckListView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
    }
}

From source file:com.fvd.nimbus.PaintActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    ContentResolver cr;/*from w w  w.j a  v a2  s .c o  m*/
    InputStream is;
    if (requestCode == TAKE_PHOTO) {
        showProgress(false);
        if (resultCode == -1) {
            try {
                if (data != null) {
                    if (data.hasExtra("data")) {
                        //Bitmap bm = ;
                        drawView.setVisibility(View.INVISIBLE);
                        drawView.recycle();
                        drawView.setBitmap((Bitmap) data.getParcelableExtra("data"), 0);
                        drawView.setVisibility(View.VISIBLE);

                    }
                } else {
                    if (outputFileUri != null) {
                        cr = getContentResolver();
                        try {
                            is = cr.openInputStream(outputFileUri);
                            Bitmap bmp = BitmapFactory.decodeStream(is);
                            if (bmp.getWidth() != -1 && bmp.getHeight() != -1) {
                                drawView.setVisibility(View.INVISIBLE);
                                drawView.recycle();
                                drawView.setBitmap(bmp, 0);
                                drawView.setVisibility(View.VISIBLE);
                            }
                        } catch (Exception e) {
                            appSettings.appendLog("paint:onCreate  " + e.getMessage());
                        }
                    }
                }
            } catch (Exception e) {
                appSettings.appendLog("main:onActivityResult: exception -  " + e.getMessage());
            }
        }
        ((ViewAnimator) findViewById(R.id.top_switcher)).setDisplayedChild(0);
    } else if (requestCode == TAKE_PICTURE) {
        showProgress(false);
        if (resultCode == -1 && data != null) {
            boolean temp = false;
            try {
                Uri resultUri = data.getData();
                String drawString = resultUri.getPath();
                InputStream input = getContentResolver().openInputStream(resultUri);

                drawView.setVisibility(View.INVISIBLE);
                drawView.recycle();
                drawView.setBitmap(BitmapFactory.decodeStream(input), 0);
                //drawView.forceRedraw();
                drawView.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                appSettings.appendLog("main:onActivityResult  " + e.getMessage());

            }
        }
        ((ViewAnimator) findViewById(R.id.top_switcher)).setDisplayedChild(0);
    } else if (requestCode == SHOW_SETTINGS) {
        switch (resultCode) {
        case RESULT_FIRST_USER + 1:
            Intent i = new Intent(getApplicationContext(), PrefsActivity.class);
            startActivity(i);
            //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
            overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
            break;
        case RESULT_FIRST_USER + 2:
            if (appSettings.sessionId.length() == 0)
                showLogin();
            else {
                appSettings.sessionId = "";
                //serverHelper.getInstance().setSessionId(appSettings.sessionId);
                Editor e = prefs.edit();
                e.putString("userMail", userMail);
                e.putString("userPass", "");
                e.putString("sessionId", appSettings.sessionId);
                e.commit();
                showLogin();
            }
            break;
        case RESULT_FIRST_USER + 3:
            try {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=" + getApplicationInfo().packageName)));
            } catch (Exception e) {
            }
        case RESULT_FIRST_USER + 4:
            Uri uri = Uri.parse(
                    "http://help.everhelper.me/customer/portal/articles/1376820-nimbus-clipper-for-android---quick-guide");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
            //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
            overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
            break;
        case RESULT_FIRST_USER + 5:
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this,
                    AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            alertDialogBuilder.setMessage(getScriptContent("license.txt")).setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // no alert dialog shown
                            //alertDialogShown = null;
                            // canceled
                            setResult(RESULT_CANCELED);
                            // and finish
                            //finish();
                        }
                    });
            // create alert dialog
            final AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.setTitle(getString(R.string.license_title));

            // and show
            //alertDialogShown = alertDialog;
            try {
                alertDialog.show();
            } catch (final java.lang.Exception e) {
                // nothing to do
            } catch (final java.lang.Error e) {
                // nothing to do
            }
            break;
        default:
            break;
        }
    }

    if (requestCode == 3) {
        if (resultCode == RESULT_OK || resultCode == RESULT_FIRST_USER) {
            userMail = data.getStringExtra("userMail");
            userPass = data.getStringExtra("userPass");
            if (resultCode == RESULT_OK)
                sendRequest("user:auth",
                        String.format("\"email\":\"%s\",\"password\":\"%s\"", userMail, userPass));
            else
                serverHelper.getInstance().sendOldRequest("user_register", String.format(
                        "{\"action\": \"user_register\",\"email\":\"%s\",\"password\":\"%s\",\"_client_software\": \"ff_addon\"}",
                        userMail, userPass), "");
        }
    } else if (requestCode == 11) {
        if (appSettings.sessionId != "") {
            sessionId = appSettings.sessionId;
            userPass = appSettings.userPass;
            sendShot();
        }
    } else if (requestCode == 4) {
        if (resultCode == RESULT_OK) {
            String id = data.getStringExtra("id").toString();
            serverHelper.getInstance().shareShot(id);
        }
    } else if (resultCode == RESULT_OK) {
        drawView.setColour(dColor);
        setPaletteColor(dColor);
        Uri resultUri = data.getData();
        String drawString = resultUri.getPath();
        String galleryString = getGalleryPath(resultUri);

        if (galleryString != null) {
            drawString = galleryString;
        }
        // else another file manager was used
        else {
            if (drawString.contains("//")) {
                drawString = drawString.substring(drawString.lastIndexOf("//"));
            }
        }

        // set the background to the selected picture
        if (drawString.length() > 0) {
            Drawable drawBackground = Drawable.createFromPath(drawString);
            drawView.setBackgroundDrawable(drawBackground);
        }

    }
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    if (requestCode == RC_SIGN_IN && !mGoogleApiKey && mGoogleApiClient != null) {
        new Thread(new Runnable() {
            @Override/*from   w ww  .j  a  v  a 2  s .co m*/
            public void run() {
                mIntentInProgress = false;
                mGoogleApiKey = true;
                // !mGoogleApiClient.isConnecting
                if (mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                } else
                    mGoogleApiClient.disconnect();

            }
        }).run();
    } else if (requestCode == image_selector_request_code) {
        if (sharedPref != null && intent != null && intent.getData() != null) {
            if (SDK_INT >= 19)
                getContentResolver().takePersistableUriPermission(intent.getData(),
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
            sharedPref.edit().putString("drawer_header_path", intent.getData().toString()).commit();
            setDrawerHeaderBackground();
        }
    } else if (requestCode == 3) {
        Uri treeUri;
        if (responseCode == Activity.RESULT_OK) {
            // Get Uri from Storage Access Framework.
            treeUri = intent.getData();
            // Persist URI - this is required for verification of writability.
            if (treeUri != null)
                sharedPref.edit().putString("URI", treeUri.toString()).commit();
        } else {
            // If not confirmed SAF, or if still not writable, then revert settings.
            /* DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false, currentFolder);
                ||!FileUtil.isWritableNormalOrSaf(currentFolder)*/
            return;
        }

        // After confirmation, update stored value of folder.
        // Persist access permissions.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        switch (operation) {
        case DataUtils.DELETE://deletion
            new DeleteTask(null, mainActivity).execute((oparrayList));
            break;
        case DataUtils.COPY://copying
            //legacy compatibility
            if (oparrayList != null && oparrayList.size() != 0) {
                oparrayListList = new ArrayList<>();
                oparrayListList.add(oparrayList);
                oparrayList = null;
                oppatheList = new ArrayList<>();
                oppatheList.add(oppathe);
                oppathe = "";
            }
            for (int i = 0; i < oparrayListList.size(); i++) {
                Intent intent1 = new Intent(con, CopyService.class);
                intent1.putExtra(CopyService.TAG_COPY_SOURCES, oparrayList.get(i));
                intent1.putExtra(CopyService.TAG_COPY_TARGET, oppatheList.get(i));
                ServiceWatcherUtil.runService(this, intent1);
            }
            break;
        case DataUtils.MOVE://moving
            //legacy compatibility
            if (oparrayList != null && oparrayList.size() != 0) {
                oparrayListList = new ArrayList<>();
                oparrayListList.add(oparrayList);
                oparrayList = null;
                oppatheList = new ArrayList<>();
                oppatheList.add(oppathe);
                oppathe = "";
            }

            new MoveFiles(oparrayListList, ((MainFragment) getFragment().getTab()),
                    getFragment().getTab().getActivity(), OpenMode.FILE)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, oppatheList);
            break;
        case DataUtils.NEW_FOLDER://mkdir
            MainFragment ma1 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.mkDir(RootHelper.generateBaseFile(new File(oppathe), true), ma1);
            break;
        case DataUtils.RENAME:
            MainFragment ma2 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.rename(ma2.openMode, (oppathe), (oppathe1), mainActivity, BaseActivity.rootMode);
            ma2.updateList();
            break;
        case DataUtils.NEW_FILE:
            MainFragment ma3 = ((MainFragment) getFragment().getTab());
            mainActivityHelper.mkFile(new HFile(OpenMode.FILE, oppathe), ma3);

            break;
        case DataUtils.EXTRACT:
            mainActivityHelper.extractFile(new File(oppathe));
            break;
        case DataUtils.COMPRESS:
            mainActivityHelper.compressFiles(new File(oppathe), oparrayList);
        }
        operation = -1;
    } else if (requestCode == REQUEST_CODE_SAF && responseCode == Activity.RESULT_OK) {
        // otg access
        sharedPref.edit().putString(KEY_PREF_OTG, intent.getData().toString()).apply();

        if (!isDrawerLocked)
            mDrawerLayout.closeDrawer(mDrawerLinear);
        else
            onDrawerClosed();
    } else if (requestCode == REQUEST_CODE_SAF && responseCode != Activity.RESULT_OK) {
        // otg access not provided
        pendingPath = null;
    }
}