Example usage for android.content Intent setClassName

List of usage examples for android.content Intent setClassName

Introduction

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

Prototype

public @NonNull Intent setClassName(@NonNull String packageName, @NonNull String className) 

Source Link

Document

Convenience for calling #setComponent with an explicit application package name and class name.

Usage

From source file:org.openintents.shopping.ui.ShoppingActivity.java

/**
 * Hook up buttons, lists, and edittext with functionality.
 *//* w w w . j av a 2s  .c  o m*/
private void createView() {

    // Temp-create either Spinner or List based upon the Display
    createList();

    mAddPanel = findViewById(R.id.add_panel);
    mEditText = (AutoCompleteTextView) findViewById(R.id.autocomplete_add_item);

    fillAutoCompleteTextViewAdapter(mEditText);
    mEditText.setThreshold(1);
    mEditText.setOnKeyListener(new OnKeyListener() {

        private int mLastKeyAction = KeyEvent.ACTION_UP;

        public boolean onKey(View v, int keyCode, KeyEvent key) {
            // Shortcut: Instead of pressing the button,
            // one can also press the "Enter" key.
            if (debug) {
                Log.i(TAG, "Key action: " + key.getAction());
            }
            if (debug) {
                Log.i(TAG, "Key code: " + keyCode);
            }
            if (keyCode == KeyEvent.KEYCODE_ENTER) {

                if (mEditText.isPopupShowing()) {
                    mEditText.performCompletion();
                }

                // long key press might cause call of duplicate onKey events
                // with ACTION_DOWN
                // this would result in inserting an item and showing the
                // pick list

                if (key.getAction() == KeyEvent.ACTION_DOWN && mLastKeyAction == KeyEvent.ACTION_UP) {
                    insertNewItem();
                }

                mLastKeyAction = key.getAction();
                return true;
            }
            return false;
        }
    });
    mEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (mItemsView.mMode == MODE_ADD_ITEMS) {
                // small optimization: Only care about updating
                // the button label on each key pressed if we
                // are in "add items" mode.
                updateButton();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

    });

    mButton = (Button) findViewById(R.id.button_add_item);
    mButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            insertNewItem();
        }
    });
    mButton.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (PreferenceActivity.getAddForBarcode(getApplicationContext()) == false) {
                if (debug) {
                    Log.v(TAG, "barcode scanner on add button long click disabled");
                }
                return false;
            }

            Intent intent = new Intent();
            intent.setData(mListUri);
            intent.setClassName("org.openintents.barcodescanner",
                    "org.openintents.barcodescanner.BarcodeScanner");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            try {
                startActivityForResult(intent, REQUEST_CODE_CATEGORY_ALTERNATIVE);
            } catch (ActivityNotFoundException e) {
                if (debug) {
                    Log.v(TAG, "barcode scanner not found");
                }
                showDialog(DIALOG_GET_FROM_MARKET);
                return false;
            }

            // Instead of calling the class of barcode
            // scanner directly, a more generic approach would
            // be to use a general activity picker.
            //
            // TODO: Implement onActivityResult.
            // Problem: User has to pick activity every time.
            // Choice should be storeable in Stettings.
            // Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            // intent.setData(mListUri);
            // intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            //
            // Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
            // pickIntent.putExtra(Intent.EXTRA_INTENT, intent);
            // pickIntent.putExtra(Intent.EXTRA_TITLE,
            // getText(R.string.title_select_item_from));
            // try {
            // startActivityForResult(pickIntent,
            // REQUEST_CODE_CATEGORY_ALTERNATIVE);
            // } catch (ActivityNotFoundException e) {
            // Log.v(TAG, "barcode scanner not found");
            // return false;
            // }
            return true;
        }
    });

    mLayoutParamsItems = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    mToastBar = (ActionableToastBar) findViewById(R.id.toast_bar);

    mItemsView = (ShoppingItemsView) findViewById(R.id.list_items);
    mItemsView.setThemedBackground(findViewById(R.id.background));
    mItemsView.setCustomClickListener(this);
    mItemsView.setToastBar(mToastBar);
    mItemsView.initTotals();

    mItemsView.setItemsCanFocus(true);
    mItemsView.setDragListener(new DragListener() {

        @Override
        public void drag(int from, int to) {
            if (debug) {
                Log.v("DRAG", "" + from + "/" + to);
            }

        }
    });
    mItemsView.setDropListener(new DropListener() {

        @Override
        public void drop(int from, int to) {
            if (debug) {
                Log.v("DRAG", "" + from + "/" + to);
            }

        }
    });

    mItemsView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView parent, View v, int pos, long id) {
            Cursor c = (Cursor) parent.getItemAtPosition(pos);
            onCustomClick(c, pos, EditItemDialog.FieldType.ITEMNAME, v);
            // DO NOT CLOSE THIS CURSOR - IT IS A MANAGED ONE.
            // ---- c.close();
        }

    });

    mItemsView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

        public void onCreateContextMenu(ContextMenu contextmenu, View view, ContextMenuInfo info) {
            contextmenu.add(0, MENU_EDIT_ITEM, 0, R.string.menu_edit_item).setShortcut('1', 'e');
            contextmenu.add(0, MENU_MARK_ITEM, 0, R.string.menu_mark_item).setShortcut('2', 'm');
            contextmenu.add(0, MENU_ITEM_STORES, 0, R.string.menu_item_stores).setShortcut('3', 's');
            contextmenu.add(0, MENU_REMOVE_ITEM_FROM_LIST, 0, R.string.menu_remove_item).setShortcut('4', 'r');
            contextmenu.add(0, MENU_COPY_ITEM, 0, R.string.menu_copy_item).setShortcut('5', 'c');
            contextmenu.add(0, MENU_DELETE_ITEM, 0, R.string.menu_delete_item).setShortcut('6', 'd');
            contextmenu.add(0, MENU_MOVE_ITEM, 0, R.string.menu_move_item).setShortcut('7', 'l');
        }

    });
}

From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java

private void launchGoogleMapsForDirections(LatLng _origin, LatLng _destination, boolean _walking) {
    StringBuilder builder = new StringBuilder("http://maps.google.com/maps?&saddr=");

    builder.append(_origin.latitude).append(",").append(_origin.longitude);

    builder.append("&daddr=").append(_destination.latitude).append(",").append(_destination.longitude).
    //append("B"). Labeling doesn't work :'(
            append("&dirflg=");

    if (_walking)
        builder.append("w");
    else//  w  w  w . j  a v  a2s  .c  o  m
        builder.append("b");

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(builder.toString()));
    intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
    if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
        startActivity(intent); // launch the map activity
    } else {
        Utils.Snackbar.makeStyled(mCoordinatorLayout, R.string.google_maps_not_installed, Snackbar.LENGTH_SHORT,
                ContextCompat.getColor(this, R.color.theme_primary_dark)).show();
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String StrtUpdtOMatic(String sPkgName, String sPkgFileName, String sCallBackIP, String sCallBackPort) {
    String sRet = "";

    Context ctx = contextWrapper.getApplicationContext();
    PackageManager pm = ctx.getPackageManager();

    Intent prgIntent = new Intent();
    prgIntent.setPackage("com.mozilla.watcher");

    try {//  w w  w  . j a  v a  2s  .c o m
        PackageInfo pi = pm.getPackageInfo("com.mozilla.watcher",
                PackageManager.GET_SERVICES | PackageManager.GET_INTENT_FILTERS);
        ServiceInfo[] si = pi.services;
        for (int i = 0; i < si.length; i++) {
            ServiceInfo s = si[i];
            if (s.name.length() > 0) {
                prgIntent.setClassName(s.packageName, s.name);
                break;
            }
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        sRet = sErrorPrefix + "watcher is not properly installed";
        return (sRet);
    }

    prgIntent.putExtra("command", "updt");
    prgIntent.putExtra("pkgName", sPkgName);
    prgIntent.putExtra("pkgFile", sPkgFileName);
    prgIntent.putExtra("reboot", true);

    try {
        if ((sCallBackIP != null) && (sCallBackPort != null) && (sCallBackIP.length() > 0)
                && (sCallBackPort.length() > 0)) {
            FileOutputStream fos = ctx.openFileOutput("update.info",
                    Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
            String sBuffer = sCallBackIP + "," + sCallBackPort + "\rupdate started " + sPkgName + " "
                    + sPkgFileName + "\r";
            fos.write(sBuffer.getBytes());
            fos.flush();
            fos.close();
            fos = null;
            prgIntent.putExtra("outFile", ctx.getFilesDir() + "/update.info");
        } else {
            if (prgIntent.hasExtra("outFile")) {
                System.out.println("outFile extra unset from intent");
                prgIntent.removeExtra("outFile");
            }
        }

        ComponentName cn = contextWrapper.startService(prgIntent);
        if (cn != null)
            sRet = "exit";
        else
            sRet = sErrorPrefix + "Unable to use watcher service";
    } catch (ActivityNotFoundException anf) {
        sRet = sErrorPrefix + "Activity Not Found Exception [updt] call failed";
        anf.printStackTrace();
    } catch (FileNotFoundException e) {
        sRet = sErrorPrefix + "File creation error [updt] call failed";
        e.printStackTrace();
    } catch (IOException e) {
        sRet = sErrorPrefix + "File error [updt] call failed";
        e.printStackTrace();
    }

    ctx = null;

    return (sRet);
}

From source file:org.mozilla.gecko.BrowserApp.java

@Override
public void handleMessage(String event, JSONObject message) {
    try {/* w w  w  .  j ava  2  s  .  co m*/
        if (event.equals("Menu:Open")) {
            if (mBrowserToolbar.isEditing()) {
                mBrowserToolbar.cancelEdit();
            }

            openOptionsMenu();
        } else if (event.equals("Menu:Update")) {
            final int id = message.getInt("id") + ADDON_MENU_OFFSET;
            final JSONObject options = message.getJSONObject("options");
            ThreadUtils.postToUiThread(new Runnable() {
                @Override
                public void run() {
                    updateAddonMenuItem(id, options);
                }
            });
        } else if (event.equals("Gecko:DelayedStartup")) {
            ThreadUtils.postToUiThread(new Runnable() {
                @Override
                public void run() {
                    // Force tabs panel inflation once the initial
                    // pageload is finished.
                    ensureTabsPanelExists();
                }
            });

            if (AppConstants.MOZ_MEDIA_PLAYER) {
                // Check if the fragment is already added. This should never be true here, but this is
                // a nice safety check.
                // If casting is disabled, these classes aren't built. We use reflection to initialize them.
                final Class<?> mediaManagerClass = getMediaPlayerManager();

                if (mediaManagerClass != null) {
                    try {
                        final String tag = "";
                        mediaManagerClass.getDeclaredField("MEDIA_PLAYER_TAG").get(tag);
                        Log.i(LOGTAG, "Found tag " + tag);
                        final Fragment frag = getSupportFragmentManager().findFragmentByTag(tag);
                        if (frag == null) {
                            final Method getInstance = mediaManagerClass.getMethod("newInstance",
                                    (Class[]) null);
                            final Fragment mpm = (Fragment) getInstance.invoke(null);
                            getSupportFragmentManager().beginTransaction().disallowAddToBackStack()
                                    .add(mpm, tag).commit();
                        }
                    } catch (Exception ex) {
                        Log.e(LOGTAG, "Error initializing media manager", ex);
                    }
                }
            }

            if (AppConstants.MOZ_STUMBLER_BUILD_TIME_ENABLED
                    && RestrictedProfiles.isAllowed(this, Restriction.DISALLOW_LOCATION_SERVICE)) {
                // Start (this acts as ping if started already) the stumbler lib; if the stumbler has queued data it will upload it.
                // Stumbler operates on its own thread, and startup impact is further minimized by delaying work (such as upload) a few seconds.
                // Avoid any potential startup CPU/thread contention by delaying the pref broadcast.
                final long oneSecondInMillis = 1000;
                ThreadUtils.getBackgroundHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        GeckoPreferences.broadcastStumblerPref(BrowserApp.this);
                    }
                }, oneSecondInMillis);
            }

            super.handleMessage(event, message);
        } else if (event.equals("Gecko:Ready")) {
            // Handle this message in GeckoApp, but also enable the Settings
            // menuitem, which is specific to BrowserApp.
            super.handleMessage(event, message);
            final Menu menu = mMenu;
            ThreadUtils.postToUiThread(new Runnable() {
                @Override
                public void run() {
                    if (menu != null) {
                        menu.findItem(R.id.settings).setEnabled(true);
                        menu.findItem(R.id.help).setEnabled(true);
                    }
                }
            });

            // Display notification for Mozilla data reporting, if data should be collected.
            if (AppConstants.MOZ_DATA_REPORTING) {
                DataReportingNotification.checkAndNotifyPolicy(GeckoAppShell.getContext());
            }

        } else if (event.equals("Search:Keyword")) {
            storeSearchQuery(message.getString("query"));
        } else if (event.equals("LightweightTheme:Update")) {
            ThreadUtils.postToUiThread(new Runnable() {
                @Override
                public void run() {
                    mDynamicToolbar.setVisible(true, VisibilityTransition.ANIMATE);
                }
            });
        } else if (event.equals("Prompt:ShowTop")) {
            // Bring this activity to front so the prompt is visible..
            Intent bringToFrontIntent = new Intent();
            bringToFrontIntent.setClassName(AppConstants.ANDROID_PACKAGE_NAME,
                    AppConstants.MOZ_ANDROID_BROWSER_INTENT_CLASS);
            bringToFrontIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(bringToFrontIntent);
        } else if (event.equals("Accounts:Exist")) {
            final String kind = message.getString("kind");
            final JSONObject response = new JSONObject();

            if ("any".equals(kind)) {
                response.put("exists", SyncAccounts.syncAccountsExist(getContext())
                        || FirefoxAccounts.firefoxAccountsExist(getContext()));
                EventDispatcher.sendResponse(message, response);
            } else if ("fxa".equals(kind)) {
                response.put("exists", FirefoxAccounts.firefoxAccountsExist(getContext()));
                EventDispatcher.sendResponse(message, response);
            } else if ("sync11".equals(kind)) {
                response.put("exists", SyncAccounts.syncAccountsExist(getContext()));
                EventDispatcher.sendResponse(message, response);
            } else {
                response.put("error", "Unknown kind");
                EventDispatcher.sendError(message, response);
            }
        } else {
            super.handleMessage(event, message);
        }
    } catch (Exception e) {
        Log.e(LOGTAG, "Exception handling message \"" + event + "\":", e);
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String StartJavaPrg(String[] sArgs, Intent preIntent) {
    String sRet = "";
    String sArgList = "";
    String sUrl = "";
    //        String sRedirFileName = "";
    Intent prgIntent = null;

    Context ctx = contextWrapper.getApplicationContext();
    PackageManager pm = ctx.getPackageManager();

    if (preIntent == null)
        prgIntent = new Intent();
    else//from ww w  .  j  ava 2 s .  c om
        prgIntent = preIntent;

    prgIntent.setPackage(sArgs[0]);
    prgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Get the main activity for this package
    try {
        final ComponentName c = pm.getLaunchIntentForPackage(sArgs[0]).getComponent();
        prgIntent.setClassName(c.getPackageName(), c.getClassName());
    } catch (Exception e) {
        e.printStackTrace();
        return "Unable to find main activity for package: " + sArgs[0];
    }

    if (sArgs.length > 1) {
        if (sArgs[0].contains("android.browser"))
            prgIntent.setAction(Intent.ACTION_VIEW);
        else
            prgIntent.setAction(Intent.ACTION_MAIN);

        if (sArgs[0].contains("fennec") || sArgs[0].contains("firefox")) {
            sArgList = "";
            sUrl = "";

            for (int lcv = 1; lcv < sArgs.length; lcv++) {
                if (sArgs[lcv].contains("://")) {
                    prgIntent.setAction(Intent.ACTION_VIEW);
                    sUrl = sArgs[lcv];
                } else {
                    if (sArgs[lcv].equals(">")) {
                        lcv++;
                        if (lcv < sArgs.length)
                            lcv++;
                        //                                sRedirFileName = sArgs[lcv++];
                    } else
                        sArgList += " " + sArgs[lcv];
                }
            }

            if (sArgList.length() > 0)
                prgIntent.putExtra("args", sArgList.trim());

            if (sUrl.length() > 0)
                prgIntent.setData(Uri.parse(sUrl.trim()));
        } else {
            for (int lcv = 1; lcv < sArgs.length; lcv++)
                sArgList += " " + sArgs[lcv];

            prgIntent.setData(Uri.parse(sArgList.trim()));
        }
    } else {
        prgIntent.setAction(Intent.ACTION_MAIN);
    }

    try {
        contextWrapper.startActivity(prgIntent);
        FindProcThread findProcThrd = new FindProcThread(contextWrapper, sArgs[0]);
        findProcThrd.start();
        findProcThrd.join(7000);
        if (!findProcThrd.bFoundIt && !findProcThrd.bStillRunning) {
            sRet = "Unable to start " + sArgs[0] + "";
        }
    } catch (ActivityNotFoundException anf) {
        anf.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    ctx = null;
    return (sRet);
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void invokeTextFileBrowser(FileListAdapter fla, final String item_optyp, final String item_name,
        final boolean item_isdir, final int item_num) {
    FileListItem item = fla.getItem(item_num);
    try {// ww w .ja  v a  2 s.  c  o  m
        Intent intent;
        intent = new Intent();
        intent.setClassName("com.sentaroh.android.TextFileBrowser",
                "com.sentaroh.android.TextFileBrowser.MainActivity");
        intent.setDataAndType(Uri.parse("file://" + item.getPath() + "/" + item.getName()), null);
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        //         commonDlg.showCommonDialog(false,"E", "TextFileBrowser can not be found.",
        //               "File name="+item.getName(),null);
        showDialogMsg("E", "TextFileBrowser can not be found.", "File name=" + item.getName());
    }
}

From source file:android.app.Activity.java

protected void testMode(String[] path) {
    int TESTCODE = 1;

    FileWorker fw = new FileWorker(path, FileWorker.READ_MODE);
    fw.start();/*  ww w  .  j a  v  a2  s  .  c o m*/

    Intent intent = new Intent();
    intent.setClassName("com.android.migrationmanager", "com.android.migrationmanager.TestMode");
    startActivityForResult(intent, TESTCODE);
}

From source file:android.app.Activity.java

/**
 * execute migration immediately with file(s)
 * NOTE: if you call this method, Activity will perform finish()
 * @param paths Absolute filepaths you want to migrate
 *//*from  ww  w.j  a v  a  2  s .co  m*/
public void migrate(String[] paths) {
    boolean result = false;
    Bundle savedBundle;

    if (paths != null) {
        FileWorker fw = new FileWorker(paths, FileWorker.READ_MODE);
        fw.start();
    }

    Intent intent = new Intent();
    intent.setClassName("com.android.migrationmanager", "com.android.migrationmanager.DeviceListDialog");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
}

From source file:android.app.Activity.java

/**
 * @hide/*  www.j a v  a  2 s.c  o m*/
 */
private void showMigrateNotification() {

    boolean flag = false;

    if (mMigrator == null) {
        mMigrator = IMigratorService.Stub.asInterface(ServiceManager.getService("Migrator"));
    }
    try {
        /* judge whether this App can migrate */
        flag = mMigrator.checkMigratableApp();
    } catch (RemoteException e) {
        Log.d(TAG, "Migrate failed in Dialog");
    }

    if (flag) {
        Intent intent = new Intent();
        intent.setClassName("com.android.migrationmanager", "com.android.migrationmanager.DeviceListDialog");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        /* on tapping, show dialog Activity */

        Notification notification = new Notification.Builder(this)
                .setContentTitle("Migrator in " + getAppName())
                .setContentText("start Migration: " + getLocalClassName())
                .setSmallIcon(com.android.internal.R.drawable.ic_menu_send).setAutoCancel(true)
                .setContentIntent(pi).build();

        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        nm.notify(Process.myUid(), notification);
    }
}