Example usage for android.content Intent ACTION_SEND_MULTIPLE

List of usage examples for android.content Intent ACTION_SEND_MULTIPLE

Introduction

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

Prototype

String ACTION_SEND_MULTIPLE

To view the source code for android.content Intent ACTION_SEND_MULTIPLE.

Click Source Link

Document

Activity Action: Deliver multiple data to someone else.

Usage

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

public void shareAttachments(ArrayList<Parcelable> uris) {
    Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    intent.setType("image/*");
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

    try {/*from www.j  av a2  s  . c  o  m*/
        mContext.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        // couldn't find activity for SEND_MULTIPLE intent
        LogUtils.e(LOG_TAG, "Couldn't find Activity for intent", e);
    }
}

From source file:com.wikonos.fingerprint.activities.MainActivity.java

/**
 * Create dialog list of logs/* w w w  . j a  v  a 2 s. com*/
 * 
 * @return
 */
public AlertDialog getDialogReviewLogs() {
    /**
     * List of logs
     */
    File folder = new File(LogWriter.APPEND_PATH);
    final String[] files = folder.list(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            if (filename.contains(".log") && !filename.equals(LogWriter.DEFAULT_NAME)
                    && !filename.equals(LogWriterSensors.DEFAULT_NAME)
                    && !filename.equals(ErrorLog.DEFAULT_NAME))
                return true;
            else
                return false;
        }
    });

    Arrays.sort(files);
    ArrayUtils.reverse(files);

    String[] files_with_status = new String[files.length];
    String[] sent_mode = { "", "(s) ", "(e) ", "(s+e) " };
    for (int i = 0; i < files.length; ++i) {
        //0 -- not sent
        //1 -- server
        //2 -- email
        files_with_status[i] = sent_mode[getSentFlags(files[i], this)] + files[i];
    }

    if (files != null && files.length > 0) {

        final boolean[] selected = new boolean[files.length];

        final AlertDialog ald = new AlertDialog.Builder(MainActivity.this)
                .setMultiChoiceItems(files_with_status, selected,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                selected[which] = isChecked;
                            }
                        })
                .setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                })
                /**
                * Delete log
                */
                .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        //Show delete confirm
                        standardConfirmDialog("Delete Logs", "Are you sure you want to delete selected logs?",
                                new OnClickListener() {
                                    //Confrim Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        int deleteCount = 0;
                                        boolean flagSelected = false;
                                        for (int i = 0; i < selected.length; i++) {
                                            if (selected[i]) {
                                                flagSelected = true;
                                                LogWriter.delete(files[i]);
                                                LogWriter.delete(files[i].replace(".log", ".dev"));
                                                deleteCount++;
                                            }
                                        }

                                        reviewLogsCheckItems(flagSelected);

                                        removeDialog(DIALOG_ID_REVIEW);

                                        Toast.makeText(getApplicationContext(), deleteCount + " logs deleted.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, new OnClickListener() {
                                    //Cancel Delete
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //Do nothing
                                        dialog.dismiss();
                                        Toast.makeText(getApplicationContext(), "Delete cancelled.",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }, false);
                    }
                })
                /**
                * Send to server functional
                **/
                .setNeutralButton("Send to Server", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (isOnline()) {
                            ArrayList<String> filesList = new ArrayList<String>();

                            for (int i = 0; i < selected.length; i++)
                                if (selected[i]) {

                                    filesList.add(LogWriter.APPEND_PATH + files[i]);
                                    //Move to httplogsender
                                    //setSentFlags(files[i], 1, MainActivity.this);   //Mark file as sent
                                }

                            if (reviewLogsCheckItems(filesList.size() > 0 ? true : false)) {
                                DataPersistence d = new DataPersistence(getApplicationContext());
                                new HttpLogSender(MainActivity.this,
                                        d.getServerName() + getString(R.string.submit_log_url), filesList)
                                                .setToken(getToken()).execute();
                            }

                            // removeDialog(DIALOG_ID_REVIEW);
                        } else {
                            standardAlertDialog(getString(R.string.msg_alert),
                                    getString(R.string.msg_no_internet), null);
                        }
                    }
                })
                /**
                * Email
                **/
                .setPositiveButton("eMail", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        boolean flagSelected = false;
                        // convert from paths to Android friendly
                        // Parcelable Uri's
                        ArrayList<Uri> uris = new ArrayList<Uri>();
                        for (int i = 0; i < selected.length; i++)
                            if (selected[i]) {
                                flagSelected = true;
                                /** wifi **/
                                File fileIn = new File(LogWriter.APPEND_PATH + files[i]);
                                Uri u = Uri.fromFile(fileIn);
                                uris.add(u);

                                /** sensors **/
                                File fileInSensors = new File(
                                        LogWriter.APPEND_PATH + files[i].replace(".log", ".dev"));
                                Uri uSens = Uri.fromFile(fileInSensors);
                                uris.add(uSens);

                                setSentFlags(files[i], 2, MainActivity.this); //Mark file as emailed
                            }

                        if (reviewLogsCheckItems(flagSelected)) {
                            /**
                             * Run sending email activity
                             */
                            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
                            emailIntent.setType("plain/text");
                            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                    "Wifi Searcher Scan Log");
                            emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                        }

                        // removeDialog(DIALOG_ID_REVIEW);
                    }
                }).create();

        ald.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                AlertDialog segmentNameAlert = segmentNameDailog("Rename Segment", ald.getContext(),
                        files[position], null, view, files, position);
                segmentNameAlert.setCanceledOnTouchOutside(false);
                segmentNameAlert.show();
                return false;
            }
        });
        return ald;
    } else {
        return standardAlertDialog(getString(R.string.msg_alert), getString(R.string.msg_log_nocount),
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeDialog(DIALOG_ID_REVIEW);
                    }
                });
    }
}

From source file:com.krayzk9s.imgurholo.activities.MainActivity.java

private void processIntent(Intent intent) {
    String action = intent.getAction();
    String type = intent.getType();
    Log.d("New Intent", intent.toString());
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            Toast.makeText(this, R.string.toast_uploading, Toast.LENGTH_SHORT).show();
            Intent serviceIntent = new Intent(this, UploadService.class);
            if (intent.getExtras() == null)
                finish();//from   w  ww.j  a v a 2s .co m
            serviceIntent.setData((Uri) intent.getExtras().get("android.intent.extra.STREAM"));
            startService(serviceIntent);
            finish();
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
        Log.d("sending", "sending multiple");
        Toast.makeText(this, R.string.toast_uploading, Toast.LENGTH_SHORT).show();
        ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        Intent serviceIntent = new Intent(this, UploadService.class);
        serviceIntent.putParcelableArrayListExtra("images", list);
        startService(serviceIntent);
        finish();
    } else if (Intent.ACTION_VIEW.equals(action) && intent.getData().toString().startsWith("imgur-holo")) {
        Uri uri = intent.getData();
        Log.d("URI", "" + action + "/" + type);
        String uripath = "";
        if (uri != null)
            uripath = uri.toString();
        Log.d("URI", uripath);
        Log.d("URI", "HERE");

        if (uri != null && uripath.startsWith(ApiCall.OAUTH_CALLBACK_URL)) {
            apiCall.verifier = new Verifier(uri.getQueryParameter("code"));
            CallbackAsync callbackAsync = new CallbackAsync(apiCall, this);
            callbackAsync.execute();
        }
    } else if (getSupportFragmentManager().getFragments() == null) {
        loadDefaultPage();
    }
}

From source file:com.cw.litenote.operation.mail.MailPagesFragment.java

void sendEMail(String strEMailAddr, // eMail address
        String[] attachmentFileName, // attachment name
        String[] picFileNameArray) // attachment picture file name
{
    mAttachmentFileName = attachmentFileName;
    // new ACTION_SEND intent
    mEMailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); // for multiple attachments

    // set type/*from   w w w .  jav a2s. co  m*/
    mEMailIntent.setType("text/plain");//can select which APP will be used to send mail

    // open issue: cause warning for Key android.intent.extra.TEXT expected ArrayList
    String text_body = mContext.getResources().getString(R.string.eMail_body)// eMail text (body)
            + " " + Util.getStorageDirName(mContext) + " (UTF-8)" + Util.NEW_LINE + mEMailBodyString;

    // attachment: message
    List<String> filePaths = new ArrayList<String>();
    for (int i = 0; i < attachmentFileName.length; i++) {
        String messagePath = "file:///" + Environment.getExternalStorageDirectory().getPath() + "/"
                + Util.getStorageDirName(mContext) + "/" + attachmentFileName[i];// message file name
        filePaths.add(messagePath);
    }

    // attachment: pictures
    if (picFileNameArray != null) {
        for (int i = 0; i < picFileNameArray.length; i++) {
            filePaths.add(picFileNameArray[i]);
        }
    }

    ArrayList<Uri> uris = new ArrayList<Uri>();
    for (String file : filePaths) {
        Uri uri = Uri.parse(file);
        uris.add(uri);
    }

    mEMailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { strEMailAddr }) // eMail address
            .putExtra(Intent.EXTRA_SUBJECT, Util.getStorageDirName(mContext) + // eMail subject
                    " " + mContext.getResources().getString(R.string.eMail_subject))// eMail subject
            .putExtra(Intent.EXTRA_TEXT, text_body) // eMail body (open issue)
            .putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); // multiple eMail attachment

    Log.v(getClass().getSimpleName(), "attachment " + Uri.parse("file name is:" + attachmentFileName));

    getActivity().startActivityForResult(
            Intent.createChooser(mEMailIntent, getResources().getText(R.string.mail_chooser_title)),
            EMAIL_PAGES);
}

From source file:org.sufficientlysecure.keychain.ui.EncryptFileActivity.java

private Intent createSendIntent(Message message) {
    Intent sendIntent;/*  ww w  .j  av  a2  s . c om*/
    // file
    if (mOutputUris.size() == 1) {
        sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_STREAM, mOutputUris.get(0));
    } else {
        sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        sendIntent.putExtra(Intent.EXTRA_STREAM, mOutputUris);
    }
    sendIntent.setType("application/octet-stream");

    if (!isModeSymmetric() && mEncryptionUserIds != null) {
        Set<String> users = new HashSet<String>();
        for (String user : mEncryptionUserIds) {
            String[] userId = KeyRing.splitUserId(user);
            if (userId[1] != null) {
                users.add(userId[1]);
            }
        }
        sendIntent.putExtra(Intent.EXTRA_EMAIL, users.toArray(new String[users.size()]));
    }
    return sendIntent;
}

From source file:org.kontalk.ui.ComposeMessage.java

private Bundle processIntent(Bundle savedInstanceState) {
    Intent intent;//from   w  ww  .java2  s  .c  om
    if (savedInstanceState != null) {
        mLostFocus = savedInstanceState.getBoolean("lostFocus");

        Uri uri = savedInstanceState.getParcelable(Uri.class.getName());
        if (uri == null) {
            Log.d(TAG, "restoring non-loaded conversation, aborting");
            finish();
            return null;
        }
        intent = new Intent(ACTION_VIEW_USERID, uri);
    } else {
        intent = getIntent();
    }

    if (intent != null) {
        final String action = intent.getAction();
        Bundle args = null;

        // view intent
        // view conversation - just threadId provided
        // view conversation - just userId provided
        if (Intent.ACTION_VIEW.equals(action) || ACTION_VIEW_CONVERSATION.equals(action)
                || ACTION_VIEW_USERID.equals(action)) {
            Uri uri = intent.getData();

            // two-panes UI: start conversation list
            if (Kontalk.hasTwoPanesUI(this)) {
                Intent startIntent = new Intent(action, uri, getApplicationContext(),
                        ConversationsActivity.class);
                startActivity(startIntent);
                // no need to go further
                finish();
                return null;
            }
            // single-pane UI: start normally
            else {
                args = new Bundle();
                args.putString("action", action);
                args.putParcelable("data", uri);
                args.putLong(EXTRA_MESSAGE, intent.getLongExtra(EXTRA_MESSAGE, -1));
                args.putString(EXTRA_HIGHLIGHT, intent.getStringExtra(EXTRA_HIGHLIGHT));
                args.putBoolean(EXTRA_CREATING_GROUP, intent.getBooleanExtra(EXTRA_CREATING_GROUP, false));
            }
        }

        // send external content
        else if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
            sendIntent = intent;
            String mime = intent.getType();

            Log.i(TAG, "sending data to someone: " + mime);
            chooseContact();

            // onActivityResult will handle the rest
            return null;
        }

        // send to someone
        else if (Intent.ACTION_SENDTO.equals(action)) {
            try {
                Uri uri = intent.getData();
                // a phone number should come here...
                String number = NumberValidator.fixNumber(this, uri.getSchemeSpecificPart(),
                        Authenticator.getDefaultAccountName(this), 0);
                // compute hash and open conversation
                String jid = XMPPUtils.createLocalJID(this, MessageUtils.sha1(number));

                // two-panes UI: start conversation list
                if (Kontalk.hasTwoPanesUI(this)) {
                    Intent startIntent = new Intent(getApplicationContext(), ConversationsActivity.class);
                    startIntent.setAction(ACTION_VIEW_USERID);
                    startIntent.setData(Threads.getUri(jid));
                    startActivity(startIntent);
                    // no need to go further
                    finish();
                    return null;
                }
                // single-pane UI: start normally
                else {
                    args = new Bundle();
                    args.putString("action", ComposeMessage.ACTION_VIEW_USERID);
                    args.putParcelable("data", Threads.getUri(jid));
                    args.putString("number", number);
                }
            } catch (Exception e) {
                Log.e(TAG, "invalid intent", e);
                finish();
            }
        }

        return args;
    }

    return null;
}

From source file:ru.dublgis.androidhelpers.DesktopUtils.java

public static boolean sendEmail(final Context ctx, final String to, final String subject, final String body,
        final String[] attachment, final String authorities) {
    try {//from ww w .  j ava2 s  .c o m
        final String[] recipients = new String[] { to };

        final Intent intent = new Intent(
                attachment.length > 1 ? Intent.ACTION_SEND_MULTIPLE : Intent.ACTION_SENDTO);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setType("message/rfc822");
        intent.putExtra(Intent.EXTRA_EMAIL, recipients);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        intent.putExtra(Intent.EXTRA_TEXT, body);

        boolean grant_permissions_workaround = false;
        final ArrayList<Uri> uri = new ArrayList<>();
        if (attachment.length > 0) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                for (final String fileName : attachment) {
                    uri.add(Uri.fromFile(new File(fileName)));
                }
            } else {
                // Android 6+: going the longer route.
                // For more information, please see:
                // http://stackoverflow.com/questions/32981194/android-6-cannot-share-files-anymore
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                grant_permissions_workaround = true;
                for (final String fileName : attachment) {
                    uri.add(FileProvider.getUriForFile(ctx, authorities, new File(fileName)));
                }
            }
            // Should not put array with only one element into intent because of a bug in GMail.
            if (uri.size() == 1) {
                intent.putExtra(Intent.EXTRA_STREAM, uri.get(0));
            } else {
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uri);
            }
        }

        final IntentResolverInfo mailtoIntentResolvers = new IntentResolverInfo(ctx.getPackageManager());
        mailtoIntentResolvers
                .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", to, null)));

        final Intent chooserIntent;

        if (mailtoIntentResolvers.isEmpty()) {
            chooserIntent = Intent.createChooser(intent, null);
        } else {
            final IntentResolverInfo messageIntentResolvers = new IntentResolverInfo(ctx.getPackageManager());
            messageIntentResolvers
                    .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("sms", "", null)));
            messageIntentResolvers
                    .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mms", "", null)));
            messageIntentResolvers
                    .appendResolvers(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("tel", "", null)));

            mailtoIntentResolvers.removeSamePackages(messageIntentResolvers.getResolveInfos());

            final List<Intent> intentList = new ArrayList<>();

            for (final ActivityInfo activityInfo : mailtoIntentResolvers.getResolveInfos()) {
                final String packageName = activityInfo.getPackageName();
                final String name = activityInfo.getName();

                // Some mail clients will not read the URI unless this is done.
                // See here: https://stackoverflow.com/questions/24467696/android-file-provider-permission-denial
                if (grant_permissions_workaround) {
                    for (int i = 0; i < uri.size(); ++i) {
                        try {
                            ctx.grantUriPermission(packageName, uri.get(i),
                                    Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        } catch (final Throwable e) {
                            Log.e(TAG, "grantUriPermission error: ", e);
                        }
                    }
                }

                final Intent cloneIntent = (Intent) intent.clone();
                cloneIntent.setComponent(new ComponentName(packageName, name));
                intentList.add(cloneIntent);
            }

            final Intent targetIntent = intentList.get(0);
            intentList.remove(0);

            chooserIntent = Intent.createChooser(targetIntent, null);
            if (!intentList.isEmpty()) {
                final Intent[] extraIntents = intentList.toArray(new Intent[intentList.size()]);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
                } else {
                    chooserIntent.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, extraIntents);
                }
            }
        }

        chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        ctx.startActivity(chooserIntent);

        return true;
    } catch (final Throwable exception) {
        Log.e(TAG, "sendEmail exception: ", exception);
        return false;
    }
}

From source file:com.bt.download.android.gui.activities.MainActivity.java

@Override
protected void onNewIntent(Intent intent) {

    if (isShutdown(intent)) {
        return;//from w ww. j a  va2s.c o m
    }

    String action = intent.getAction();
    //onResumeFragments();

    if (action != null && action.equals(Constants.ACTION_SHOW_TRANSFERS)) {
        if (Ads.isLoaded(Fetcher.AdFormat.interstitial, Constants.TAG_INTERSTITIAL_WIDGET)) {
            Ads.showAppWidget(this, null, Constants.TAG_INTERSTITIAL_WIDGET, Ads.ShowMode.FULL_SCREEN);
        }

        controller.showTransfers(TransferStatus.ALL);
    } else if (action != null && action.equals(Constants.ACTION_OPEN_TORRENT_URL)) {
        //Open a Torrent from a URL or from a local file :), say from Astro File Manager.
        /**
         * TODO: Ask @aldenml the best way to plug in NewTransferDialog.
         * I've refactored this dialog so that it is forced (no matter if the setting
         * to not show it again has been used) and when that happens the checkbox is hidden.
         * 
         * However that dialog requires some data about the download, data which is not
         * obtained until we have instantiated the Torrent object.
         * 
         * I'm thinking that we can either:
         * a) Pass a parameter to the transfer manager, but this would probably
         * not be cool since the transfer manager (I think) should work independently from
         * the UI thread.
         * 
         * b) Pass a "listener" to the transfer manager, once the transfer manager has the torrent
         * it can notify us and wait for the user to decide wether or not to continue with the transfer
         * 
         * c) Forget about showing that dialog, and just start the download, the user can cancel it.
         */

        //Show me the transfer tab
        Intent i = new Intent(this, MainActivity.class);
        i.setAction(Constants.ACTION_SHOW_TRANSFERS);
        i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(i);

        //go!
        TransferManager.instance().downloadTorrent(intent.getDataString());
    }
    // When another application wants to "Share" a file and has chosen FrostWire to do so.
    // We make the file "Shared" so it's visible for other FrostWire devices on the local network.
    else if (action != null
            && (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE))) {
        controller.handleSendAction(intent);
    }

    if (intent.hasExtra(Constants.EXTRA_DOWNLOAD_COMPLETE_NOTIFICATION)) {
        controller.showTransfers(TransferStatus.COMPLETED);
        TransferManager.instance().clearDownloadsToReview();
        try {
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .cancel(Constants.NOTIFICATION_DOWNLOAD_TRANSFER_FINISHED);
            Bundle extras = intent.getExtras();
            if (extras.containsKey(Constants.EXTRA_DOWNLOAD_COMPLETE_PATH)) {
                File file = new File(extras.getString(Constants.EXTRA_DOWNLOAD_COMPLETE_PATH));
                if (file.isFile()) {
                    UIUtils.openFile(this, file.getAbsoluteFile());
                }
            }
        } catch (Throwable e) {
            LOG.warn("Error handling download complete notification", e);
        }
    }
}

From source file:com.ubuntuone.android.files.activity.FilesActivity.java

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

    mTracker = GoogleAnalyticsTracker.getInstance();
    mTracker.start(Analytics.U1F_ACCOUNT, this);
    mTracker.trackPageView(TAG);/* w  w  w.ja va2 s  .  c om*/

    mHandler = new Handler();
    mReceiver = new DetachableResultReceiver(mHandler);

    mSignOutReceiver = new SignOutBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter("com.ubuntuone.android.files.SIGN_OUT");
    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
    lbm.registerReceiver(mSignOutReceiver, intentFilter);

    mResolver = getContentResolver();

    // Override splash screen background.
    getWindow().setBackgroundDrawableResource(android.R.drawable.screen_background_light);

    final ImageButton homeButton = (ImageButton) getActionBar().findViewById(R.id.gd_action_bar_home_item);
    homeButton.setImageResource(R.drawable.u1_logo);

    // Refresh
    addActionBarItem(Type.Refresh);
    mLoaderItem = (LoaderActionBarItem) getActionBar().getItem(ActionBar.REFRESH);
    mLoaderItem.setDrawable(R.drawable.ic_act_action_bar_refresh);
    // Upload
    addActionBarItem(Type.Add);
    mUploadItem = (NormalActionBarItem) getActionBar().getItem(ActionBar.UPLOAD);
    mUploadItem.setDrawable(R.drawable.ic_act_action_bar_add);

    onCreateUploadQuickActionGrid();

    getActionBar().setBackgroundResource(R.drawable.action_bar_background);

    mEmptyTextView = (TextView) findViewById(android.R.id.empty);

    ListView listView = getListView();
    listView.setEmptyView(mEmptyTextView);
    listView.setFastScrollEnabled(true);

    registerForContextMenu(getListView());

    mPathTracker = new PathTracker();

    if (NetworkUtil.getAvailableNetworkType(this) == -1) {
        UIUtil.showToast(this, R.string.toast_working_offline, true);
    }

    if (Preferences.hasTokens(this)) {
        mImageDownloader = U1CroppedImageDownloader.SMALL;
        onRefresh(null);
        suggestAutoUploadConfiguration();
        ChangeLogUtils.maybeShowChangelog(this);
    } else {
        final Intent intent = getIntent();
        final String data = (intent != null) ? intent.getDataString() : null;
        if (data != null && data.startsWith("x-ubuntuone-sso")) {
            validate();
        } else {
            signIn();
        }
    }

    String action = getIntent() != null ? getIntent().getAction() : null;
    if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
        mIsPickShareWithDirectoryMode = true;
        shareIntent = getIntent();
        showDialog(DIALOG_PICK_UPLOAD_DIRECTORY_ID);
    }
}

From source file:im.vector.activity.HomeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (CommonActivityUtils.shouldRestartApp()) {
        Log.e(LOG_TAG, "Restart the application.");
        CommonActivityUtils.restartApp(this);
    }/*from   www. ja v a 2  s .  com*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mMyRoomList = (ExpandableListView) findViewById(R.id.listView_myRooms);
    // the chevron is managed in the header view
    mMyRoomList.setGroupIndicator(null);
    mAdapter = new ConsoleRoomSummaryAdapter(this, Matrix.getMXSessions(this), R.layout.adapter_item_my_rooms,
            R.layout.adapter_room_section_header);

    if (null != savedInstanceState) {
        if (savedInstanceState.containsKey(PUBLIC_ROOMS_LIST_LIST)) {
            Serializable map = savedInstanceState.getSerializable(PUBLIC_ROOMS_LIST_LIST);

            if (null != map) {
                HashMap<String, List<PublicRoom>> hash = (HashMap<String, List<PublicRoom>>) map;
                mPublicRoomsListList = new ArrayList<List<PublicRoom>>(hash.values());
                mHomeServerNames = new ArrayList<>(hash.keySet());
            }
        }
    }

    final Intent intent = getIntent();
    if (intent.hasExtra(EXTRA_JUMP_TO_ROOM_ID)) {
        mAutomaticallyOpenedRoomId = intent.getStringExtra(EXTRA_JUMP_TO_ROOM_ID);
    }

    if (intent.hasExtra(EXTRA_JUMP_MATRIX_ID)) {
        mAutomaticallyOpenedMatrixId = intent.getStringExtra(EXTRA_JUMP_MATRIX_ID);
    }

    if (intent.hasExtra(EXTRA_ROOM_INTENT)) {
        mOpenedRoomIntent = intent.getParcelableExtra(EXTRA_ROOM_INTENT);
    }

    String action = intent.getAction();
    String type = intent.getType();

    // send files from external application
    if ((Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) && type != null) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CommonActivityUtils.sendFilesTo(HomeActivity.this, intent);
            }
        });
    }

    mMyRoomList.setAdapter(mAdapter);
    Collection<MXSession> sessions = Matrix.getMXSessions(HomeActivity.this);

    // check if  there is some valid session
    // the home activity could be relaunched after an application crash
    // so, reload the sessions before displaying the hidtory
    if (sessions.size() == 0) {
        Log.e(LOG_TAG, "Weird : onCreate : no session");

        if (null != Matrix.getInstance(this).getDefaultSession()) {
            Log.e(LOG_TAG, "No loaded session : reload them");
            startActivity(new Intent(HomeActivity.this, SplashActivity.class));
            HomeActivity.this.finish();
            return;
        }
    }

    for (MXSession session : sessions) {
        addSessionListener(session);
    }

    mMyRoomList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id) {

            if (mAdapter.isRecentsGroupIndex(groupPosition)) {
                String roomId = null;
                MXSession session = null;

                RoomSummary roomSummary = mAdapter.getRoomSummaryAt(groupPosition, childPosition);
                session = Matrix.getInstance(HomeActivity.this).getSession(roomSummary.getMatrixId());

                roomId = roomSummary.getRoomId();
                Room room = session.getDataHandler().getRoom(roomId);
                // cannot join a leaving room
                if ((null == room) || room.isLeaving()) {
                    roomId = null;
                }

                if (mAdapter.resetUnreadCount(groupPosition, roomId)) {
                    session.getDataHandler().getStore().flushSummary(roomSummary);
                }

                if (null != roomId) {
                    CommonActivityUtils.goToRoomPage(session, roomId, HomeActivity.this, null);
                }

            } else if (mAdapter.isPublicsGroupIndex(groupPosition)) {
                joinPublicRoom(mAdapter.getHomeServerURLAt(groupPosition),
                        mAdapter.getPublicRoomAt(groupPosition, childPosition));
            }

            return true;
        }
    });

    mMyRoomList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
                long packedPos = ((ExpandableListView) parent).getExpandableListPosition(position);
                final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPos);

                if (mAdapter.isRecentsGroupIndex(groupPosition)) {
                    final int childPosition = ExpandableListView.getPackedPositionChild(packedPos);

                    FragmentManager fm = HomeActivity.this.getSupportFragmentManager();
                    IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm
                            .findFragmentByTag(TAG_FRAGMENT_ROOM_OPTIONS);

                    if (fragment != null) {
                        fragment.dismissAllowingStateLoss();
                    }

                    final Integer[] lIcons = new Integer[] { R.drawable.ic_material_exit_to_app };
                    final Integer[] lTexts = new Integer[] { R.string.action_leave };

                    fragment = IconAndTextDialogFragment.newInstance(lIcons, lTexts, null,
                            HomeActivity.this.getResources().getColor(R.color.vector_title_color));
                    fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() {
                        @Override
                        public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) {
                            Integer selectedVal = lTexts[position];

                            if (selectedVal == R.string.action_leave) {
                                HomeActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        final RoomSummary roomSummary = mAdapter.getRoomSummaryAt(groupPosition,
                                                childPosition);
                                        final MXSession roomSession = Matrix.getInstance(HomeActivity.this)
                                                .getSession(roomSummary.getMatrixId());

                                        String roomId = roomSummary.getRoomId();
                                        Room room = roomSession.getDataHandler().getRoom(roomId);

                                        if (null != room) {
                                            room.leave(new SimpleApiCallback<Void>(HomeActivity.this) {
                                                @Override
                                                public void onSuccess(Void info) {
                                                    mAdapter.removeRoomSummary(groupPosition, roomSummary);
                                                    mAdapter.notifyDataSetChanged();
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        }
                    });

                    fragment.show(fm, TAG_FRAGMENT_ROOM_OPTIONS);

                    return true;
                }
            }

            return false;
        }
    });

    mMyRoomList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        @Override
        public void onGroupExpand(int groupPosition) {
            if (mAdapter.isPublicsGroupIndex(groupPosition)) {
                refreshPublicRoomsList();
            }
        }
    });

    mMyRoomList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            return mAdapter.getGroupCount() < 2;
        }
    });

    mSearchRoomEditText = (EditText) this.findViewById(R.id.editText_search_room);
    mSearchRoomEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(android.text.Editable s) {
            mAdapter.setSearchedPattern(s.toString());
            mMyRoomList.smoothScrollToPosition(0);
        }

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

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