Example usage for android.os Bundle getParcelable

List of usage examples for android.os Bundle getParcelable

Introduction

In this page you can find the example usage for android.os Bundle getParcelable.

Prototype

@Nullable
public <T extends Parcelable> T getParcelable(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

From source file:com.android.mms.ui.ComposeMessageActivity.java

private boolean handleSendIntent() {
    Intent intent = getIntent();//from www  .  ja v a  2  s.c o  m
    Bundle extras = intent.getExtras();
    if (extras == null) {
        return false;
    }

    final String mimeType = intent.getType();
    String action = intent.getAction();
    if (Intent.ACTION_SEND.equals(action)) {
        if (extras.containsKey(Intent.EXTRA_STREAM)) {
            final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
            getAsyncDialog().runAsync(new Runnable() {
                @Override
                public void run() {
                    addAttachment(mimeType, uri, false);
                }
            }, null, R.string.adding_attachments_title);
            return true;
        } else if (extras.containsKey(Intent.EXTRA_TEXT)) {
            mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT));
            return true;
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && extras.containsKey(Intent.EXTRA_STREAM)) {
        SlideshowModel slideShow = mWorkingMessage.getSlideshow();
        final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
        int currentSlideCount = slideShow != null ? slideShow.size() : 0;
        int importCount = uris.size();
        if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) {
            importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount, importCount);
            Toast.makeText(ComposeMessageActivity.this,
                    getString(R.string.too_many_attachments, SlideshowEditor.MAX_SLIDE_NUM, importCount),
                    Toast.LENGTH_LONG).show();
        }

        // Attach all the pictures/videos asynchronously off of the UI thread.
        // Show a progress dialog if adding all the slides hasn't finished
        // within half a second.
        final int numberToImport = importCount;
        getAsyncDialog().runAsync(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < numberToImport; i++) {
                    Parcelable uri = uris.get(i);
                    addAttachment(mimeType, (Uri) uri, true);
                }
            }
        }, null, R.string.adding_attachments_title);
        return true;
    }
    return false;
}

From source file:com.hybris.mobile.app.commerce.fragment.CatalogContentFragmentBase.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Breadcrum/*www.jav a  2 s  .  c o m*/
    mCategoryBreadcrumb = (TextView) getView().findViewById(R.id.catalog_content_header_breadcumb);
    mCategoryBreadcrumb.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Open the drawer
            DrawerLayout mCatalogDrawer = ((DrawerLayout) getActivity().findViewById(R.id.catalog_menu_drawer));
            mCatalogDrawer.openDrawer(mCatalogDrawer.getChildAt(1));
        }
    });

    List<ViewTypeItem> viewTypeTextViewList = new ArrayList<>();
    viewTypeTextViewList.add(new ViewTypeItem(getString(R.string.catalog_content_header_list_view),
            R.drawable.ic_subnav_list_blue));
    viewTypeTextViewList.add(new ViewTypeItem(getString(R.string.catalog_content_header_grid_view),
            R.drawable.ic_subnav_grid_blue));
    mItemViewTypeSpinner = (Spinner) getView().findViewById(R.id.catalog_content_header_view_type_spinner);
    ViewTypeAdapter mViewTypeAdapter = new ViewTypeAdapter(getActivity(), viewTypeTextViewList);
    mItemViewTypeSpinner.setAdapter(mViewTypeAdapter);
    mItemViewTypeSpinner.setOnItemSelectedListener(new ItemViewTypeSpinnerListener());

    // Select the default view
    mItemViewTypeSpinner.setSelection(SessionHelper.getCatalogContentViewType());

    // List/Line view
    mProductListView = (ListView) getView().findViewById(R.id.catalog_content_product_list);

    // Footer loading
    mFooterLoadingListView = getActivity().getLayoutInflater().inflate(R.layout.loading_spinner,
            mProductListView, false);

    // Grid view
    mProductGridView = (GridView) getView().findViewById(R.id.catalog_content_product_grid);

    // Infinite scroll listener for the list view
    mInfiniteScrollListener = new InfiniteScrollListener() {

        @Override
        public void loadNextItems(int page) {
            Log.i(TAG, "Loading the items for page " + page);
            mCurrentPage = page;
            updateProductList();
        }

    };

    mProductListView.setOnScrollListener(mInfiniteScrollListener);
    mProductGridView.setOnScrollListener(mInfiniteScrollListener);

    // Default product adapter
    mProductItemsAdapter = new ProductListAdapter(getActivity(), null, 0,
            CommerceApplication.getContentServiceHelper());

    // No product found view
    mNoProductFoundView = getActivity().findViewById(R.id.catalog_content_product_list_no_product_found);
    mNoProductFoundTextView = (TextView) getActivity()
            .findViewById(R.id.catalog_content_product_list_no_product_found_text);
    mNoProductFoundViewImage = getActivity()
            .findViewById(R.id.catalog_content_product_list_no_product_found_image);
    mNoProductFoundDidYouMeanView = getActivity()
            .findViewById(R.id.catalog_content_product_list_no_product_found_did_you_mean_view);
    mNoProductFoundDidYouMeanTextView = (TextView) getActivity()
            .findViewById(R.id.catalog_content_product_list_no_product_found_did_you_mean);

    // On click on did you mean, we update the list with the suggested term
    mNoProductFoundDidYouMeanTextView.setOnClickListener(mDidYouMeanOnClickListener);

    // Search header
    mSearchHeader = getActivity().findViewById(R.id.catalog_content_product_list_header_search);
    mSearchHeaderSearched = (TextView) getActivity()
            .findViewById(R.id.catalog_content_product_list_header_search_searched);
    mSearchHeaderDidYouMean = (TextView) getActivity()
            .findViewById(R.id.catalog_content_product_list_header_search_did_you_mean);
    mSearchHeaderDidYouMeanView = getActivity()
            .findViewById(R.id.catalog_content_product_list_header_search_did_you_mean_view);
    mSearchHeaderNbResults = (TextView) getActivity()
            .findViewById(R.id.catalog_content_product_list_header_search_nb_results);

    // On click on did you mean, we update the list with the suggested term
    mSearchHeaderDidYouMean.setOnClickListener(mDidYouMeanOnClickListener);

    // Restore the current category or search query
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(SAVED_INSTANCE_CATEGORY)) {
            mCurrentCategory = savedInstanceState.getParcelable(SAVED_INSTANCE_CATEGORY);
        }

        if (savedInstanceState.containsKey(SAVED_INSTANCE_SEARCH_TEXT)) {
            mCurrentSearchText = savedInstanceState.getString(SAVED_INSTANCE_SEARCH_TEXT);
        }

    }

    // Product list loader
    mProductListLoader = new ProductListLoader(getActivity(), CommerceApplication.getContentServiceHelper(),
            mProductItemsAdapter, new QueryProducts(), new OnRequestListener() {

                @Override
                public void beforeRequest() {
                    showLoading(true);
                }

                @Override
                public void afterRequestBeforeResponse() {

                }

                @Override
                public void afterRequest(boolean isDataSynced) {
                    updateUI(false, null, mProductItemsAdapter.getCount());
                    mInitialCall = false;

                    // TODO - offline enabling this will cause the content provider provider to ba called infinitly
                    showLoading(false);
                }
            });

}

From source file:org.xingjitong.ChatFragment.java

@SuppressLint("Recycle")
@SuppressWarnings("static-access")
@Override/*from   w  w  w .  ja  v  a 2s . c o m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(getActivity());
    if (share.getInt(getString(R.string.setting_reg_uid), 0) == 0) {
        Toast.makeText(getActivity(), "!?,?!",
                Toast.LENGTH_LONG).show();
        getActivity().getSupportFragmentManager().popBackStack();
    }
    String displayName = getArguments().getString("DisplayName");
    String pictureUri = getArguments().getString("PictureUri");

    sipUri = getArguments().getString("SipUri");
    sipUri = sipUri.substring(sipUri.indexOf(":") + 1, sipUri.indexOf("@"));

    try {
        LinphoneAddress address = LinphoneManager.getInstance().getLc().interpretUrl(sipUri);
        sipUri = address.asString();
        sipUri = sipUri.replace("<", "").replace(">", "");
    } catch (LinphoneCoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    view = inflater.inflate(R.layout.chat, container, false);

    contactName = (TextView) view.findViewById(R.id.contactName);
    contactPicture = (AvatarWithShadow) view.findViewById(R.id.contactPicture);

    sendMessage = (TextView) view.findViewById(R.id.sendMessage);
    sendMessage.setOnClickListener(this);

    message = (EditText) view.findViewById(R.id.message);
    if (!getActivity().getResources().getBoolean(R.bool.allow_chat_multiline)) {
        message.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
        message.setMaxLines(1);
    }

    uploadLayout = (RelativeLayout) view.findViewById(R.id.uploadLayout);
    textLayout = (RelativeLayout) view.findViewById(R.id.messageLayout);

    messagesLayout = (RelativeLayout) view.findViewById(R.id.messages);
    messagesScrollView = (ScrollView) view.findViewById(R.id.chatScrollView);
    progressBar = (ProgressBar) view.findViewById(R.id.progressbar);

    sendImage = (TextView) view.findViewById(R.id.sendPicture);
    registerForContextMenu(sendImage);
    sendImage.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            pickImage();
        }
    });

    cancelUpload = (ImageView) view.findViewById(R.id.cancelUpload);
    cancelUpload.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadThread.interrupt();
            uploadLayout.setVisibility(View.GONE);
            textLayout.setVisibility(View.VISIBLE);
            progressBar.setProgress(0);
        }
    });

    displayChat(displayName, pictureUri);

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    if (lc != null) {
        chatRoom = lc.createChatRoom(sipUri);
    }

    // SharedPreferences prefs =
    // PreferenceManager.getDefaultSharedPreferences(LinphoneActivity.instance());
    // uploadServerUri =
    // prefs.getString(getString(R.string.pref_image_sharing_server_key),
    // getString(R.string.pref_image_sharing_server_default));
    uploadServerUri = getString(R.string.pref_image_sharing_server_default);

    textWatcher = new TextWatcher() {
        public void afterTextChanged(Editable arg0) {

        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            if (message.getText().toString().equals("")) {
                sendMessage.setEnabled(false);
            } else {
                sendMessage.setEnabled(true);
            }
        }
    };

    // Force hide keyboard
    if (LinphoneActivity.isInstanciated()) {
        InputMethodManager imm = (InputMethodManager) LinphoneActivity.instance()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    // Workaround for SGS3 issue
    if (savedInstanceState != null) {
        fileToUploadPath = savedInstanceState.getString("fileToUploadPath");
        imageToUpload = savedInstanceState.getParcelable("imageToUpload");
    }
    if (fileToUploadPath != null || imageToUpload != null) {
        sendImage.post(new Runnable() {
            @Override
            public void run() {
                sendImage.showContextMenu();
            }
        });
    }

    return view;
}

From source file:com.android.launcher3.Launcher.java

/**
 * Restores the previous state, if it exists.
 *
 * @param savedState The previous state.
 *///w w w.  j  a  va 2s.  c  o  m
private void restoreState(Bundle savedState) {
    if (savedState == null) {
        return;
    }

    State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
    if (state == State.APPS || state == State.WIDGETS) {
        mOnResumeState = state;
    }

    int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, PagedView.INVALID_RESTORE_PAGE);
    if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
        mWorkspace.setRestorePage(currentScreen);
    }

    PendingRequestArgs requestArgs = savedState.getParcelable(RUNTIME_STATE_PENDING_REQUEST_ARGS);
    if (requestArgs != null) {
        setWaitingForResult(requestArgs);
    }

    mPendingActivityResult = savedState.getParcelable(RUNTIME_STATE_PENDING_ACTIVITY_RESULT);
}

From source file:fr.univsavoie.ltp.client.MainActivity.java

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

    // Appliquer le thme LTP a l'ActionBar
    //setTheme(R.style.Theme_ltp);

    // Cration de l'activit principale
    setContentView(R.layout.activity_main);

    // Instancier les classes utiles
    setPopup(new Popup(this));
    setSession(new Session(this));
    setTools(new Tools(this));

    // Afficher la ActionBar
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setHomeButtonEnabled(true);
    mActionBar.setDisplayShowHomeEnabled(true);

    // MapView settings
    map = (MapView) findViewById(R.id.openmapview);
    map.setTileSource(TileSourceFactory.MAPNIK);
    map.setBuiltInZoomControls(false);// ww  w . j  a  v a 2  s . c  o  m
    map.setMultiTouchControls(true);

    // MapController settings
    mapController = map.getController();

    //To use MapEventsReceiver methods, we add a MapEventsOverlay:
    overlay = new MapEventsOverlay(this, this);
    map.getOverlays().add(overlay);

    boolean isWifiEnabled = false;
    boolean isGPSEnabled = false;

    // Vrifier si le wifi ou le rseau mobile est activ
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wifi.isAvailable() && (wifi.getDetailedState() == DetailedState.CONNECTING
            || wifi.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_wifi, Toast.LENGTH_LONG).show();
        isWifiEnabled = true;
    } else if (mobile.isAvailable() && (mobile.getDetailedState() == DetailedState.CONNECTING
            || mobile.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_3G, Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, R.string.toast_aucun_reseau, Toast.LENGTH_LONG).show();
    }

    // Obtenir le service de localisation
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Verifier si le service de localisation GPS est actif, le cas echeant, tester le rseau
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        isGPSEnabled = true;
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    // Afficher une boite de dialogue et proposer d'activer un ou plusieurs services pas actifs
    if (!isWifiEnabled || !isGPSEnabled) {
        //getTools().showSettingsAlert(this, isWifiEnabled, isGPSEnabled);
    }

    // Si on a une localisation, on dfinit ses coordonnes geopoint
    if (location != null) {
        startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
    } else {
        // Sinon, on indique des paramtres par dfaut
        location = getTools().getLastKnownLocation(locationManager);
        if (location == null) {
            location = new Location("");
            location.setLatitude(46.227638);
            location.setLongitude(2.213749000000);
        }
        startPoint = new GeoPoint(46.227638, 2.213749000000);
    }

    setLongitude(location.getLongitude());
    setLatitude(location.getLatitude());

    destinationPoint = null;
    viaPoints = new ArrayList<GeoPoint>();

    // On recupre quelques paramtres de la session prcdents si possible
    if (savedInstanceState == null) {
        mapController.setZoom(15);
        mapController.setCenter(startPoint);
    } else {
        mapController.setZoom(savedInstanceState.getInt("zoom_level"));
        mapController.setCenter((GeoPoint) savedInstanceState.getParcelable("map_center"));
    }

    // Crer un overlay sur la carte pour afficher notre point de dpart
    myLocationOverlay = new SimpleLocationOverlay(this, new DefaultResourceProxyImpl(this));
    map.getOverlays().add(myLocationOverlay);
    myLocationOverlay.setLocation(startPoint);

    // Boutton pour zoomer la carte
    ImageButton btZoomIn = (ImageButton) findViewById(R.id.btZoomIn);
    btZoomIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomIn();
        }
    });

    // Boutton pour dezoomer la carte
    ImageButton btZoomOut = (ImageButton) findViewById(R.id.btZoomOut);
    btZoomOut.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomOut();
        }
    });

    // Pointeurs d'itinrairea:
    final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>();
    itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map,
            new ViaPointInfoWindow(R.layout.itinerary_bubble, map));
    map.getOverlays().add(itineraryMarkers);
    //updateUIWithItineraryMarkers();

    Button searchButton = (Button) findViewById(R.id.buttonSearch);
    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            handleSearchLocationButton();
        }
    });

    //context menu for clicking on the map is registered on this button. 
    registerForContextMenu(searchButton);

    // Routes et Itinraires
    final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>();
    roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map);
    map.getOverlays().add(roadNodeMarkers);

    if (savedInstanceState != null) {
        mRoad = savedInstanceState.getParcelable("road");
        updateUIWithRoad(mRoad);
    }

    //POIs:
    //POI search interface:
    String[] poiTags = getResources().getStringArray(R.array.poi_tags);
    poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            poiTags);
    poiTagText.setAdapter(adapter);
    Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag);
    setPOITagButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Hide the soft keyboard:
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0);
            //Start search:
            getPOIAsync(poiTagText.getText().toString());
        }
    });

    //POI markers:
    final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>();
    poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map,
            new POIInfoWindow(map));
    map.getOverlays().add(poiMarkers);
    if (savedInstanceState != null) {
        mPOIs = savedInstanceState.getParcelableArrayList("poi");
        updateUIWithPOI(mPOIs);
    }

    // Load friends ListView
    lvListeFriends = (ListView) findViewById(R.id.listViewFriends);
    //lvListeFriends.setBackgroundResource(R.drawable.listview_roundcorner_item);
    lvListeFriends.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            Friends item = (Friends) adapter.getItemAtPosition(position);
            if (item.getLongitude() != 0.0 && item.getLatitude() != 0.0) {
                destinationPoint = new GeoPoint(item.getLongitude(), item.getLatitude());
                markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX,
                        R.string.destination, R.drawable.marker_destination, -1);
                getRoadAsync();
                map.getController().setCenter(destinationPoint);
            } else {
                Toast.makeText(MainActivity.this, R.string.toast_friend_statut, Toast.LENGTH_LONG).show();
            }
        }
    });

    viewMapFilters = (ScrollView) this.findViewById(R.id.scrollViewMapFilters);
    viewMapFilters.setVisibility(View.GONE);

    // Initialiser tout ce qui est donnes utilisateur propres  l'activit
    init();

    getTools().relocateUser(mapController, map, myLocationOverlay, location);
}

From source file:me.willowcheng.makerthings.ui.OpenHABMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate()");
    // Check if we are in development mode
    perPreferences = getSharedPreferences("pref", this.MODE_PRIVATE);
    isDeveloper = false;//from  www .  j a  v  a2  s .c  o m
    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    // Set non-persistent HABDroid version preference to current version from application package
    try {
        Log.d(TAG, "App version = " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.PREFERENCE_APPVERSION,
                getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit();
    } catch (PackageManager.NameNotFoundException e1) {
        if (e1 != null)
            Log.d(TAG, e1.getMessage());
    }
    checkDiscoveryPermissions();
    checkVoiceRecognition();
    // initialize loopj async http client
    mAsyncHttpClient = new MyAsyncHttpClient(this);
    // Set the theme to one from preferences
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    // Disable screen timeout if set in preferences
    if (mSettings.getBoolean(Constants.PREFERENCE_SCREENTIMEROFF, false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    // Fetch openHAB service type name from strings.xml
    openHABServiceType = getString(R.string.openhab_service_type);
    // Get username/password from preferences
    openHABUsername = mSettings.getString(Constants.PREFERENCE_USERNAME, null);
    openHABPassword = mSettings.getString(Constants.PREFERENCE_PASSWORD, null);
    mAsyncHttpClient.setBasicAuth(openHABUsername, openHABPassword, true);
    mAsyncHttpClient.setTimeout(30000);
    if (!isDeveloper)
        Util.initCrittercism(getApplicationContext(), "5117659f59e1bd4ba9000004");
    Util.setActivityTheme(this);
    super.onCreate(savedInstanceState);
    if (!isDeveloper)
        ((HABDroid) getApplication()).getTracker(HABDroid.TrackerName.APP_TRACKER);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.openhab_toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // ProgressBar layout params inside the toolbar have to be done programmatically
    // because it doesn't work through layout file :-(
    mProgressBar = (SwipeRefreshLayout) findViewById(R.id.toolbar_progress_bar);
    mProgressBar.setColorSchemeColors(getResources().getColor(R.color.theme_accent));
    mProgressBar.setEnabled(false);
    mProgressBar.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mProgressBar.setRefreshing(false);
        }
    });
    //        mProgressBar.setLayoutParams(new Toolbar.LayoutParams(Gravity.RIGHT));
    startProgressIndicator();
    gcmRegisterBackground();
    // Enable app icon in action bar work as 'home'
    //        this.getActionBar().setHomeButtonEnabled(true);
    pager = (OpenHABViewPager) findViewById(R.id.pager);
    pager.setScrollDurationFactor(2.5);
    pager.setOffscreenPageLimit(1);
    pagerAdapter = new OpenHABFragmentPagerAdapter(getSupportFragmentManager());
    pagerAdapter.setColumnsNumber(getResources().getInteger(R.integer.pager_columns));
    pagerAdapter.setOpenHABUsername(openHABUsername);
    pagerAdapter.setOpenHABPassword(openHABPassword);
    pager.setAdapter(pagerAdapter);
    pager.setOnPageChangeListener(pagerAdapter);
    MemorizingTrustManager.setResponder(this);
    //        pager.setPageMargin(1);
    //        pager.setPageMarginDrawable(android.R.color.darker_gray);
    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl");
        sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl");
        mStartedWithNetworkConnectivityInfo = savedInstanceState
                .getParcelable("startedWithNetworkConnectivityInfo");
        mOpenHABVersion = savedInstanceState.getInt("openHABVersion");
        mSitemapList = savedInstanceState.getParcelableArrayList("sitemapList");
    }
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
            R.string.app_name) {
        public void onDrawerClosed(View view) {
            Log.d(TAG, "onDrawerClosed");
            getSupportActionBar().setTitle(pagerAdapter.getPageTitle(pager.getCurrentItem()));
        }

        public void onDrawerOpened(View drawerView) {
            Log.d(TAG, "onDrawerOpened");
            getSupportActionBar().setTitle("Makerthings");
            loadSitemapList(OpenHABMainActivity.this.openHABBaseUrl);
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    if (mSitemapList == null)
        mSitemapList = new ArrayList<OpenHABSitemap>();
    mDrawerItemList = new ArrayList<OpenHABDrawerItem>();
    mDrawerAdapter = new OpenHABDrawerAdapter(this, R.layout.openhabdrawer_sitemap_item, mDrawerItemList);
    mDrawerAdapter.setOpenHABUsername(openHABUsername);
    mDrawerAdapter.setOpenHABPassword(openHABPassword);
    mDrawerList.setAdapter(mDrawerAdapter);
    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int item, long l) {
            Log.d(TAG, "Drawer selected item " + String.valueOf(item));
            if (mDrawerItemList != null && mDrawerItemList.get(item)
                    .getItemType() == OpenHABDrawerItem.DrawerItemType.SITEMAP_ITEM) {
                Log.d(TAG, "This is sitemap " + mDrawerItemList.get(item).getSiteMap().getLink());
                mDrawerLayout.closeDrawers();
                openSitemap(mDrawerItemList.get(item).getSiteMap().getHomepageLink());
            } else {
                Log.d(TAG, "This is not sitemap");
                if (mDrawerItemList.get(item).getTag() == DRAWER_NOTIFICATIONS) {
                    Log.d(TAG, "Notifications selected");
                    mDrawerLayout.closeDrawers();
                    OpenHABMainActivity.this.openNotifications();
                } else if (mDrawerItemList.get(item).getTag() == DRAWER_BINDINGS) {
                    Log.d(TAG, "Bindings selected");
                    mDrawerLayout.closeDrawers();
                    OpenHABMainActivity.this.openBindings();
                } else if (mDrawerItemList.get(item).getTag() == DRAWER_INBOX) {
                    Log.d(TAG, "Inbox selected");
                    mDrawerLayout.closeDrawers();
                    OpenHABMainActivity.this.openDiscoveryInbox();
                }
            }
        }
    });
    loadDrawerItems();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    if (getIntent() != null) {
        Log.d(TAG, "Intent != null");
        if (getIntent().getAction() != null) {
            Log.d(TAG, "Intent action = " + getIntent().getAction());
            if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) {
                Log.d(TAG, "This is NFC action");
                if (getIntent().getDataString() != null) {
                    Log.d(TAG, "NFC data = " + getIntent().getDataString());
                    mNfcData = getIntent().getDataString();
                }
            } else if (getIntent().getAction().equals("org.openhab.notification.selected")) {
                onNotificationSelected(getIntent());
            } else if (getIntent().getAction().equals("android.intent.action.VIEW")) {
                Log.d(TAG, "This is URL Action");
                String URL = getIntent().getDataString();
                mNfcData = URL;
            }
        }
    }

    /**
     * If we are 4.4 we can use fullscreen mode and Daydream features
     */
    supportsKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    boolean fullScreen = mSettings.getBoolean("default_openhab_fullscreen", false);

    if (supportsKitKat && fullScreen) {
        registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STARTED"));
        registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STOPPED"));
        checkFullscreen();
    }
}

From source file:com.android.messaging.ui.conversation.ConversationFragment.java

/**
 * {@inheritDoc} from Fragment//from   w  ww .j  av  a  2 s .  c  o  m
 */
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.conversation_fragment, container, false);
    mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
    final LinearLayoutManager manager = new LinearLayoutManager(getActivity());
    manager.setStackFromEnd(true);
    manager.setReverseLayout(false);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(manager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator() {
        private final List<ViewHolder> mAddAnimations = new ArrayList<ViewHolder>();
        private PopupTransitionAnimation mPopupTransitionAnimation;

        @Override
        public boolean animateAdd(final ViewHolder holder) {
            final ConversationMessageView view = (ConversationMessageView) holder.itemView;
            final ConversationMessageData data = view.getData();
            endAnimation(holder);
            final long timeSinceSend = System.currentTimeMillis() - data.getReceivedTimeStamp();
            if (data.getReceivedTimeStamp() == InsertNewMessageAction.getLastSentMessageTimestamp()
                    && !data.getIsIncoming() && timeSinceSend < MESSAGE_ANIMATION_MAX_WAIT) {
                final ConversationMessageBubbleView messageBubble = (ConversationMessageBubbleView) view
                        .findViewById(R.id.message_content);
                final Rect startRect = UiUtils.getMeasuredBoundsOnScreen(mComposeMessageView);
                final View composeBubbleView = mComposeMessageView.findViewById(R.id.compose_message_text);
                final Rect composeBubbleRect = UiUtils.getMeasuredBoundsOnScreen(composeBubbleView);
                final AttachmentPreview attachmentView = (AttachmentPreview) mComposeMessageView
                        .findViewById(R.id.attachment_draft_view);
                final Rect attachmentRect = UiUtils.getMeasuredBoundsOnScreen(attachmentView);
                if (attachmentView.getVisibility() == View.VISIBLE) {
                    startRect.top = attachmentRect.top;
                } else {
                    startRect.top = composeBubbleRect.top;
                }
                startRect.top -= view.getPaddingTop();
                startRect.bottom = composeBubbleRect.bottom;
                startRect.left += view.getPaddingRight();

                view.setAlpha(0);
                mPopupTransitionAnimation = new PopupTransitionAnimation(startRect, view);
                mPopupTransitionAnimation.setOnStartCallback(new Runnable() {
                    @Override
                    public void run() {
                        final int startWidth = composeBubbleRect.width();
                        attachmentView.onMessageAnimationStart();
                        messageBubble.kickOffMorphAnimation(startWidth,
                                messageBubble.findViewById(R.id.message_text_and_info).getMeasuredWidth());
                    }
                });
                mPopupTransitionAnimation.setOnStopCallback(new Runnable() {
                    @Override
                    public void run() {
                        view.setAlpha(1);
                    }
                });
                mPopupTransitionAnimation.startAfterLayoutComplete();
                mAddAnimations.add(holder);
                return true;
            } else {
                return super.animateAdd(holder);
            }
        }

        @Override
        public void endAnimation(final ViewHolder holder) {
            if (mAddAnimations.remove(holder)) {
                holder.itemView.clearAnimation();
            }
            super.endAnimation(holder);
        }

        @Override
        public void endAnimations() {
            for (final ViewHolder holder : mAddAnimations) {
                holder.itemView.clearAnimation();
            }
            mAddAnimations.clear();
            if (mPopupTransitionAnimation != null) {
                mPopupTransitionAnimation.cancel();
            }
            super.endAnimations();
        }
    });
    mRecyclerView.setAdapter(mAdapter);

    if (savedInstanceState != null) {
        mListState = savedInstanceState.getParcelable(SAVED_INSTANCE_STATE_LIST_VIEW_STATE_KEY);
    }

    mConversationComposeDivider = view.findViewById(R.id.conversation_compose_divider);
    mScrollToDismissThreshold = ViewConfiguration.get(getActivity()).getScaledTouchSlop();
    mRecyclerView.addOnScrollListener(mListScrollListener);
    mFastScroller = ConversationFastScroller.addTo(mRecyclerView,
            UiUtils.isRtlMode() ? ConversationFastScroller.POSITION_LEFT_SIDE
                    : ConversationFastScroller.POSITION_RIGHT_SIDE);

    mComposeMessageView = (ComposeMessageView) view.findViewById(R.id.message_compose_view_container);
    // Bind the compose message view to the DraftMessageData
    mComposeMessageView.bind(DataModel.get().createDraftMessageData(mBinding.getData().getConversationId()),
            this);

    return view;
}

From source file:com.android.soma.Launcher.java

/**
 * Restores the previous state, if it exists.
 *
 * @param savedState The previous state.
 *//*from www  . j a  va 2  s .  c om*/
private void restoreState(Bundle savedState) {
    if (savedState == null) {
        return;
    }

    State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
    if (state == State.APPS_CUSTOMIZE) {
        mOnResumeState = State.APPS_CUSTOMIZE;
    }

    int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, PagedView.INVALID_RESTORE_PAGE);
    if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
        mWorkspace.setRestorePage(currentScreen);
    }

    final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
    final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);

    if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
        mPendingAddInfo.container = pendingAddContainer;
        mPendingAddInfo.screenId = pendingAddScreen;
        mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
        mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
        mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
        mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
        mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
        mWaitingForResult = true;
        mRestoring = true;
    }

    boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
    if (renameFolder) {
        long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
        mFolderInfo = mModel.getFolderById(this, sFolders, id);
        mRestoring = true;
    }

    // Restore the AppsCustomize tab
    if (mAppsCustomizeTabHost != null) {
        String curTab = savedState.getString("apps_customize_currentTab");
        if (curTab != null) {
            mAppsCustomizeTabHost
                    .setContentTypeImmediate(mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
            mAppsCustomizeContent.loadAssociatedPages(mAppsCustomizeContent.getCurrentPage());
        }

        int currentIndex = savedState.getInt("apps_customize_currentIndex");
        mAppsCustomizeContent.restorePageForIndex(currentIndex);
    }
}