Example usage for android.content Intent resolveActivity

List of usage examples for android.content Intent resolveActivity

Introduction

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

Prototype

public ComponentName resolveActivity(@NonNull PackageManager pm) 

Source Link

Document

Return the Activity component that should be used to handle this intent.

Usage

From source file:bikebadger.RideFragment.java

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

    Log.d(Constants.APP.TAG, "RideFragment.onCreate()");
    //setRetainInstance(true);

    mRideManager = RideManager.get(getActivity());
    Log.d(Constants.APP.TAG, "mRideManager set = RideManager.get(" + getActivity() + ")");

    setHasOptionsMenu(true);/*from w  w  w  .  ja  va2s .com*/

    // check for a Ride ID as an argument, and find the run
    Bundle args = getArguments();
    if (args != null) {
        long runId = args.getLong(ARG_RUN_ID, -1);
        Log.d(Constants.APP.TAG, "RideFragment.onCreate() runId=" + runId);
        if (runId != -1) {
            LoaderManager lm = getLoaderManager();
            lm.initLoader(LOAD_RUN, args, new RunLoaderCallbacks());
            lm.initLoader(LOAD_LOCATION, args, new LocationLoaderCallbacks());
        }
    }

    // Initialize the TextToSpeech Engine...
    // TODO this engine may not exist. Provide the ability to run without it.
    Intent checkTTSIntent = new Intent();
    checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);

    if (checkTTSIntent.resolveActivity(mRideManager.mAppContext.getPackageManager()) != null) {
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE_REQUEST);
    } else {
        Log.d(Constants.APP.TAG, "Could not find TTS Intent");
        MyToast.Show(getActivity(), "Could not find Text To Speech Service", Color.RED);
        AlertDialog ad1 = new AlertDialog.Builder(getActivity()).create();
        ad1.setCancelable(false);
        ad1.setTitle("Text To Speech Engine Not Found");
        ad1.setMessage(
                "There was a problem finding the Text To Speech Engine. Make sure it's install properly under Language and Input Settings.");
        ad1.setButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        ad1.show();

    }

    if (mRideManager.mLoadLastGPXFile) {
        Log.d(Constants.APP.TAG, "mLoadLastGPXFile=" + mRideManager.mLoadLastGPXFile);
        Log.d(Constants.APP.TAG, "mCurrentGPXPath=" + mRideManager.mCurrentGPXPath);

        OpenGPXFileOnNewThreadWithDialog(mRideManager.mCurrentGPXPath);
    }

    if (!mRideManager.IsGPSEnabled()) {
        ShowAlertMessageNoGps();
    }

    // keep the screen on so it doesn't time out and turn dark
    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

}

From source file:com.master.metehan.filtereagle.ActivityMain.java

private void checkExtras(Intent intent) {
    // Approve request
    if (intent.hasExtra(EXTRA_APPROVE)) {
        Log.i(TAG, "Requesting VPN approval");
        swEnabled.toggle();// w w  w . j  a v a  2  s.co  m
    }

    if (intent.hasExtra(EXTRA_LOGCAT)) {
        Log.i(TAG, "Requesting logcat");
        Intent logcat = getIntentLogcat();
        if (logcat.resolveActivity(getPackageManager()) != null)
            startActivityForResult(logcat, REQUEST_LOGCAT);
    }
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.ObjectStatusFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    MainActivity activity = (MainActivity) getActivity();
    View view = inflater.inflate(R.layout.fragment_object_status, null);

    mLineName = (TextView) view.findViewById(R.id.line_name_st);
    mObjectNameCaption = (TextView) view.findViewById(R.id.object_name_caption_st);
    mObjectName = (TextView) view.findViewById(R.id.object_name_st);
    mCompleteStatusButton = (Button) view.findViewById(R.id.complete_status_st);
    mPhotoHintText = (TextView) view.findViewById(R.id.photo_hint_text_st);
    mMakePhotoButton = (Button) view.findViewById(R.id.btn_make_photo_st);
    mPhotoGallery = (RecyclerView) view.findViewById(R.id.photo_gallery_st);

    registerForContextMenu(mPhotoGallery);

    String toolbarTitle = "";

    switch (mFoclStructLayerType) {
    case FoclConstants.LAYERTYPE_FOCL_OPTICAL_CABLE:
        toolbarTitle = activity.getString(R.string.cable_laying);
        mObjectNameCaption.setText(R.string.optical_cable_colon);
        break;//from   ww w .  jav  a  2  s .  co  m

    case FoclConstants.LAYERTYPE_FOCL_FOSC:
        toolbarTitle = activity.getString(R.string.fosc_mounting);
        mObjectNameCaption.setText(R.string.fosc_colon);
        break;

    case FoclConstants.LAYERTYPE_FOCL_OPTICAL_CROSS:
        toolbarTitle = activity.getString(R.string.cross_mounting);
        mObjectNameCaption.setText(R.string.cross_colon);
        break;

    case FoclConstants.LAYERTYPE_FOCL_ACCESS_POINT:
        toolbarTitle = activity.getString(R.string.access_point_mounting);
        mObjectNameCaption.setText(R.string.access_point_colon);
        break;

    case FoclConstants.LAYERTYPE_FOCL_SPECIAL_TRANSITION:
        toolbarTitle = activity.getString(R.string.special_transition_laying);
        break;
    }

    activity.setBarsView(toolbarTitle);

    mCompleteStatusButton.setText(activity.getString(R.string.completed));
    mPhotoHintText.setText(R.string.take_photos_to_confirm);

    final GISApplication app = (GISApplication) getActivity().getApplication();
    final FoclProject foclProject = app.getFoclProject();

    if (null == foclProject) {
        setBlockedView();
        return view;
    }

    FoclStruct foclStruct;
    try {
        foclStruct = (FoclStruct) foclProject.getLayer(mLineId);
    } catch (Exception e) {
        foclStruct = null;
    }

    if (null == foclStruct) {
        setBlockedView();
        return view;
    }

    FoclVectorLayer layer = (FoclVectorLayer) foclStruct.getLayerByFoclType(mFoclStructLayerType);

    if (null == layer) {
        setBlockedView();
        return view;
    }

    if (null == mObjectId) {
        setBlockedView();
        return view;
    }

    mLineName.setText(Html.fromHtml(foclStruct.getHtmlFormattedNameTwoStringsSmall()));
    mObjectLayerName = layer.getPath().getName();

    Uri uri = Uri
            .parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName + "/" + mObjectId);

    String proj[] = { FIELD_ID, FoclConstants.FIELD_NAME, FoclConstants.FIELD_STATUS_BUILT };

    Cursor objectCursor;

    try {
        objectCursor = getActivity().getContentResolver().query(uri, proj, null, null, null);

    } catch (Exception e) {
        Log.d(TAG, e.getLocalizedMessage());
        objectCursor = null;
    }

    boolean blockView = false;

    if (null != objectCursor) {
        try {
            if (objectCursor.getCount() == 1 && objectCursor.moveToFirst()) {

                String objectNameText = ObjectCursorAdapter.getObjectName(mContext, objectCursor);
                mObjectStatus = objectCursor
                        .getString(objectCursor.getColumnIndex(FoclConstants.FIELD_STATUS_BUILT));

                if (TextUtils.isEmpty(mObjectStatus)) {
                    mObjectStatus = FoclConstants.FIELD_VALUE_UNKNOWN;
                }

                mObjectName.setText(objectNameText);
                setStatusButtonView(true);

            } else {
                blockView = true;
            }

        } catch (Exception e) {
            blockView = true;
            //Log.d(TAG, e.getLocalizedMessage());
        } finally {
            objectCursor.close();
        }

    } else {
        blockView = true;
    }

    if (blockView) {
        setBlockedView();
        return view;
    }

    View.OnClickListener statusButtonOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (mObjectStatus) {
            case FoclConstants.FIELD_VALUE_PROJECT:
                mObjectStatus = FoclConstants.FIELD_VALUE_BUILT;
                break;

            case FoclConstants.FIELD_VALUE_BUILT:
                mObjectStatus = FoclConstants.FIELD_VALUE_PROJECT;
                break;

            case FoclConstants.FIELD_VALUE_UNKNOWN:
            default:
                mObjectStatus = FoclConstants.FIELD_VALUE_BUILT;
                break;
            }

            Uri uri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName);
            Uri updateUri = ContentUris.withAppendedId(uri, mObjectId);

            ContentValues values = new ContentValues();
            Calendar calendar = Calendar.getInstance();

            values.put(FoclConstants.FIELD_STATUS_BUILT, mObjectStatus);
            values.put(FoclConstants.FIELD_STATUS_BUILT_CH, calendar.getTimeInMillis());

            int result = 0;
            try {
                result = getActivity().getContentResolver().update(updateUri, values, null, null);

            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }

            if (result == 0) {
                Log.d(TAG, "Layer: " + mObjectLayerName + ", id: " + mObjectId + ", update FAILED");
            } else {
                Log.d(TAG, "Layer: " + mObjectLayerName + ", id: " + mObjectId + ", update result: " + result);
                setStatusButtonView(true);
            }
        }
    };

    ActionBar actionBar = activity.getSupportActionBar();
    if (actionBar != null) {
        View customActionBarView = actionBar.getCustomView();
        View saveMenuItem = customActionBarView.findViewById(R.id.custom_toolbar_button_layout);
        saveMenuItem.setOnClickListener(statusButtonOnClickListener); // TODO: it is test
    }

    mCompleteStatusButton.setOnClickListener(statusButtonOnClickListener);

    mMakePhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // Ensure that there's a camera activity to handle the intent
            if (null != cameraIntent.resolveActivity(getActivity().getPackageManager())) {

                try {
                    File tempFile = new File(app.getDataDir(), "temp-photo.jpg");

                    if (!tempFile.exists() && tempFile.createNewFile()
                            || tempFile.exists() && tempFile.delete() && tempFile.createNewFile()) {

                        mTempPhotoPath = tempFile.getAbsolutePath();

                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                        startActivityForResult(cameraIntent, REQUEST_TAKE_PHOTO);
                    }

                } catch (IOException e) {
                    Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(),
            LinearLayoutManager.HORIZONTAL, false);

    mPhotoGallery.setLayoutManager(layoutManager);
    mPhotoGallery.setHasFixedSize(true);
    setPhotoGalleryAdapter();

    setPhotoGalleryVisibility(true);

    return view;
}

From source file:freed.viewer.screenslide.ScreenSlideFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    view = inflater.inflate(layout.freedviewer_screenslide_fragment, container, false);

    mImageThumbSize = getResources().getDimensionPixelSize(dimen.image_thumbnail_size);
    activityInterface = (ActivityInterface) getActivity();

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) view.findViewById(id.pager);
    topbar = (LinearLayout) view.findViewById(id.top_bar);
    histogram = (MyHistogram) view.findViewById(id.screenslide_histogram);

    closeButton = (Button) view.findViewById(id.button_closeView);
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override//from  ww  w.java 2  s .  co m
        public void onClick(View v) {
            if (thumbclick != null) {
                thumbclick.onThumbClick(mPager.getCurrentItem(), view);
                mPager.setCurrentItem(0);
            } else
                getActivity().finish();
        }
    });

    bottombar = (LinearLayout) view.findViewById(id.bottom_bar);

    exifinfo = (LinearLayout) view.findViewById(id.exif_info);
    exifinfo.setVisibility(View.GONE);
    iso = (TextView) view.findViewById(id.textView_iso);
    iso.setText("");
    shutter = (TextView) view.findViewById(id.textView_shutter);
    shutter.setText("");
    focal = (TextView) view.findViewById(id.textView_focal);
    focal.setText("");
    fnumber = (TextView) view.findViewById(id.textView_fnumber);
    fnumber.setText("");
    filename = (TextView) view.findViewById(id.textView_filename);

    play = (Button) view.findViewById(id.button_play);
    play.setVisibility(View.GONE);
    play.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (folder_to_show == null)
                return;
            if (!folder_to_show.getFile().getName().endsWith(FileEnding.RAW)
                    || !folder_to_show.getFile().getName().endsWith(FileEnding.BAYER)) {
                Uri uri = Uri.fromFile(folder_to_show.getFile());

                Intent i;
                if (folder_to_show.getFile().getName().endsWith(FileEnding.MP4)) {
                    i = new Intent(Intent.ACTION_VIEW);
                    i.setDataAndType(uri, "video/*");
                } else {
                    i = new Intent(Intent.ACTION_EDIT);
                    i.setDataAndType(uri, "image/*");
                }
                Intent chooser = Intent.createChooser(i, "Choose App");
                //startActivity(i);
                if (i.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivity(chooser);
                }

            }
        }
    });
    deleteButton = (Button) view.findViewById(id.button_delete);
    deleteButton.setVisibility(View.GONE);
    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP || VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP
                    && !activityInterface.getAppSettings().GetWriteExternal()) {
                Builder builder = new Builder(getContext());
                builder.setMessage("Delete File?").setPositiveButton("Yes", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();
            } else {
                DocumentFile sdDir = activityInterface.getExternalSdDocumentFile();
                if (sdDir == null) {

                    activityInterface.ChooseSDCard(ScreenSlideFragment.this);
                } else {
                    Builder builder = new Builder(getContext());
                    builder.setMessage("Delete File?").setPositiveButton("Yes", dialogClickListener)
                            .setNegativeButton("No", dialogClickListener).show();
                }
            }

        }
    });
    mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
    mPager.setAdapter(mPagerAdapter);
    mPager.setOffscreenPageLimit(2);
    mPager.addOnPageChangeListener(this);
    return view;
}

From source file:com.tt.jobtracker.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }//from w  ww .j  av a 2s .co m
    // Handle action buttons
    switch (item.getItemId()) {
    case R.id.action_logout:
        // create intent to perform web search for this planet
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
        // catch event that there's no activity to handle intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, R.string.app_name, Toast.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.layer.atlas.messenger.AtlasMessagesScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.uiHandler = new Handler();
    this.app = (MessengerApp) getApplication();

    setContentView(R.layout.atlas_screen_messages);

    boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false);
    String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI);
    if (convUri != null) {
        Uri uri = Uri.parse(convUri);//ww w  . ja v a  2 s.  co m
        conv = app.getLayerClient().getConversation(uri);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation
    }

    participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker);
    participantsPicker.init(new String[] { app.getLayerClient().getAuthenticatedUserId() },
            app.getParticipantProvider());
    if (convIsNew) {
        participantsPicker.setVisibility(View.VISIBLE);
    }

    messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer);
    messageComposer.init(app.getLayerClient(), conv);
    messageComposer.setListener(new AtlasMessageComposer.Listener() {
        public boolean beforeSend(Message message) {
            boolean conversationReady = ensureConversationReady();
            if (!conversationReady)
                return false;

            // push
            preparePushMetadata(message);
            return true;
        }

    });

    messageComposer.registerMenuItem("Photo", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg";
            photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName);
            final Uri outputUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            if (debug)
                Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri);
            startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
        }
    });

    messageComposer.registerMenuItem("Image", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            // in onCreate or any event where your want the user to select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY);
        }
    });

    messageComposer.registerMenuItem("Location", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            if (lastKnownLocation == null) {
                Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":"
                    + lastKnownLocation.getLongitude() + "}";
            MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION,
                    locationString.getBytes());
            Message message = app.getLayerClient().newMessage(Arrays.asList(part));

            preparePushMetadata(message);
            conv.send(message);

            if (debug)
                Log.w(TAG, "onSendLocation() loc:  " + locationString);
        }
    });

    messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list);
    messagesList.init(app.getLayerClient(), app.getParticipantProvider());
    if (USE_QUERY) {
        Query<Message> query = Query.builder(Message.class)
                .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv))
                .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING))
                .build();
        messagesList.setQuery(query);
    } else {
        messagesList.setConversation(conv);
    }

    messagesList.setItemClickListener(new ItemClickListener() {
        public void onItemClick(Cell cell) {
            if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) {
                String jsonLonLat = new String(cell.messagePart.getData());
                JSONObject json;
                try {
                    json = new JSONObject(jsonLonLat);
                    double lon = json.getDouble("lon");
                    double lat = json.getDouble("lat");
                    Intent openMapIntent = new Intent(Intent.ACTION_VIEW);
                    String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18,
                            lat, lon);
                    final Uri geoUri = Uri.parse(uriString);
                    openMapIntent.setData(geoUri);
                    if (openMapIntent.resolveActivity(getPackageManager()) != null) {
                        startActivity(openMapIntent);
                        if (debug)
                            Log.w(TAG, "onItemClick() starting Map: " + uriString);
                    } else {
                        if (debug)
                            Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri);
                    }
                } catch (JSONException ignored) {
                }
            } else if (cell instanceof ImageCell) {
                Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(),
                        AtlasImageViewScreen.class);
                app.setParam(intent, cell);
                startActivity(intent);
            }
        }
    });

    typingIndicator = (AtlasTypingIndicator) findViewById(R.id.atlas_screen_messages_typing_indicator);
    typingIndicator.init(conv,
            new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider()));

    // location manager for inserting locations:
    this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    prepareActionBar();
}

From source file:com.jimsuplee.scottishwhiskydistilleries.Scottishwhiskydistilleries.java

public void onClickMap(View view) {
    //WORKS, opens web browser:
    // Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/?q=57.351,-2.745"));
    //startActivity(browserIntent);
    Uri geo;/*from  ww w  . java  2 s.c om*/
    //NOT WORKING NOT FOUND IN GOOGLE MAPS APP
    // geo = Uri.parse("geo:57.351,-2.745(Distillery)");
    String location = mapMap.get(Scottishwhiskydistilleries.distilleryChoice);
    if (location != null) {
        Toast.makeText(this, "Loading  map for " + Scottishwhiskydistilleries.distilleryChoice,
                Toast.LENGTH_LONG).show();
        geo = Uri.parse(location);
    } else {
        Toast.makeText(this, "Exact location not found for " + Scottishwhiskydistilleries.distilleryChoice,
                Toast.LENGTH_LONG).show();
        geo = Uri.parse("geo:57.351,-2.745?z=8");
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(geo);
    if (intent.resolveActivity(getPackageManager()) != null) {
        Log.w(TAG, "In Scottishwhiskydistilleries.onClickMap(), about to start intent, not browserIntent");
        startActivity(intent);
    } else {
        Log.w(TAG, "In Scottishwhiskydistilleries.onClickMap(), about to start browserIntent, not intent");
        Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://maps.google.com/?q=57.351,-2.745"));
        startActivity(browserIntent);
    }
}

From source file:uno.weichen.abnd10_inventoryapp.DetailActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    // Find all relevant views that we will need to read user input from
    mNameEditText = (EditText) findViewById(R.id.edit_product_name);
    mPriceEditText = (EditText) findViewById(R.id.edit_product_price);
    mQuantityTextView = (TextView) findViewById(R.id.textview_product_quantity);
    mContactEditText = (EditText) findViewById(R.id.edit_product_contact);
    mSoldQuantityTextView = (TextView) findViewById(R.id.textview_product_sold_quantity);
    mRestockQuantityTextView = (TextView) findViewById(R.id.textview_product_restock_quantity);
    mSaleButton = (Button) findViewById(R.id.button_sale_product);
    mRestockButton = (Button) findViewById(R.id.button_restock_product);
    mDeleteButton = (Button) findViewById(R.id.button_delete_product);
    mOrderButton = (Button) findViewById(R.id.button_order);

    mProductPhotoImageView = (ImageView) findViewById(R.id.image);

    // Use getIntent and getData to get the associated URI
    mCurrentProductUri = getIntent().getData();
    //Set title of DetailActivity on which situation we have
    if (mCurrentProductUri == null) {
        setTitle(getString(R.string.editor_activity_title_new_product));
        invalidateOptionsMenu();//from w w w . j  a va 2 s .co  m
        mDeleteButton.setVisibility(View.GONE);
    } else {
        setTitle(getString(R.string.editor_activity_title_edit_product));
        /**
         * Initializes the CursorLoader. The URL_LOADER value is eventually passed
         * to onCreateLoader().
         */
        getSupportLoaderManager().initLoader(PRODUCTION_ITEM_LOADER, null, this);
    }

    // Setup onTouchListener for editors components.
    mNameEditText.setOnTouchListener(mTouchListener);
    mPriceEditText.setOnTouchListener(mTouchListener);
    mContactEditText.setOnTouchListener(mTouchListener);

    //Onclick Listener for Sale
    mSaleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String soldQuantityString = mSoldQuantityTextView.getText().toString().trim();
            String quantityString = mQuantityTextView.getText().toString().trim();
            int soldQuantityInt = Integer.parseInt(soldQuantityString);
            int quantityInt = Integer.parseInt(quantityString);
            if (quantityInt > 0) {
                //if button clicked and quantity > 0
                soldQuantityInt++;
                quantityInt--;
                soldQuantityString = Integer.toString(soldQuantityInt);
                quantityString = Integer.toString(quantityInt);
                mQuantityTextView.setText(quantityString);
                mSoldQuantityTextView.setText(soldQuantityString);
                //inform the user the product detail has been changed.
                mProductHasChanged = true;
            }
        }
    });

    //Onclick Listener for Restock
    mRestockButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String restockQuantityString = mRestockQuantityTextView.getText().toString().trim();
            String quantityString = mQuantityTextView.getText().toString().trim();
            int restockQuantityInt = Integer.parseInt(restockQuantityString);
            int quantityInt = Integer.parseInt(quantityString);
            //if button clicked
            restockQuantityInt++;
            quantityInt++;
            restockQuantityString = Integer.toString(restockQuantityInt);
            quantityString = Integer.toString(quantityInt);
            mQuantityTextView.setText(quantityString);
            mRestockQuantityTextView.setText(restockQuantityString);
            //inform the user the product detail has been changed.
            mProductHasChanged = true;
        }
    });

    //Onclick Listener for Delete
    mDeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDeleteConfirmationDialog();
        }
    });

    //Onclick Listener for Order
    mOrderButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String subject = "Restocking Request";
            String body = "Dear Supplier, \n" + "We need more " + mNameEditText.getText().toString().trim()
                    + ".\n" + "Please contact us! \n";

            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("mailto:")); // only email apps should handle this
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mContactEditText.getText().toString().trim() });
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
            intent.putExtra(Intent.EXTRA_TEXT, body);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    });

}

From source file:com.google.android.apps.muzei.settings.ChooseSourceFragment.java

private void redrawSources() {
    if (mSourceContainerView == null || !isAdded()) {
        return;/* www  . j ava 2 s . co  m*/
    }

    mSourceContainerView.removeAllViews();
    for (final Source source : mSources) {
        source.rootView = LayoutInflater.from(getContext()).inflate(R.layout.settings_choose_source_item,
                mSourceContainerView, false);

        source.selectSourceButton = source.rootView.findViewById(R.id.source_image);
        source.selectSourceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (source.componentName.equals(mSelectedSource)) {
                    if (getContext() instanceof Callbacks) {
                        ((Callbacks) getContext()).onRequestCloseActivity();
                    } else if (getParentFragment() instanceof Callbacks) {
                        ((Callbacks) getParentFragment()).onRequestCloseActivity();
                    }
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                        && source.targetSdkVersion >= Build.VERSION_CODES.O) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                            .setTitle(R.string.action_source_target_too_high_title)
                            .setMessage(R.string.action_source_target_too_high_message)
                            .setNegativeButton(R.string.action_source_target_too_high_learn_more,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                                    "https://medium.com/@ianhlake/the-muzei-plugin-api-and-androids-evolution-9b9979265cfb")));
                                        }
                                    })
                            .setPositiveButton(R.string.action_source_target_too_high_dismiss, null);
                    final Intent sendFeedbackIntent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://play.google.com/store/apps/details?id="
                                    + source.componentName.getPackageName()));
                    if (sendFeedbackIntent.resolveActivity(getContext().getPackageManager()) != null) {
                        builder.setNeutralButton(
                                getString(R.string.action_source_target_too_high_send_feedback, source.label),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        startActivity(sendFeedbackIntent);
                                    }
                                });
                    }
                    builder.show();
                } else if (source.setupActivity != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString(FirebaseAnalytics.Param.ITEM_ID,
                            source.componentName.flattenToShortString());
                    bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, source.label);
                    bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "sources");
                    FirebaseAnalytics.getInstance(getContext()).logEvent(FirebaseAnalytics.Event.VIEW_ITEM,
                            bundle);
                    mCurrentInitialSetupSource = source.componentName;
                    launchSourceSetup(source);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString(FirebaseAnalytics.Param.ITEM_ID,
                            source.componentName.flattenToShortString());
                    bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "sources");
                    FirebaseAnalytics.getInstance(getContext()).logEvent(FirebaseAnalytics.Event.SELECT_CONTENT,
                            bundle);
                    SourceManager.selectSource(getContext(), source.componentName);
                }
            }
        });

        source.selectSourceButton.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                final String pkg = source.componentName.getPackageName();
                if (TextUtils.equals(pkg, getContext().getPackageName())) {
                    // Don't open Muzei's app info
                    return false;
                }
                // Otherwise open third party extensions
                try {
                    startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                            Uri.fromParts("package", pkg, null)));
                } catch (final ActivityNotFoundException e) {
                    return false;
                }
                return true;
            }
        });

        float alpha = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                && source.targetSdkVersion >= Build.VERSION_CODES.O ? ALPHA_DISABLED : ALPHA_UNSELECTED;
        source.rootView.setAlpha(alpha);

        source.icon.setColorFilter(source.color, PorterDuff.Mode.SRC_ATOP);
        source.selectSourceButton.setBackground(source.icon);

        TextView titleView = source.rootView.findViewById(R.id.source_title);
        titleView.setText(source.label);
        titleView.setTextColor(source.color);

        updateSourceStatusUi(source);

        source.settingsButton = source.rootView.findViewById(R.id.source_settings_button);
        TooltipCompat.setTooltipText(source.settingsButton, source.settingsButton.getContentDescription());
        source.settingsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launchSourceSettings(source);
            }
        });

        animateSettingsButton(source.settingsButton, false, false);

        mSourceContainerView.addView(source.rootView);
    }

    updateSelectedItem(mCurrentSourceLiveData.getValue(), false);
}

From source file:com.owncloud.android.ui.activity.Preferences.java

private void launchDavDroidLogin()
        throws com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException,
        OperationCanceledException, AuthenticatorException, IOException {
    Account account = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());

    Intent davDroidLoginIntent = new Intent();
    davDroidLoginIntent.setClassName("at.bitfire.davdroid", "at.bitfire.davdroid.ui.setup.LoginActivity");
    if (getPackageManager().resolveActivity(davDroidLoginIntent, 0) != null) {
        // arguments
        if (mUri != null) {
            davDroidLoginIntent.putExtra("url", mUri.toString() + AccountUtils.DAV_PATH);
        }/*from  ww w .ja  v  a 2 s  . c  o m*/
        davDroidLoginIntent.putExtra("username", AccountUtils.getAccountUsername(account.name));
        //loginIntent.putExtra("password", "...");
        startActivityForResult(davDroidLoginIntent, ACTION_REQUEST_CODE_DAVDROID_SETUP);
    } else {
        // DAVdroid not installed
        Intent installIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("market://details?id=at.bitfire.davdroid"));

        // launch market(s)
        if (installIntent.resolveActivity(getPackageManager()) != null) {
            startActivity(installIntent);
        } else {
            // no f-droid market app or Play store installed --> launch browser for f-droid url
            Intent downloadIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://f-droid.org/repository/browse/?fdid=at.bitfire.davdroid"));
            startActivity(downloadIntent);

            Toast.makeText(MainApp.getAppContext(), R.string.prefs_calendar_contacts_no_store_error,
                    Toast.LENGTH_SHORT).show();
        }
    }
}