Example usage for android.content Intent getAction

List of usage examples for android.content Intent getAction

Introduction

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

Prototype

public @Nullable String getAction() 

Source Link

Document

Retrieve the general action to be performed, such as #ACTION_VIEW .

Usage

From source file:RhodesService.java

private File downloadPackage(String url) throws IOException {
    final Context ctx = RhodesActivity.getContext();

    final Thread thisThread = Thread.currentThread();

    final Runnable cancelAction = new Runnable() {
        public void run() {
            thisThread.interrupt();/* ww  w  .  jav a 2 s .co  m*/
        }
    };

    BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setMessage("Cancel download?");
                AlertDialog dialog = builder.create();
                dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                cancelAction.run();
                            }
                        });
                dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Nothing
                            }
                        });
                dialog.show();
            } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) {
                cancelAction.run();
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD);
    filter.addAction(ACTION_CANCEL_DOWNLOAD);
    ctx.registerReceiver(downloadReceiver, filter);

    File tmpFile = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        updateDownloadNotification(url, -1, 0);

        /*
        List<File> folders = new ArrayList<File>();
        folders.add(Environment.getDownloadCacheDirectory());
        folders.add(Environment.getDataDirectory());
        folders.add(ctx.getCacheDir());
        folders.add(ctx.getFilesDir());
        try {
           folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir));
        } catch (NameNotFoundException e1) {
           // Ignore
        }
        folders.add(Environment.getExternalStorageDirectory());
                
        for (File folder : folders) {
           File tmpRootFolder = new File(folder, "rhodownload");
           File tmpFolder = new File(tmpRootFolder, ctx.getPackageName());
           if (tmpFolder.exists())
              deleteFilesInFolder(tmpFolder.getAbsolutePath());
           else
              tmpFolder.mkdirs();
                   
           File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk");
           Logger.D(TAG, "Check path " + of.getAbsolutePath() + "...");
           try {
              os = new FileOutputStream(of);
           }
           catch (FileNotFoundException e) {
              Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path");
              continue;
           }
           Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app");
                   
           tmpFile = of;
           break;
        }
        */

        tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk");
        os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE);

        Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "...");

        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int totalBytes = -1;
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            totalBytes = httpConn.getContentLength();
        }
        is = conn.getInputStream();

        int downloaded = 0;
        updateDownloadNotification(url, totalBytes, downloaded);

        long prevProgress = 0;
        byte[] buf = new byte[65536];
        for (;;) {
            if (thisThread.isInterrupted()) {
                tmpFile.delete();
                Logger.D(TAG, "Download of " + url + " was canceled");
                return null;
            }
            int nread = is.read(buf);
            if (nread == -1)
                break;

            //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes...");
            os.write(buf, 0, nread);

            downloaded += nread;
            if (totalBytes > 0) {
                // Update progress view only if current progress is greater than
                // previous by more than 10%. Otherwise, if update it very frequently,
                // user will no have chance to click on notification view and cancel if need
                long progress = downloaded * 10 / totalBytes;
                if (progress > prevProgress) {
                    updateDownloadNotification(url, totalBytes, downloaded);
                    prevProgress = progress;
                }
            }
        }

        Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath());

        return tmpFile;
    } catch (IOException e) {
        if (tmpFile != null)
            tmpFile.delete();
        throw e;
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }

        mNM.cancel(DOWNLOAD_PACKAGE_ID);
        ctx.unregisterReceiver(downloadReceiver);
    }
}

From source file:com.zertinteractive.wallpaper.MainActivity.java

public void initDownloadComponents() {

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override/*w ww .j a va2 s  . c  o  m*/
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                //
            }
        }
    };

    registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    unregisterReceiver(receiver);
}

From source file:com.ichi2.anki.NoteEditor.java

private void fetchIntentInformation(Intent intent) {
    Bundle extras = intent.getExtras();/*from www.  j a va2s  .  c om*/
    if (ACTION_CREATE_FLASHCARD.equals(intent.getAction())) {
        // mSourceLanguage = extras.getString(SOURCE_LANGUAGE);
        // mTargetLanguage = extras.getString(TARGET_LANGUAGE);
        mSourceText = new String[2];
        mSourceText[0] = extras.getString(SOURCE_TEXT);
        mSourceText[1] = extras.getString(TARGET_TEXT);
    } else {
        String first;
        String second;
        if (extras.getString(Intent.EXTRA_SUBJECT) != null) {
            first = extras.getString(Intent.EXTRA_SUBJECT);
        } else {
            first = "";
        }
        if (extras.getString(Intent.EXTRA_TEXT) != null) {
            second = extras.getString(Intent.EXTRA_TEXT);
        } else {
            second = "";
        }
        // Some users add cards via SEND intent from clipboard. In this case SUBJECT is empty
        if (first.equals("")) {
            // Assume that if only one field was sent then it should be the front
            first = second;
            second = "";
        }
        Pair<String, String> messages = new Pair<String, String>(first, second);

        mSourceText = new String[2];
        mSourceText[0] = messages.first;
        mSourceText[1] = messages.second;
    }
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

@Override
protected void onResume() {
    super.onResume();

    // CameraManager must be initialized here, not in onCreate(). This is
    // necessary because we don't
    // want to open the camera driver and measure the screen size if we're
    // going to show the help on
    // first launch. That led to bugs where the scanning rectangle was the
    // wrong size and partially
    // off screen.
    cameraManager = new CameraManager(getApplication());

    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
    viewfinderView.setCameraManager(cameraManager);

    resultView = findViewById(R.id.result_view);
    statusView = (TextView) findViewById(R.id.status_view);

    handler = null;//  w  w  w. java  2s .  co m
    lastResult = null;

    resetStatusView();

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
        // The activity was paused but not stopped, so the surface still
        // exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the
        // camera.
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    beepManager.updatePrefs();

    inactivityTimer.onResume();

    Intent intent = getIntent();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
            && (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));

    source = IntentSource.NONE;
    decodeFormats = null;
    characterSet = null;

    if (intent != null) {

        String action = intent.getAction();
        String dataString = intent.getDataString();

        if (Intents.Scan.ACTION.equals(action)) {

            // Scan the formats the intent requested, and return the result
            // to the calling activity.
            source = IntentSource.NATIVE_APP_INTENT;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);

            if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
                int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
                int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
                if (width > 0 && height > 0) {
                    cameraManager.setManualFramingRect(width, height);
                }
            }

            String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
            if (customPromptMessage != null) {
                statusView.setText(customPromptMessage);
            }

        } else if (dataString != null && dataString.contains(PRODUCT_SEARCH_URL_PREFIX)
                && dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {

            // Scan only products and send the result to mobile Product
            // Search.
            source = IntentSource.PRODUCT_SEARCH_LINK;
            sourceUrl = dataString;
            decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;

        } else if (isZXingURL(dataString)) {

            // Scan formats requested in query string (all formats if none
            // specified).
            // If a return URL is specified, send the results there.
            // Otherwise, handle it ourselves.
            source = IntentSource.ZXING_LINK;
            sourceUrl = dataString;
            Uri inputUri = Uri.parse(sourceUrl);
            returnUrlTemplate = inputUri.getQueryParameter(RETURN_URL_PARAM);
            returnRaw = inputUri.getQueryParameter(RAW_PARAM) != null;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);

        }

        characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);

    }
}

From source file:com.chatwing.whitelabel.activities.CommunicationActivity.java

private int getActionMode(Intent intent) {
    if (ACTION_OPEN_CONVERSATION.equals(intent.getAction())) {
        return MODE_CONVERSATION;
    }//from   w  w  w  .j  a  va2s. com
    if (ACTION_OPEN_CHATBOX.equals(intent.getAction())) {
        return MODE_CHAT_BOX;
    }
    return MODE_NONE;
}

From source file:gc.david.dfm.ui.MainActivity.java

/**
 * Handles all Intent types.//from w  ww.ja va 2s  .c o  m
 *
 * @param intent The input intent.
 */
private void handleIntents(final Intent intent) {
    Mint.leaveBreadcrumb("MainActivity::handleIntents");
    if (intent != null) {
        if (intent.getAction().equals(Intent.ACTION_SEARCH)) {
            handleSearchIntent(intent);
        } else if (intent.getAction().equals(Intent.ACTION_VIEW)) {
            try {
                handleViewPositionIntent(intent);
            } catch (Exception e) {
                e.printStackTrace();
                Mint.logException(e);
            }
        }
    }
}

From source file:net.fred.feedex.activity.EditFeedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    UiUtils.setPreferenceTheme(this);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_feed_edit);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*w ww.  j  ava  2s  . c o m*/
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    setResult(RESULT_CANCELED);

    Intent intent = getIntent();

    mTabHost = (TabHost) findViewById(R.id.tabHost);
    mNameEditText = (EditText) findViewById(R.id.feed_title);
    mUrlEditText = (EditText) findViewById(R.id.feed_url);
    mRetrieveFulltextCb = (CheckBox) findViewById(R.id.retrieve_fulltext);
    mFiltersListView = (ListView) findViewById(android.R.id.list);
    View tabWidget = findViewById(android.R.id.tabs);

    mTabHost.setup();
    mTabHost.addTab(mTabHost.newTabSpec("feedTab").setIndicator(getString(R.string.tab_feed_title))
            .setContent(R.id.feed_tab));
    mTabHost.addTab(mTabHost.newTabSpec("filtersTab").setIndicator(getString(R.string.tab_filters_title))
            .setContent(R.id.filters_tab));

    mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String s) {
            invalidateOptionsMenu();
        }
    });

    if (savedInstanceState != null) {
        mTabHost.setCurrentTab(savedInstanceState.getInt(STATE_CURRENT_TAB));
    }

    if (intent.getAction().equals(Intent.ACTION_INSERT) || intent.getAction().equals(Intent.ACTION_SEND)) {
        setTitle(R.string.new_feed_title);

        tabWidget.setVisibility(View.GONE);

        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            mUrlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    } else if (intent.getAction().equals(Intent.ACTION_VIEW)) {
        setTitle(R.string.new_feed_title);

        tabWidget.setVisibility(View.GONE);
        mUrlEditText.setText(intent.getDataString());
    } else if (intent.getAction().equals(Intent.ACTION_EDIT)) {
        setTitle(R.string.edit_feed_title);

        mFiltersCursorAdapter = new FiltersCursorAdapter(this, Constants.EMPTY_CURSOR);
        mFiltersListView.setAdapter(mFiltersCursorAdapter);
        mFiltersListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                startSupportActionMode(mFilterActionModeCallback);
                mFiltersCursorAdapter.setSelectedFilter(position);
                mFiltersListView.invalidateViews();
                return true;
            }
        });

        getLoaderManager().initLoader(0, null, this);

        if (savedInstanceState == null) {
            Cursor cursor = getContentResolver().query(intent.getData(), FEED_PROJECTION, null, null, null);

            if (cursor != null && cursor.moveToNext()) {
                mNameEditText.setText(cursor.getString(0));
                mUrlEditText.setText(cursor.getString(1));
                mRetrieveFulltextCb.setChecked(cursor.getInt(2) == 1);
                if (cursor.getInt(3) == 1) { // if it's a group, we cannot edit it
                    finish();
                }
            } else {
                UiUtils.showMessage(EditFeedActivity.this, R.string.error);
                finish();
            }

            if (cursor != null) {
                cursor.close();
            }
        }
    }
}

From source file:com.carlrice.reader.activity.EditFeedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    UiUtils.setPreferenceTheme(this);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_feed_edit);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//w ww .j ava2s  . c  o  m
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    setResult(RESULT_CANCELED);

    Intent intent = getIntent();

    mTabHost = (TabHost) findViewById(R.id.tabHost);
    mNameEditText = (EditText) findViewById(R.id.feed_title);
    mUrlEditText = (EditText) findViewById(R.id.feed_url);
    mRetrieveFulltextCb = (CheckBox) findViewById(R.id.retrieve_fulltext);
    mFiltersListView = (ListView) findViewById(android.R.id.list);
    View tabWidget = findViewById(android.R.id.tabs);
    View buttonLayout = findViewById(R.id.button_layout);

    mTabHost.setup();
    mTabHost.addTab(mTabHost.newTabSpec("feedTab").setIndicator(getString(R.string.tab_feed_title))
            .setContent(R.id.feed_tab));
    mTabHost.addTab(mTabHost.newTabSpec("filtersTab").setIndicator(getString(R.string.tab_filters_title))
            .setContent(R.id.filters_tab));

    mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String s) {
            invalidateOptionsMenu();
        }
    });

    if (savedInstanceState != null) {
        mTabHost.setCurrentTab(savedInstanceState.getInt(STATE_CURRENT_TAB));
    }

    if (intent.getAction().equals(Intent.ACTION_INSERT) || intent.getAction().equals(Intent.ACTION_SEND)) {
        setTitle(R.string.new_feed_title);

        tabWidget.setVisibility(View.GONE);

        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            mUrlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    } else if (intent.getAction().equals(Intent.ACTION_EDIT)) {
        setTitle(R.string.edit_feed_title);

        buttonLayout.setVisibility(View.GONE);

        mFiltersCursorAdapter = new FiltersCursorAdapter(this, Constants.EMPTY_CURSOR);
        mFiltersListView.setAdapter(mFiltersCursorAdapter);
        mFiltersListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                startSupportActionMode(mFilterActionModeCallback);
                mFiltersCursorAdapter.setSelectedFilter(position);
                mFiltersListView.invalidateViews();
                return true;
            }
        });

        getLoaderManager().initLoader(0, null, this);

        if (savedInstanceState == null) {
            Cursor cursor = getContentResolver().query(intent.getData(), FEED_PROJECTION, null, null, null);

            if (cursor.moveToNext()) {
                mNameEditText.setText(cursor.getString(0));
                mUrlEditText.setText(cursor.getString(1));
                mRetrieveFulltextCb.setChecked(cursor.getInt(2) == 1);
                cursor.close();
            } else {
                cursor.close();
                Toast.makeText(EditFeedActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
}

From source file:com.dycody.android.idealnote.ListFragment.java

/**
 * Notes list adapter initialization and association to view
 *///from w w  w . j  ava2 s .com
void initNotesList(Intent intent) {
    Log.d(Constants.TAG, "initNotesList intent: " + intent.getAction());

    progress_wheel.setAlpha(1);
    list.setAlpha(0);

    // Search for a tag
    // A workaround to simplify it's to simulate normal search
    if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getCategories() != null
            && intent.getCategories().contains(Intent.CATEGORY_BROWSABLE)) {
        searchTags = intent.getDataString().replace(UrlCompleter.HASHTAG_SCHEME, "");
        goBackOnToggleSearchLabel = true;
    }

    // Searching
    searchQuery = searchQueryInstant;
    searchQueryInstant = null;
    if (searchTags != null || searchQuery != null || Intent.ACTION_SEARCH.equals(intent.getAction())) {

        // Using tags
        if (searchTags != null && intent.getStringExtra(SearchManager.QUERY) == null) {
            searchQuery = searchTags;
            NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByTag",
                    searchQuery);
        } else {
            // Get the intent, verify the action and get the query
            if (intent.getStringExtra(SearchManager.QUERY) != null) {
                searchQuery = intent.getStringExtra(SearchManager.QUERY);
                searchTags = null;
            }
            NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getNotesByPattern",
                    searchQuery);
        }

        toggleSearchLabel(true);

    } else {
        // Check if is launched from a widget with categories
        if ((Constants.ACTION_WIDGET_SHOW_LIST.equals(intent.getAction())
                && intent.hasExtra(Constants.INTENT_WIDGET))
                || !TextUtils.isEmpty(mainActivity.navigationTmp)) {
            String widgetId = intent.hasExtra(Constants.INTENT_WIDGET)
                    ? intent.getExtras().get(Constants.INTENT_WIDGET).toString()
                    : null;
            if (widgetId != null) {
                String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, "");
                String categoryId = TextHelper.checkIntentCategory(sqlCondition);
                mainActivity.navigationTmp = !TextUtils.isEmpty(categoryId) ? categoryId : null;
            }
            intent.removeExtra(Constants.INTENT_WIDGET);
            if (mainActivity.navigationTmp != null) {
                Long categoryId = Long.parseLong(mainActivity.navigationTmp);
                NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                        "getNotesByCategory", categoryId);
            } else {
                NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes",
                        true);
            }

        } else {
            NoteLoaderTask.getInstance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "getAllNotes", true);
        }
    }
}