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:nz.co.wholemeal.christchurchmetro.FavouritesActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
    case R.id.map:
        Log.d(TAG, "Map selected from menu");
        intent = new Intent();
        intent.setClassName("nz.co.wholemeal.christchurchmetro",
                "nz.co.wholemeal.christchurchmetro.MetroMapActivity");
        startActivity(intent);//from w  ww . j  a va  2s. c  om
        return true;
    case R.id.search:
        Log.d(TAG, "Search selected from menu");
        onSearchRequested();
        return true;
    case R.id.routes:
        Log.d(TAG, "Routes selected from menu");
        intent = new Intent();
        intent.setClassName("nz.co.wholemeal.christchurchmetro",
                "nz.co.wholemeal.christchurchmetro.RoutesActivity");
        startActivity(intent);
        return true;
    case R.id.preferences:
        Log.d(TAG, "Preferences selected from menu");
        intent = new Intent();
        intent.setClassName("nz.co.wholemeal.christchurchmetro",
                "nz.co.wholemeal.christchurchmetro.PreferencesActivity");
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.hanuor.sapphire.utils.intentation.IntentationPrime.java

public Intent jsonToINTENT(String JSONString) throws JSONException {

    JSONObject jsonObject = new JSONObject(JSONString.toString());
    String toArray = jsonObject.get("intentExtras").toString();
    String contextName = jsonObject.get("context").toString();
    String className = jsonObject.get("className").toString();
    Log.d("Insass", className.toString());

    Intent setIntent = new Intent();
    setIntent.setClassName(contextName, className);
    HashMap<String, String> extrasHash = new HashMap<String, String>();
    JSONObject issueObj = new JSONObject(toArray);
    for (int i = 0; i < issueObj.length(); i++) {
        extrasHash.put(issueObj.names().getString(i), issueObj.get(issueObj.names().getString(i)).toString());
    }/* www.  j  a va  2  s  .c  o m*/
    Iterator it = extrasHash.entrySet().iterator();
    while (it.hasNext()) {
        //add conditions  and checks here

        Map.Entry pair = (Map.Entry) it.next();
        String currentKey = (String) pair.getKey();
        Log.d("HAHA", "" + currentKey);
        String[] getValuethroughSplit = pair.getValue().toString().split(LibraryDatabase.JSONSEPERATOR);
        String dataType = getValuethroughSplit[0];
        String value = (String) getValuethroughSplit[2];
        Log.d("Insamareen", getValuethroughSplit.length + " " + dataType + " " + value.toString());
        switch (dataType) {
        case "String":
            setIntent.putExtra(currentKey, (String) value);
            break;
        case "String[]":
            String comp1 = value.substring(1, value.length() - 1);
            String[] comp2 = comp1.split(",");
            setIntent.putExtra(currentKey, comp2);
            break;
        case "Integer":
            setIntent.putExtra(currentKey, Integer.parseInt(value));
            break;
        case "Double":

            setIntent.putExtra(currentKey, Double.parseDouble(value));

            break;
        case "double[]":
            String compDouble1 = value.substring(1, value.length() - 1);
            String[] compDoub2 = compDouble1.split(",");
            double[] db = new double[compDoub2.length];
            for (int i = 0; i < compDoub2.length; i++) {
                db[i] = Double.parseDouble(compDoub2[i]);
            }
            setIntent.putExtra(currentKey, db);
            break;
        case "int[]":
            String compInt1 = value.substring(1, value.length() - 1);
            String[] compInt2 = compInt1.split(",");
            int[] intVal = new int[compInt2.length];
            for (int i = 0; i < compInt2.length; i++) {
                intVal[i] = Integer.parseInt(compInt2[i]);
            }
            Log.d("Hankey", intVal.toString());
            setIntent.putExtra(currentKey, intVal);

            break;
        case "Boolean":
            setIntent.putExtra(currentKey, Boolean.valueOf(value));

            break;
        case "boolean[]":
            String compB1 = value.substring(1, value.length() - 1);
            String[] compB2 = compB1.split(",");
            boolean[] BVal = new boolean[compB2.length];
            for (int i = 0; i < compB2.length; i++) {
                BVal[i] = Boolean.parseBoolean(compB2[i]);
            }
            setIntent.putExtra(currentKey, value);

            break;
        case "Char":
            setIntent.putExtra(currentKey, value);

            break;
        case "char[]":

            String ch1 = value.substring(1, value.length() - 1);
            String[] ch2 = ch1.split(",");
            String newS = null;
            for (int i = 0; i < ch2.length; i++) {
                newS = newS + ch2[i];
            }
            setIntent.putExtra(currentKey, newS.toCharArray());

            break;
        case "CharSequence":
            setIntent.putExtra(currentKey, (CharSequence) value);

            break;
        case "Charsequence[]":
            setIntent.putExtra(currentKey, value.toString());

            break;
        case "Byte":
            setIntent.putExtra(currentKey, Byte.valueOf(value));

            break;
        case "byte[]":
            String by = value.substring(1, value.length() - 1);
            String[] by2 = by.split(",");
            byte[] by3 = new byte[by2.length];
            for (int i = 0; i < by2.length; i++) {
                by3[i] = Byte.parseByte(by2[i]);
            }
            setIntent.putExtra(currentKey, by3);

            break;
        case "Float":
            setIntent.putExtra(currentKey, Float.valueOf(value));

            break;
        case "float[]":
            String fl = value.substring(1, value.length() - 1);
            String[] fl2 = fl.split(",");
            float[] fl3 = new float[fl2.length];
            for (int i = 0; i < fl2.length; i++) {
                fl3[i] = Float.parseFloat(fl2[i]);
            }
            setIntent.putExtra(currentKey, fl3);

            break;
        case "Short":
            setIntent.putExtra(currentKey, Short.valueOf(value));

            break;
        case "short[]":
            String sh = value.substring(1, value.length() - 1);
            String[] sh2 = sh.split(",");
            short[] sh3 = new short[sh2.length];
            for (int i = 0; i < sh2.length; i++) {
                sh3[i] = Short.parseShort(sh2[i]);
            }
            setIntent.putExtra(currentKey, sh3);

            break;
        case "Long":
            setIntent.putExtra(currentKey, Long.valueOf(value));

            break;
        case "long[]":
            String ll = value.substring(1, value.length() - 1);
            String[] ll2 = ll.split(",");
            long[] ll3 = new long[ll2.length];
            for (int i = 0; i < ll2.length; i++) {
                ll3[i] = Long.parseLong(ll2[i]);
            }
            setIntent.putExtra(currentKey, ll3);

            break;

        case "ArrayListString":
            Log.d("Hankey", currentKey + " ");
            String arrL = value.substring(1, value.length() - 1);
            String[] arrl2 = arrL.split(",");
            ArrayList<String> arrStr = new ArrayList<String>();
            for (int i = 0; i < arrl2.length; i++) {
                arrStr.add(arrl2[i]);
            }
            setIntent.putStringArrayListExtra(currentKey, arrStr);

            break;
        case "ArrayListInteger":
            String arL = value.substring(1, value.length() - 1);
            String[] arl2 = arL.split(",");
            ArrayList<Integer> arrInt = new ArrayList<Integer>();
            for (int i = 0; i < arl2.length; i++) {
                arrInt.add(Integer.parseInt(arl2[i]));
            }

            setIntent.putIntegerArrayListExtra(currentKey, arrInt);

            break;
        default:
            // whatever
        }
    }
    return setIntent;
}

From source file:arun.com.chromer.browsing.customtabs.CustomTabs.java

/**
 * Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView.
 *//*from ww w.j  a  v a  2 s.co  m*/
private void openCustomTab() {
    final String packageName = getCustomTabPackage(activity);
    final CustomTabsIntent customTabsIntent = builder.build();
    final Uri uri = Uri.parse(url);
    if (packageName != null) {
        customTabsIntent.intent.setPackage(packageName);
        final Intent keepAliveIntent = new Intent();
        keepAliveIntent.setClassName(activity.getPackageName(), KeepAliveService.class.getCanonicalName());
        customTabsIntent.intent.putExtra(EXTRA_CUSTOM_TABS_KEEP_ALIVE, keepAliveIntent);
        try {
            customTabsIntent.launchUrl(activity, uri);
            Timber.d("Launched url: %s", uri.toString());
        } catch (Exception e) {
            CUSTOM_TABS_FALLBACK.openUri(activity, uri);
            Timber.e("Called fallback even though a package was found, weird Exception : %s", e.toString());
        }
    } else {
        Timber.e("Called fallback since no package found!");
        CUSTOM_TABS_FALLBACK.openUri(activity, uri);
    }
}

From source file:com.java2s.intents4.IntentsDemo4Activity.java

@Override
public void onClick(View view) {
    if (view == addIntentCatButton) {
        addRow(intentCategoriesLayout, "addCategory", "e.g., android.intent.category.SAMPLE_CODE", false);
    }//ww w.j  a v a2s .co  m
    if (view == addFilterCatButton) {
        addRow(filterCategoriesLayout, "addCategory", "e.g., android.intent.category.SAMPLE_CODE", false);
        if (filterCategoriesLayout.getChildCount() == 1) {
            ((EditText) ((ViewGroup) filterCategoriesLayout.getChildAt(0)).getChildAt(1))
                    .setText("android.intent.category.SAMPLE_CODE");
        }
    }
    if (view == addFilterActionButton) {
        addRow(filterActionsLayout, "addAction", "e.g., android.intent.action.VIEW", false);
    }
    if (view == addFilterSchemeButton) {
        addRow(filterSchemeLayout, "addDataScheme", "e.g., content (without a colon)", false);
    }
    if (view == addFilterAuthButton) {
        addRow(filterAuthLayout, "addDataAuthority", "e.g., example.com:2000", false);
    }
    if (view == addFilterPathButton) {
        addRow(filterPathLayout, "addDataPath", "e.g., /folder/subfoler", true);
    }
    if (view instanceof RadioButtonPlusStuff) {

        (((RadioButtonPlusStuff) view).getTextView()).setText(((RadioButtonPlusStuff) view).getAHint());
    }
    if (view == addFilterTypeButton) {
        addRow(filterTypeLayout, "addDataType", "e.g., text/html", false);
    }
    if (view == testButton) {

        Intent intent = createIntentFromEditTextFields();

        if (intentHasBothUriAndType) {
            savedIntent = intent;

            Intent alertIntent = new Intent();
            alertIntent.setClassName("com.java2s.intents4", "com.java2s.intents4.MyAlert");
            startActivityForResult(alertIntent, MY_REQUEST_CODE);
        } else {
            finishTest(intent);
        }
    } else if (view == clearButton) {
        clearEditTextFields();
    }
}

From source file:fm.smart.r1.activity.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {/* ww w .ja v a 2  s. co  m*/
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //             
            // ContentResolver contentResolver = new ContentResolver(this);
            //             
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (Main.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("list_id", list_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", id);

                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:com.android.mail.browse.MessageFooterView.java

private void viewEntireMessage() {
    Analytics.getInstance().sendEvent("view_entire_message", "clicked", null, 0);

    final Context context = getContext();
    final Intent intent = new Intent();
    final String activityName = context.getResources().getString(R.string.full_message_activity);
    if (TextUtils.isEmpty(activityName)) {
        LogUtils.wtf(LOG_TAG, "Trying to open clipped message with no activity defined");
        return;/*  w ww  .  ja v  a2  s  .co m*/
    }
    intent.setClassName(context, activityName);
    final Account account = getAccount();
    final ConversationMessage message = mMessageHeaderItem.getMessage();
    if (account != null && !TextUtils.isEmpty(message.permalink)) {
        intent.putExtra(AccountFeedbackActivity.EXTRA_ACCOUNT_URI, account.uri);
        intent.putExtra(FullMessageContract.EXTRA_PERMALINK, message.permalink);
        intent.putExtra(FullMessageContract.EXTRA_ACCOUNT_NAME, account.getEmailAddress());
        intent.putExtra(FullMessageContract.EXTRA_SERVER_MESSAGE_ID, message.serverId);
        context.startActivity(intent);
    }
}

From source file:org.mozilla.gecko.tests.testDistribution.java

private void doReferrerTest(String ref, final TestableDistribution distribution,
        final Distribution.ReadyCallback distributionReady) throws InterruptedException {
    final Intent intent = new Intent(ACTION_INSTALL_REFERRER);
    intent.setClassName(AppConstants.ANDROID_PACKAGE_NAME, CLASS_REFERRER_RECEIVER);
    intent.putExtra("referrer", ref);

    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override/* w  w w.j a va2  s  . com*/
        public void onReceive(Context context, Intent intent) {
            Log.i(LOGTAG, "Test received " + intent.getAction());

            ThreadUtils.postToBackgroundThread(new Runnable() {
                @Override
                public void run() {
                    distribution.addOnDistributionReadyCallback(distributionReady);
                    distribution.go();
                }
            });
        }
    };

    IntentFilter intentFilter = new IntentFilter(ReferrerReceiver.ACTION_REFERRER_RECEIVED);
    final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(mActivity);
    localBroadcastManager.registerReceiver(receiver, intentFilter);

    Log.i(LOGTAG, "Broadcasting referrer intent.");
    try {
        mActivity.sendBroadcast(intent, null);
        synchronized (distribution) {
            distribution.wait(WAIT_TIMEOUT_MSEC);
        }
    } finally {
        localBroadcastManager.unregisterReceiver(receiver);
    }
}

From source file:fm.smart.r1.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {//w  w  w  .  j ava 2  s .c o  m
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //
            // ContentResolver contentResolver = new ContentResolver(this);
            //
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (LoginActivity.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("goal_id", goal_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", item_id, id, to_record);
                        // this will also ensure item is in goal, but this
                        // should be sentence
                        // submission if we are handling sentence sound.
                        if (sound_type.equals(Integer.toString(R.id.cue_sound))) {
                            CreateSoundActivity.add_item_result = new AddItemResult(
                                    Main.lookup.addItemToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, CreateSoundActivity.create_sound_result.sound_id));
                        } else {
                            // ensure item is in goal
                            CreateSoundActivity.add_item_result = new AddItemResult(Main.lookup
                                    .addItemToGoal(Main.transport, Main.default_study_goal_id, item_id, null));
                            CreateSoundActivity.add_sentence_result = new AddSentenceResult(
                                    Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, id, CreateSoundActivity.create_sound_result.sound_id));

                        }
                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:org.elasticdroid.LoginView.java

/**
 * Process results from model. Called by onPostExecute() method
 * in any given Model class.//from  w  w  w  . j a  v a  2  s .c  o  m
 * 
 * Displays either an error message (if result is an exeception)
 * or the next activity.
 * 
 * Overrides
 * @see org.elasticdroid.tpl.GenericActivity#processModelResults(java.lang.Object)
 */
@Override
public void processModelResults(Object result) {
    Log.v(this.getClass().getName(), "Processing model results...");

    //dismiss the progress bar
    if (progressDialogDisplayed) {
        progressDialogDisplayed = false;
        dismissDialog(DialogConstants.PROGRESS_DIALOG.ordinal());
    }

    if (result == null) {
        Toast.makeText(this, Html.fromHtml(this.getString(R.string.cancelled_login)), Toast.LENGTH_LONG).show();

        return; //do not execute the rest of this method.
    }

    /*
     * The result returned by the model can be:
     * a) true: if authentication successful.
     * b) AmazonServiceException: if authentication failed (typically).
     * c) AmazonClientException: if communication to AWS failed (user not connected to internet?).
     * d) null: if the credentials have been validated.
     */
    if (result instanceof Boolean) {
        HashMap<String, String> connectionData = new HashMap<String, String>();

        //TODO add the ability to change the default dashboard for a user
        finish(); //finish the activity; we dont want the user to be able to return to this screen using the 
        //back key.
        Intent displayDashboardIntent = new Intent();
        displayDashboardIntent.setClassName("org.elasticdroid", "org.elasticdroid.EC2DashboardView");
        //pass the username, access key, and secret access key to the dashboard as arguments
        //create a HashMap<String,String> to hold the connection data
        connectionData.put("username", username);
        connectionData.put("accessKey", accessKey);
        connectionData.put("secretAccessKey", secretAccessKey);

        //add connection data to intent, and start new activity
        displayDashboardIntent.putExtra("org.elasticdroid.LoginView.connectionData", connectionData);
        startActivity(displayDashboardIntent);
    } else if (result instanceof AmazonServiceException) {
        if ((((AmazonServiceException) result).getStatusCode() == HttpStatus.SC_UNAUTHORIZED)
                || (((AmazonServiceException) result).getStatusCode() == HttpStatus.SC_FORBIDDEN)) {
            //set errors in the access key and secret access key fields.
            ((EditText) findViewById(R.id.akEntry))
                    .setError(this.getString(R.string.loginview_invalid_credentials_err));
            ((EditText) findViewById(R.id.sakEntry))
                    .setError(this.getString(R.string.loginview_invalid_credentials_err));

            alertDialogMessage = this.getString(R.string.loginview_invalid_keys_dlg);
        } else {
            //TODO a wrong SecretAccessKey is handled using a different error if the AccessKey is right.
            //Handle this.
            alertDialogMessage = this.getString(R.string.loginview_unexpected_err_dlg)
                    + ((AmazonServiceException) result).getStatusCode() + "--"
                    + ((AmazonServiceException) result).getMessage() + ". "
                    + this.getString(R.string.loginview_bug_report_dlg);
        }

        //whatever the error, display the error
        //and set the boolean to true. This is so that we know we should redisplay
        //dialog on restore.
        Log.e(this.getClass().getName(), alertDialogMessage);

        alertDialogDisplayed = true;

    } else if (result instanceof AmazonClientException) {
        alertDialogMessage = this.getString(R.string.loginview_no_connxn_dlg);
        Log.e(this.getClass().getName(), alertDialogMessage);

        alertDialogDisplayed = true;
    } else if (result instanceof IllegalArgumentException) {
        ((EditText) findViewById(R.id.usernameEntry))
                .setError(this.getString(R.string.loginview_invalid_username_err));
        alertDialogMessage = this.getString(R.string.loginview_invalid_username_err);
        Log.e(this.getClass().getName(), alertDialogMessage);
        alertDialogDisplayed = true;
    } else if (result instanceof SQLException) {
        alertDialogMessage = this.getString(R.string.loginview_username_exists_dlg);
        Log.e(this.getClass().getName(), alertDialogMessage);
        alertDialogDisplayed = true;
    } else if (result != null) {
        Log.e(this.getClass().getName(), "Unexpected error!!!");
    }

    //set the loginModel to null
    loginModel = null;
    //display the alert dialog if the user set the displayed var to true
    if (alertDialogDisplayed) {
        alertDialogBox.setMessage(alertDialogMessage);
        alertDialogBox.show();//show error
    }
}

From source file:jp.app_mart.billing.AppmartHelper.java

/**
 * appmart???//w  w w.  j  av  a  2 s.  c o  m
 * @param listener Activity?callback
 */
public void startSetup(final OnAppmartSetupFinishedListener listener) {

    if (mSetupDone)
        throw new IllegalStateException(mContext.getString(R.string.already_connected));

    mServiceConn = new ServiceConnection() {

        //?
        public void onServiceConnected(ComponentName name, IBinder boundService) {
            mService = AppmartInBillingInterface.Stub.asInterface((IBinder) boundService);
            mSetupDone = true;
            if (listener != null) {
                listener.onAppmartSetupFinished(new AppmartResult(BILLING_RESPONSE_RESULT_OK,
                        mContext.getString(R.string.is_now_connected)));
            }

            //????receiver
            IntentFilter filter = new IntentFilter("appmart_broadcast_return_service_payment");
            if (mReceiver == null)
                mReceiver = new AppmartReceiver();
            mContext.registerReceiver(mReceiver, filter);
        }

        //?
        public void onServiceDisconnected(ComponentName name) {
            logDebug(mContext.getString(R.string.is_now_deconnected));
            mService = null;
        }
    };

    Intent serviceIntent = new Intent();
    serviceIntent.setClassName(BILLING_APPMART_PACKAGE_NAME, BILLING_APPMART_SERVICE_NAME);

    //?appmart????????
    if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {

        mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);

    } else {

        if (listener != null) {
            listener.onAppmartSetupFinished(new AppmartResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
                    mContext.getString(R.string.appmart_not_installed)));
        }
    }
}