Example usage for android.content Intent putExtras

List of usage examples for android.content Intent putExtras

Introduction

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

Prototype

public @NonNull Intent putExtras(@NonNull Bundle extras) 

Source Link

Document

Add a set of extended data to the intent.

Usage

From source file:com.irccloud.android.Notifications.java

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title,
        String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network,
        String auto_messages[]) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());

    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext())
                    .setContentTitle(title + ((network != null) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.dark_blue))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE);
        String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound");
        if (ringtone != null && ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }//from  w  ww . ja  v a2s . c  o m

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        if (prefs.getBoolean("notify_vibrate", true))
            builder.setDefaults(
                    android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE);
        else
            builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS);
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    if (replyIntent != null) {
        WearableExtender extender = new WearableExtender();
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
        extender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_reply, "Reply", replyPendingIntent)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                        .build());

        if (count > 1 && wear_text != null)
            extender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true))
                            .build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (auto_messages != null) {
            for (String m : auto_messages) {
                if (m != null && m.length() > 0) {
                    unreadConvBuilder.addMessage(m);
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(extender)
                .extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    android.app.Notification notification = builder.build();

    RemoteViews contentView = new RemoteViews(
            IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification);
    contentView.setTextViewText(R.id.title, title + " (" + network + ")");
    contentView.setTextViewText(R.id.text,
            (count == 1) ? Html.fromHtml(text) : (count + " unread highlights."));
    contentView.setLong(R.id.time, "setTime", eids[0] / 1000);
    notification.contentView = contentView;

    if (Build.VERSION.SDK_INT >= 16 && big_text != null) {
        RemoteViews bigContentView = new RemoteViews(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                R.layout.notification_expanded);
        bigContentView.setTextViewText(R.id.title,
                title + (!title.equals(network) ? (" (" + network + ")") : ""));
        bigContentView.setTextViewText(R.id.text, big_text);
        bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
        if (count > 3) {
            bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
            bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
        } else {
            bigContentView.setViewVisibility(R.id.more, View.GONE);
        }
        if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
            bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
            bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
            i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
            i.setData(Uri.parse("irccloud-bid://" + bid));
            i.putExtras(replyIntent);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent quickReplyIntent = PendingIntent.getActivity(
                    IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
        }
        notification.bigContentView = bigContentView;
    }

    return notification;
}

From source file:com.cssweb.android.common.FairyUI.java

/**
 * ??\//w w  w .  j  a  va 2  s  .co m
 * 
 * @param paramInt
 * @param paramContext
 * @return
 */
public static Intent genIsLoginIntent(int paramInt, int paramInt2, Context paramContext) {
    Intent localIntent = new Intent();
    if (genIsActiveIntent(paramInt, paramInt2, paramContext)) {
        if (!TradeUtil.checkUserLogin()) {// ?
            localIntent.putExtra("menu_id", paramInt);
            localIntent.setClass(paramContext, LoginActivity.class);
        } else {
            localIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            String orgid = TradeUser.getInstance().getOrgid();
            switch (paramInt2) {
            case Global.NJZQ_JLP_JYYH:
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.putExtra("menu_id", paramInt2);
                if (1 == TradeUser.getInstance().getLoginType()) {
                    localIntent = null;
                } else {
                    localIntent.setClass(paramContext, LoginActivity.class);
                }
                break;
            case Global.NJZQ_WTJY:
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.putExtra("menu_id", paramInt2);
                if (orgid == null || "".equals(orgid)) {
                    localIntent.setClass(paramContext, LoginActivity.class);
                } else {
                    localIntent.setClass(paramContext, JlpActivity.class);
                }
                break;
            case Global.NJZQ_WTJY_TWO:
                localIntent.putExtra("menu_id", Global.NJZQ_WTJY_GP_THREE);
                localIntent.setClass(paramContext, FundActivity.class);
                break;
            case Global.QUOTE_USERSTK:
                localIntent.putExtra("requestType", 1);
                localIntent.setClass(paramContext, PersonalStock.class);
                break;
            case Global.QUOTE_WARNING:
            case Global.NJZQ_HQBJ_HQYJ:
                if (TradeUser.getInstance().getLoginType() == 3) {
                    localIntent.putExtra("menu_id", paramInt);
                    localIntent.setClass(paramContext, LoginActivity.class);
                } else
                    localIntent.setClass(paramContext, QuoteWarning.class);
                break;
            case Global.NJZQ_ZXHD_EGHT:
                localIntent.putExtra("menu_id", Global.NJZQ_ZXHD_EGHT);
                localIntent.setClass(paramContext, VistualTrade.class);
                break;
            case Global.QUOTE_PAIMING:
                localIntent.putExtra("requestType", 0);
                localIntent.setClass(paramContext, PaiMing.class);
                break;
            case Global.QUOTE_DAPAN:
                localIntent.putExtra("requestType", 2);
                localIntent.setClass(paramContext, DaPan.class);
                break;
            case Global.NJZQ_HQBJ_QQSC_WHSC:
                localIntent.putExtra("menu_id", Global.NJZQ_HQBJ_QQSC_WHSC);
                localIntent.setClass(paramContext, GlobalMarket.class);
                break;
            case Global.QUOTE_FENLEI:
                localIntent.putExtra("requestType", 2);
                localIntent.setClass(paramContext, FenLei.class);
                break;
            case Global.QUOTE_STOCK:
                localIntent.putExtra("type", 0);
                localIntent.setClass(paramContext, StockTypeFund.class);
                break;
            case Global.QUOTE_BOND:
                localIntent.putExtra("type", 1);
                localIntent.setClass(paramContext, StockTypeFund.class);
                break;
            case Global.QUOTE_MONETARY:
                localIntent.putExtra("type", 2);
                localIntent.setClass(paramContext, StockTypeFund.class);
                break;
            case Global.QUOTE_MIX:
                localIntent.putExtra("type", 3);
                localIntent.setClass(paramContext, StockTypeFund.class);
                break;
            case Global.SUN_PRIVATE:
                localIntent.putExtra("type", 4);
                localIntent.setClass(paramContext, SunPrivate.class);
                break;
            case Global.HK_MAINBOARD: // ?
                Bundle bundle = new Bundle();
                bundle.putInt("stocktype", 101);
                bundle.putInt("flag", 1);
                localIntent.putExtras(bundle);
                localIntent.setClass(paramContext, HKMainboard.class);
                break;
            case Global.HK_CYB: // ?
                Bundle bundle2 = new Bundle();
                bundle2.putInt("stocktype", 102);
                bundle2.putInt("flag", 2);
                localIntent.putExtras(bundle2);
                localIntent.setClass(paramContext, HKMainboard.class);
                break;

            case Global.ZJS:// 
                localIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                localIntent.setClass(paramContext, ZJS.class);

                Bundle extras = new Bundle();
                extras.putString("market", "cffex");
                extras.putString("exchange", "cf");
                extras.putString("title", "");
                localIntent.putExtras(extras);
                break;
            case Global.SDZ:// ,,
                localIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                localIntent.setClass(paramContext, QHSCBaseActivity.class);
                break;
            case Global.QUOTE_HSZS:
                localIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                localIntent.setClass(paramContext, HSZS.class);
                break;

            case Global.QUOTE_KLINE:
                localIntent.setClass(paramContext, KLineActivity.class);
                break;
            case Global.QUOTE_FENSHI:
                localIntent.putExtra("exchange", CssSystem.exchange);
                localIntent.putExtra("stockcode", CssSystem.stockcode);
                localIntent.putExtra("stockname", CssSystem.stockname);
                localIntent.setClass(paramContext, TrendActivity.class);
                break;

            case Global.NJZQ_ZXHD_KHJL:
                localIntent.putExtra("pos", Global.NJZQ_ZXHD_KHJL);
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.setClass(paramContext, WebViewDisplay.class);
                break;
            case Global.NJZQ_ZXHD_TZGW:
                if (TradeUser.getInstance().getLoginType() == 3) {
                    localIntent.putExtra("menu_id", paramInt);
                    localIntent.setClass(paramContext, LoginActivity.class);
                } else {
                    localIntent.putExtra("pos", Global.NJZQ_ZXHD_TZGW);
                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    localIntent.setClass(paramContext, WebViewDisplay.class);
                }
                break;
            }
        }
    } else {
        localIntent.putExtra("menu_id", paramInt);
        if (paramInt == Global.NJZQ_WTJY) {
            localIntent.putExtra("isChangeBtn", true);
        }
        localIntent.setClass(paramContext, SMSJHActivity.class);
    }
    return localIntent;
}

From source file:com.example.ronald.tracle.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new DownloadTask().execute("https://flifo-qa.api.aero/flifo/v3/flight/sin/sq/998/d");
    /*//from   w w w  .java2 s.c o  m
    Parsing of data from previous activity
     */
    String username = getIntent().getStringExtra("name");
    String password = getIntent().getStringExtra("password");
    String alias = getIntent().getStringExtra("alias");
    myUser = username;
    pw = password;
    /*
    Declare your layout here
     */

    Button sendBtn = (Button) findViewById(R.id.buttonSendAll);

    TextView nametv = (TextView) findViewById(R.id.username);
    TextView emailtv = (TextView) findViewById(R.id.email);
    emailtv.setText(username);
    nametv.setText(alias);

    // Initializing Toolbar and setting it as the actionbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {

            //Replacing the main content with ContentFragment Which is our Inbox View;
            case R.id.home:
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                startActivity(intent);
                return true;
            case R.id.explore:
                Intent intente = new Intent(MainActivity.this, SlideTab.class);
                startActivity(intente);
                return true;
            case R.id.network:
                Intent intentk = new Intent(MainActivity.this, SlideTab.class);
                startActivity(intentk);
                return true;
            case R.id.announcement:
                Intent intenti = new Intent(MainActivity.this, AnnounceActivity.class);
                startActivity(intenti);
                return true;
            case R.id.setting:
                String username = "";
                String pw = "";
                String PREFS_LOGIN_USERNAME_KEY = "";
                String PREFS_LOGIN_PASSWORD_KEY = "";
                PrefUtils.saveToPrefs(getApplication(), PREFS_LOGIN_USERNAME_KEY, username);
                PrefUtils.saveToPrefs(getApplication(), PREFS_LOGIN_PASSWORD_KEY, pw);
                System.exit(0);
                return true;
            // For rest of the options we just show a toast on click
            default:
                Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                return true;

            }
        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //Toast.makeText(this, "username: "+username+" pw: "+password, Toast.LENGTH_SHORT).show();

    //calling sync state is necessay or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();

    /*
    This is the initial step in getting back the token from GCM
     */
    //mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                //  mInformationTextView.setText(getString(R.string.gcm_send_message));
            } else {
                // mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };
    //mInformationTextView = (TextView) findViewById(R.id.informationTextView);

    /*
    Check play services, if not GCM won't work.
     */
    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        Bundle localBundle = new Bundle();
        localBundle.putString("name", username);
        localBundle.putString("password", password);
        intent.putExtras(localBundle);
        startService(intent);
    }

}

From source file:com.cognizant.trumobi.PersonaLauncher.java

private void pickShortcut(int requestCode, int title) {
    Bundle bundle = new Bundle();
    /*/*from ww w . jav  a  2s  . c om*/
          ArrayList<String> shortcutNames = new ArrayList<String>();
          shortcutNames.add(getString(R.string.group_applications));
          bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
            
          ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
          shortcutIcons.add(ShortcutIconResource.fromContext(
    PersonaLauncher.this, R.drawable.pr_ic_launcher_application));
          bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
    shortcutIcons);*/
    //   Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
    Intent pickIntent = new Intent();

    String ShortCutName = new String(getString(R.string.group_applications));
    bundle.putString(Intent.EXTRA_SHORTCUT_NAME, ShortCutName);

    pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
    pickIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.group_applications));
    pickIntent.putExtras(bundle);
    processShortcut(pickIntent, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT);
    //startActivityForResult(pickIntent, requestCode);
}

From source file:com.linkedin.android.eventsapp.EventFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final String eventNameArg = getArguments().getString(EXTRA_EVENT_NAME);
    final long eventDateArg = getArguments().getLong(EXTRA_EVENT_DATE);
    final String eventLocationArg = getArguments().getString(EXTRA_EVENT_LOCATION);
    int pictureIdArg = getArguments().getInt(EXTRA_PICTURE_ID);
    boolean isAttendingArg = getArguments().getBoolean(EXTRA_EVENT_ATTENDING);
    Person[] attendeesArg = (Person[]) getArguments().getParcelableArray(EXTRA_EVENT_ATTENDEES);

    SimpleDateFormat dateFormat = new SimpleDateFormat("E dd MMM yyyy 'at' hh:00 a");
    final String dateString = dateFormat.format(new Date(eventDateArg));

    View v = inflater.inflate(R.layout.layout_event_fragment, container, false);

    boolean accessTokenValid = LISessionManager.getInstance(getActivity()).getSession().isValid();
    if (!accessTokenValid) {
        ViewStub linkedinLogin = (ViewStub) v.findViewById(R.id.connectWithLinkedInStub);
        linkedinLogin.inflate();/*from w w  w.  j av  a  2 s . co m*/

        Button loginButton = (Button) v.findViewById(R.id.connectWithLinkedInButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "clicked login button");
                LISessionManager.getInstance(getActivity()).init(getActivity(), Constants.scope,
                        new AuthListener() {
                            @Override
                            public void onAuthSuccess() {
                                Intent intent = new Intent(getActivity(), MainActivity.class);
                                startActivity(intent);
                                getActivity().finish();
                            }

                            @Override
                            public void onAuthError(LIAuthError error) {

                            }
                        }, false);
            }
        });
    }

    TextView eventNameView = (TextView) v.findViewById(R.id.eventName);
    eventNameView.setText(eventNameArg);

    TextView eventLocationAndDateView = (TextView) v.findViewById(R.id.eventLocationAndDate);
    eventLocationAndDateView.setText(eventLocationArg + "   " + dateString);

    TextView eventAttendeeCount = (TextView) v.findViewById(R.id.attendeeCount);
    eventAttendeeCount.setText("Other Attendees (" + attendeesArg.length + ")");

    ImageView eventImageView = (ImageView) v.findViewById(R.id.eventImage);
    eventImageView.setImageResource(pictureIdArg);

    final Button attendButton = (Button) v.findViewById(R.id.attendButton);
    final Button declineButton = (Button) v.findViewById(R.id.declineButton);

    if (isAttendingArg) {
        attendButton.setText("Attending");
        attendButton.setEnabled(false);

        declineButton.setText("Decline");
        declineButton.setEnabled(true);
    }

    attendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((Button) v).setText("Attending");
            v.setEnabled(false);
            declineButton.setText("Decline");
            declineButton.setEnabled(true);
            if (LISessionManager.getInstance(getActivity()).getSession().isValid()) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
                alertDialogBuilder.setTitle("Share on LinkedIn?");
                alertDialogBuilder.setCancelable(true)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                JSONObject shareObject = new JSONObject();
                                try {
                                    JSONObject visibilityCode = new JSONObject();
                                    visibilityCode.put("code", "anyone");
                                    shareObject.put("visibility", visibilityCode);
                                    shareObject.put("comment", "I am attending " + eventNameArg + " in "
                                            + eventLocationArg + " on " + dateString);
                                } catch (JSONException e) {

                                }
                                APIHelper.getInstance(getActivity()).postRequest(getActivity(),
                                        Constants.shareBaseUrl, shareObject, new ApiListener() {
                                            @Override
                                            public void onApiSuccess(ApiResponse apiResponse) {
                                                Toast.makeText(getActivity(), "Your share was successful!",
                                                        Toast.LENGTH_LONG);
                                            }

                                            @Override
                                            public void onApiError(LIApiError apiError) {
                                                Log.e(TAG, apiError.toString());
                                                Toast.makeText(getActivity(),
                                                        "Your share was unsuccessful. Try again later!",
                                                        Toast.LENGTH_LONG);
                                            }
                                        });
                            }
                        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        }
    });

    declineButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((Button) v).setText("Declined");
            v.setEnabled(false);
            attendButton.setText("Attend");
            attendButton.setEnabled(true);
        }
    });

    ListView attendeesListView = (ListView) v.findViewById(R.id.attendeesList);
    AttendeeAdapter adapter = new AttendeeAdapter(getActivity(), R.layout.attendee_list_item, attendeesArg,
            accessTokenValid);
    attendeesListView.setAdapter(adapter);
    attendeesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ArrayAdapter adapter = (ArrayAdapter) parent.getAdapter();
            Person person = (Person) adapter.getItem(position);

            Intent intent = new Intent(getActivity(), ProfileActivity.class);
            Bundle extras = new Bundle();
            extras.putParcelable("person", person);
            intent.putExtras(extras);
            startActivity(intent);
        }
    });
    return v;
}

From source file:com.android.gallery3d.app.PhotoPage.java

@Override
protected boolean onItemSelected(MenuItem item) {
    if (mModel == null)
        return true;
    refreshHidingMessage();/* w ww. j ava2  s. c  o m*/
    MediaItem current = mModel.getMediaItem(0);

    // This is a shield for monkey when it clicks the action bar
    // menu when transitioning from filmstrip to camera
    if (current instanceof SnailItem)
        return true;
    // TODO: We should check the current photo against the MediaItem
    // that the menu was initially created for. We need to fix this
    // after PhotoPage being refactored.
    if (current == null) {
        // item is not ready, ignore
        return true;
    }
    int currentIndex = mModel.getCurrentIndex();
    Path path = current.getPath();

    DataManager manager = mActivity.getDataManager();
    int action = item.getItemId();
    /// M: [BUG.ADD] show toast before PhotoDataAdapter finishing loading to avoid JE @{
    if (action != android.R.id.home && !mLoadingFinished && mSetPathString != null) {
        Toast.makeText(mActivity, mActivity.getString(R.string.please_wait), Toast.LENGTH_SHORT).show();
        return true;
    }
    /// @}
    String confirmMsg = null;
    switch (action) {
    case android.R.id.home: {
        onUpPressed();
        return true;
    }
    case R.id.action_slideshow: {
        Bundle data = new Bundle();
        /// M: [BUG.MODIFY] fix bug: slideshow doesn't play again
        // when finish playing the last picture @{
        String mediaSetPath = mMediaSet.getPath().toString();
        if (mSnailSetPath != null) {
            mediaSetPath = mediaSetPath.replace(mSnailSetPath + ",", "");
            Log.i(TAG, "<onItemSelected> action_slideshow | mediaSetPath: " + mediaSetPath);
        }
        /*data.putString(SlideshowPage.KEY_SET_PATH, mMediaSet.getPath().toString());*/
        data.putString(SlideshowPage.KEY_SET_PATH, mediaSetPath);
        /// @}
        data.putString(SlideshowPage.KEY_ITEM_PATH, path.toString());
        /// M: [BUG.ADD] currentIndex-- if it is in camera folder @{
        if (mHasCameraScreennailOrPlaceholder) {
            currentIndex--;
        }
        /// @}

        data.putInt(SlideshowPage.KEY_PHOTO_INDEX, currentIndex);
        data.putBoolean(SlideshowPage.KEY_REPEAT, true);
        mActivity.getStateManager().startStateForResult(SlideshowPage.class, REQUEST_SLIDESHOW, data);
        return true;
    }
    case R.id.action_crop: {
        /// M: [BUG.ADD] disable cropping photo when file not exists or sdcard is full. @{
        File srcFile = new File(current.getFilePath());
        if (!srcFile.exists()) {
            Log.i(TAG, "<onItemSelected> abort cropping photo when not exists!");
            return true;
        }
        if (!isSpaceEnough(srcFile)) {
            Log.i(TAG, "<onItemSelected> abort cropping photo when no enough space!");
            Toast.makeText(mActivity, mActivity.getString(R.string.storage_not_enough), Toast.LENGTH_SHORT)
                    .show();
            return true;
        }
        /// @}
        Activity activity = mActivity;
        Intent intent = new Intent(CropActivity.CROP_ACTION);
        intent.setClass(activity, CropActivity.class);
        intent.setDataAndType(manager.getContentUri(path), current.getMimeType())
                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        activity.startActivityForResult(intent,
                PicasaSource.isPicasaImage(current) ? REQUEST_CROP_PICASA : REQUEST_CROP);
        return true;
    }
    case R.id.action_trim: {
        Intent intent = new Intent(mActivity, TrimVideo.class);
        intent.setData(manager.getContentUri(path));
        // We need the file path to wrap this into a RandomAccessFile.
        intent.putExtra(KEY_MEDIA_ITEM_PATH, current.getFilePath());
        /// M: [FEATURE.ADD] SlideVideo@{
        if (FeatureConfig.SUPPORT_SLIDE_VIDEO_PLAY) {
            intent.putExtra(TrimVideo.KEY_COME_FROM_GALLERY, true);
        }
        /// @}
        mActivity.startActivityForResult(intent, REQUEST_TRIM);
        return true;
    }
    case R.id.action_mute: {
        /// M: [BUG.ADD] disable muting video when file not exists or sdcard is full. @{
        File srcFile = new File(current.getFilePath());
        if (!srcFile.exists()) {
            Log.i(TAG, "<onItemSelected> abort muting video when not exists!");
            return true;
        }
        if (!isSpaceEnough(srcFile)) {
            Log.i(TAG, "<onItemSelected> abort muting video when no enough space!");
            Toast.makeText(mActivity, mActivity.getString(R.string.storage_not_enough), Toast.LENGTH_SHORT)
                    .show();
            return true;
        }
        /// @}
        mMuteVideo = new MuteVideo(current.getFilePath(), manager.getContentUri(path), mActivity);
        mMuteVideo.muteInBackground();
        /// M: [FEATURE.ADD] SlideVideo@{
        mMuteVideo.setMuteDoneListener(new MuteDoneListener() {
            public void onMuteDone(Uri uri) {
                redirectCurrentMedia(uri, false);
            }
        });
        /// @}
        return true;
    }
    case R.id.action_edit: {
        /// M: [BUG.ADD] disable editing photo when file not exists or sdcard is full. @{
        File srcFile = new File(current.getFilePath());
        if (!srcFile.exists()) {
            Log.i(TAG, "<onItemSelected> abort editing photo when not exists!");
            return true;
        }
        if (!isSpaceEnough(srcFile)) {
            Log.i(TAG, "<onItemSelected> abort editing photo when no enough space!");
            Toast.makeText(mActivity, mActivity.getString(R.string.storage_not_enough), Toast.LENGTH_SHORT)
                    .show();
            return true;
        }
        /// @}
        launchPhotoEditor();
        return true;
    }
    /// M: [FEATURE.ADD] @{
    case R.id.m_action_picture_quality: {
        Activity activity = (Activity) mActivity;
        Intent intent = new Intent(PictureQualityActivity.ACTION_PQ);
        intent.setClass(activity, PictureQualityActivity.class);
        intent.setData(manager.getContentUri(path));
        Bundle pqBundle = new Bundle();
        pqBundle.putString("PQUri", manager.getContentUri(path).toString());
        pqBundle.putString("PQMineType", current.getMimeType());
        pqBundle.putInt("PQViewWidth", mPhotoView.getWidth());
        pqBundle.putInt("PQViewHeight", mPhotoView.getHeight());
        intent.putExtras(pqBundle);
        Log.i(TAG, "<onItemSelected>startActivity PQ");
        activity.startActivityForResult(intent, REQUEST_PQ);
        return true;
    }
    case R.id.m_action_image_dc: {
        ImageDC.resetStatus((Context) mActivity);
        ImageDC.setMenuItemTile(item);
        path.clearObject();
        mActivity.getDataManager().forceRefreshAll();
        Log.d(TAG, "< onStateResult > forceRefreshAll~~");
        return true;
    }
    /// @}
    case R.id.action_simple_edit: {
        launchSimpleEditor();
        return true;
    }
    case R.id.action_details: {
        if (mShowDetails) {
            hideDetails();
        } else {
            showDetails();
        }
        return true;
    }
    case R.id.print: {
        mActivity.printSelectedImage(manager.getContentUri(path));
        return true;
    }
    case R.id.action_delete:
        confirmMsg = mActivity.getResources().getQuantityString(R.plurals.delete_selection, 1);
    case R.id.action_setas:
    case R.id.action_rotate_ccw:
    case R.id.action_rotate_cw:
    case R.id.action_show_on_map:
        mSelectionManager.deSelectAll();
        mSelectionManager.toggle(path);
        mMenuExecutor.onMenuClicked(item, confirmMsg, mConfirmDialogListener);
        return true;
    /// M: [FEATURE.ADD] DRM & HotKnot @{
    case R.id.m_action_protect_info:
        Log.d(TAG, "<onItemSelected> ProtectionInfo: do action_protection_info");
        DrmHelper.showProtectionInfoDialog((Activity) mActivity, manager.getContentUri(path));
        return true;
    case R.id.action_hotknot:
        Log.d(TAG, "<onItemSelected> HotKnot: do action_hotknot");
        // for continuous shot, may share a group image, so getContentUris()
        Uri[] uris = null;
        ExtItem extItem = mCurrentPhoto.getExtItem();
        if (extItem != null) {
            uris = extItem.getContentUris();
        }
        if (uris != null) {
            mActivity.getHotKnot().sendZip(uris);
        } else {
            extHotKnot();
        }
        return true;
    /// @}
    /// M: [FEATURE.ADD] entry to export as video @{
    case R.id.action_export:
        mAnimatedContentSharer.exportCurrentPhoto();
        return true;
    /// @}
    /// M: [FEATURE.ADD] Support BlueTooth print feature.@{
    case R.id.action_print:
        mSelectionManager.deSelectAll();
        mSelectionManager.toggle(path);
        mMenuExecutor.onMenuClicked(item, confirmMsg, mConfirmDialogListener);
        return true;
    /// @}
    default:
        /// M: [FEATURE.ADD] menu extension @{
        // return false;
        return mPhotoView.onOptionsItemSelected(item);
    /// @}
    }
}