Java Code Examples for androidx.fragment.app.FragmentActivity

The following examples show how to use androidx.fragment.app.FragmentActivity. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: PixImagePicker   Source File: PermUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void checkForCamaraWritePermissions(final FragmentActivity activity, WorkFinish workFinish) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        workFinish.onWorkFinish(true);
    } else {
        List<String> permissionsNeeded = new ArrayList<String>();
        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.CAMERA, activity))
            permissionsNeeded.add("CAMERA");
        if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE, activity))
            permissionsNeeded.add("WRITE_EXTERNAL_STORAGE");
        if (permissionsList.size() > 0) {
            activity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
        } else {
            workFinish.onWorkFinish(true);
        }
    }
}
 
Example 2
public static void startVoiceCall(@NonNull FragmentActivity activity, @NonNull Recipient recipient) {
  if (TelephonyUtil.isAnyPstnLineBusy(activity)) {
    Toast.makeText(activity,
                   R.string.CommunicationActions_a_cellular_call_is_already_in_progress,
                   Toast.LENGTH_SHORT)
         .show();
    return;
  }

  WebRtcCallService.isCallActive(activity, new ResultReceiver(new Handler(Looper.getMainLooper())) {
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
      if (resultCode == 1) {
        startCallInternal(activity, recipient, false);
      } else {
        new AlertDialog.Builder(activity)
                       .setMessage(R.string.CommunicationActions_start_voice_call)
                       .setPositiveButton(R.string.CommunicationActions_call, (d, w) -> startCallInternal(activity, recipient, false))
                       .setNegativeButton(R.string.CommunicationActions_cancel, (d, w) -> d.dismiss())
                       .setCancelable(true)
                       .show();
      }
    }
  });
}
 
Example 3
Source Project: Android-Goldfinger   Source File: ValidateUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return list of prompt params errors. If no errors detected, list will be empty.
 */
@NonNull
static List<String> validatePromptParams(@NonNull Mode mode, @NonNull Goldfinger.PromptParams params) {
    List<String> errors = new ArrayList<>();

    if (!(params.dialogOwner() instanceof Fragment) && !(params.dialogOwner() instanceof FragmentActivity)) {
        errors.add("DialogOwner must be of instance Fragment or FragmentActivity");
    }

    if (StringUtils.isBlankOrNull(params.title())) {
        errors.add("Title is required!");
    }

    if (!params.deviceCredentialsAllowed() && StringUtils.isBlankOrNull(params.negativeButtonText())) {
        errors.add("NegativeButtonText is required!");
    }

    if (params.deviceCredentialsAllowed() && mode != Mode.AUTHENTICATION) {
        errors.add("DeviceCredentials are allowed only for Goldfinger#authenticate method.");
    }

    return errors;
}
 
Example 4
Source Project: libcommon   Source File: SAFUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * requestCodeに対応するUriへのアクセス要求を行う
 * @param activity
 * @param requestCode
 * @return 既にrequestCodeに対応するUriが存在していればそれを返す, 存在していなければパーミッション要求をしてnullを返す
 * @throws UnsupportedOperationException
 */
@Nullable
public static Uri requestPermission(
	@NonNull final FragmentActivity activity,
	final int requestCode) {

	if (BuildCheck.isLollipop()) {
		final Uri uri = getStorageUri(activity, requestCode);
		if (uri == null) {
			// requestCodeに対応するUriへのパーミッションを保持していない時は要求してnullを返す
			activity.startActivityForResult(prepareStorageAccessPermission(), requestCode);
		}
		return uri;
	} else {
		throw new UnsupportedOperationException("should be API>=21");
	}
}
 
Example 5
public static void addFragment(FragmentActivity fragmentActivity, Fragment fragmentToAdd,
                               String fragmentTag) {
    FragmentManager supportFragmentManager = fragmentActivity.getSupportFragmentManager();

    FragmentTransaction fragmentTransaction = supportFragmentManager
            .beginTransaction();
    fragmentTransaction.replace(R.id.layout_child_activity, fragmentToAdd,
            fragmentTag);

    if (supportFragmentManager.getBackStackEntryCount() > 1) {
        supportFragmentManager.popBackStack();
    }
    fragmentTransaction.addToBackStack(fragmentTag);
    fragmentTransaction.commitAllowingStateLoss();
    supportFragmentManager.executePendingTransactions();
}
 
Example 6
Source Project: CrazyDaily   Source File: WXTabPagerComponent.java    License: Apache License 2.0 6 votes vote down vote up
@WXComponentProp(name = "titledata")
public void setData(List<String> datas) {

    if (mTabPagerAdapter == null) {
        final Context context = getContext();
        if (!(context instanceof FragmentActivity)) {
            LoggerUtil.d("context不是FragmentActivity");
            return;
        }
        final FragmentActivity activity = (FragmentActivity) context;
        mTabPagerAdapter = new TabPagerAdapter(activity.getSupportFragmentManager(), datas);
        mViewPager.setAdapter(mTabPagerAdapter);
        return;
    }
    mTabPagerAdapter.reload(datas);
}
 
Example 7
Source Project: Bluefruit_LE_Connect_Android_V2   Source File: DialogUtils.java    License: MIT License 5 votes vote down vote up
public static boolean hasOpenedDialogs(@NonNull FragmentActivity activity) {
    List<Fragment> fragments = activity.getSupportFragmentManager().getFragments();
    if (fragments != null) {
        for (Fragment fragment : fragments) {
            if (fragment instanceof DialogFragment) {
                return true;
            }
        }
    }

    return false;
}
 
Example 8
/**
 * Updates the status on the action bar.
 *
 * @param resId a string resource ID
 */
private void setStatus(int resId) {
    FragmentActivity activity = getActivity();
    if (null == activity) {
        return;
    }
    final ActionBar actionBar = activity.getActionBar();
    if (null == actionBar) {
        return;
    }
    actionBar.setSubtitle(resId);
}
 
Example 9
Source Project: intra42   Source File: HomeEventsFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onItemClick(Events item) {
    BottomSheetEventDialogFragment bottomSheetDialogFragment = BottomSheetEventDialogFragment.newInstance(item);
    FragmentActivity activity = getActivity();
    if (activity != null)
        bottomSheetDialogFragment.show(activity.getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
 
Example 10
Source Project: browser-switch-android   Source File: ChromeCustomTabsTest.java    License: MIT License 5 votes vote down vote up
@Test
@SdkSuppress(maxSdkVersion = 23)
public void isAvailable_whenCustomTabsAreNotSupported_returnsFalse() {
    scenario.onFragment(fragment -> {
        FragmentActivity activity = fragment.getActivity();
        assertFalse(ChromeCustomTabs.isAvailable(activity.getApplication()));
    });
}
 
Example 11
Source Project: RuntimePermission   Source File: RuntimePermission.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ask for the permission. Which permission? Anything you register on your manifest that needs it.
 * It is safe to call this every time without querying `shouldAsk`.
 * In case you call `ask` without any permission, the method returns.
 */
public void ask() {
    final FragmentActivity activity = activityReference.get();
    if (activity == null || activity.isFinishing()) {
        return;
    }

    //retrieve permissions we want
    final List<String> permissions = findNeededPermissions(activity);

    // No need to ask for permissions on API levels below Android Marshmallow
    if (permissions.isEmpty() || Build.VERSION.SDK_INT < Build.VERSION_CODES.M || arePermissionsAlreadyAccepted(activity, permissions)) {
        onAllAccepted(permissions);
    } else {
        final PermissionFragment oldFragment = (PermissionFragment) activity
                .getSupportFragmentManager()
                .findFragmentByTag(TAG);

        if (oldFragment != null) {
            oldFragment.setListener(listener);
        } else {
            final PermissionFragment newFragment = PermissionFragment.newInstance(permissions);
            newFragment.setListener(listener);

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    activity.getSupportFragmentManager()
                            .beginTransaction()
                            .add(newFragment, TAG)
                            .commitAllowingStateLoss();
                    // change to .commitNowAllowingStateLoss() to see the crash
                }
            });

        }
    }
}
 
Example 12
Source Project: CrazyDaily   Source File: CrazyDailyAlertDialog.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
    Window window = getDialog().getWindow();
    FragmentActivity activity = getActivity();
    if (window != null && activity != null) {
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.8f);
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }
}
 
Example 13
Source Project: Spyglass   Source File: SpyglassRobolectricRunner.java    License: Apache License 2.0 5 votes vote down vote up
public static void startFragment(Fragment fragment, FragmentActivity activity, String tag) {
    FragmentManager fragmentManager = activity.getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(fragment, tag);
    fragmentTransaction.commit();
    fragmentManager.executePendingTransactions();
    activity.invalidateOptionsMenu();
}
 
Example 14
Source Project: Passbook   Source File: BiometricAuthHelper.java    License: Apache License 2.0 5 votes vote down vote up
public BiometricAuthHelper(boolean isFirstTime, BiometricListener listener, FragmentActivity context) {
    Executor executor = ContextCompat.getMainExecutor(context);
    mBiometricPrompt = new BiometricPrompt(context, executor, this);
    this.mIsFirstTime = isFirstTime;
    mTitle = context.getString(R.string.fp_title);
    initCipher(mIsFirstTime ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE);
    if (mIsFirstTime) {
        mDesc = context.getString(R.string.fp_ask);
        mNegativeButtonText = context.getString(android.R.string.cancel);
    } else {
        mDesc = context.getString(R.string.fp_desc);
        mNegativeButtonText = context.getString(R.string.fp_use_pwd);
    }
    this.mListener = listener;
}
 
Example 15
private static void startAudioCallInternal(@NonNull FragmentActivity activity, @NonNull Recipient recipient) {
  Permissions.with(activity)
             .request(Manifest.permission.RECORD_AUDIO)
             .ifNecessary()
             .withRationaleDialog(activity.getString(R.string.ConversationActivity__to_call_s_signal_needs_access_to_your_microphone, recipient.getDisplayName(activity)),
                 R.drawable.ic_mic_solid_24)
             .withPermanentDenialDialog(activity.getString(R.string.ConversationActivity__to_call_s_signal_needs_access_to_your_microphone, recipient.getDisplayName(activity)))
             .onAllGranted(() -> {
               Intent intent = new Intent(activity, WebRtcCallService.class);
               intent.setAction(WebRtcCallService.ACTION_OUTGOING_CALL)
                     .putExtra(WebRtcCallService.EXTRA_REMOTE_PEER, new RemotePeer(recipient.getId()))
                     .putExtra(WebRtcCallService.EXTRA_OFFER_TYPE, OfferMessage.Type.AUDIO_CALL.getCode());
               activity.startService(intent);

               MessageSender.onMessageSent();

               if (FeatureFlags.profileForCalling() && recipient.resolve().getProfileKey() == null) {
                 CalleeMustAcceptMessageRequestDialogFragment.create(recipient.getId())
                                                             .show(activity.getSupportFragmentManager(), null);
               } else {
                 Intent activityIntent = new Intent(activity, WebRtcCallActivity.class);

                 activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                 activity.startActivity(activityIntent);
               }
             })
             .execute();
}
 
Example 16
@Override
public void onResume() {
    super.onResume();

    FragmentActivity activity = getActivity();
    if (activity != null) {
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    }
}
 
Example 17
Source Project: EhViewer   Source File: SceneFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.setTag(R.id.fragment_tag, getTag());
    view.setBackgroundDrawable(AttrResources.getAttrDrawable(getContext(), android.R.attr.windowBackground));

    // Notify
    FragmentActivity activity = getActivity();
    if (activity instanceof StageActivity) {
        ((StageActivity) activity).onSceneViewCreated(this, savedInstanceState);
    }
}
 
Example 18
Source Project: EhViewer   Source File: BaseScene.java    License: Apache License 2.0 5 votes vote down vote up
public int getDrawerLockMode(int edgeGravity) {
    FragmentActivity activity = getActivity();
    if (activity instanceof MainActivity) {
        return ((MainActivity) activity).getDrawerLockMode(edgeGravity);
    } else {
        return DrawerLayout.LOCK_MODE_UNLOCKED;
    }
}
 
Example 19
Source Project: EasyPhotos   Source File: EasyPhotos.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 提供外部预览图片(网络图片请开启网络权限)
 *
 * @param act           上下文
 * @param imageEngine   图片加载引擎
 * @param paths         图片路径集合
 * @param bottomPreview 是否显示底部预览效果
 */
public static void startPreviewPaths(FragmentActivity act, @NonNull ImageEngine imageEngine, @NonNull ArrayList<String> paths, boolean bottomPreview) {
    Setting.imageEngine = imageEngine;
    ArrayList<Photo> photos = new ArrayList<>();
    for (String path : paths) {
        Photo photo = new Photo(null, path, 0, 0, 0, 0, 0, "");
        photos.add(photo);
    }
    PreviewActivity.start(act, photos, bottomPreview);
}
 
Example 20
Source Project: cathode   Source File: UpcomingAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public UpcomingAdapter(FragmentActivity activity, Callbacks callbacks) {
  super(activity);
  this.activity = activity;
  this.callbacks = callbacks;

  setHasStableIds(true);
}
 
Example 21
Source Project: particle-android   Source File: ConnectToApFragment.java    License: Apache License 2.0 5 votes vote down vote up
public static ConnectToApFragment ensureAttached(FragmentActivity activity) {
    ConnectToApFragment frag = get(activity);
    if (frag == null) {
        frag = new ConnectToApFragment();
        WorkerFragment.addFragment(activity, frag, TAG);
    }
    return frag;
}
 
Example 22
Source Project: mimi-reader   Source File: RepliesListAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public RepliesListAdapter(final FragmentActivity activity, final String boardName, final List<ChanPost> replies, final List<OutsideLink> links, final ChanThread thread) {
    this.activity = activity;
    this.boardName = boardName;
    this.replies = replies;
    this.links = (links == null) ? new ArrayList<OutsideLink>() : links;
    this.thread = thread;
    this.inflater = LayoutInflater.from(activity);

    this.thumbUrlMap = new HashMap<>();

    this.flagUrl = MimiUtil.https() + activity.getString(R.string.flag_int_link);
    this.trollUrl = MimiUtil.https() + activity.getString(R.string.flag_pol_link);

    setupReplies();
}
 
Example 23
Source Project: YImagePicker   Source File: ImagePicker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 提供媒体相册列表
 *
 * @param activity    调用activity
 * @param mimeTypeSet 指定相册文件类型
 * @param provider    相回调
 */
public static void provideMediaSets(FragmentActivity activity,
                                    Set<MimeType> mimeTypeSet,
                                    MediaSetsDataSource.MediaSetProvider provider) {
    if (PPermissionUtils.hasStoragePermissions(activity)) {
        MediaSetsDataSource.create(activity).setMimeTypeSet(mimeTypeSet).loadMediaSets(provider);
    }
}
 
Example 24
Source Project: android_9.0.0_r45   Source File: ProcessOwnerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNavigationToNonSupport() throws Throwable {
    FragmentActivity firstActivity = setupObserverOnResume();
    Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
            NonSupportActivity.class.getCanonicalName(), null, false);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.addMonitor(monitor);

    Intent intent = new Intent(firstActivity, NonSupportActivity.class);
    firstActivity.finish();
    firstActivity.startActivity(intent);
    NonSupportActivity secondActivity = (NonSupportActivity) monitor.waitForActivity();
    assertThat("Failed to navigate", secondActivity, notNullValue());
    checkProcessObserverSilent(secondActivity);
}
 
Example 25
Source Project: android_9.0.0_r45   Source File: ProcessOwnerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRecreation() throws Throwable {
    FragmentActivity activity = setupObserverOnResume();
    FragmentActivity recreated = TestUtils.recreateActivity(activity, activityTestRule);
    assertThat("Failed to recreate", recreated, notNullValue());
    checkProcessObserverSilent(recreated);
}
 
Example 26
Source Project: android_9.0.0_r45   Source File: ProcessOwnerTest.java    License: Apache License 2.0 5 votes vote down vote up
private FragmentActivity setupObserverOnResume() throws Throwable {
    FragmentActivity firstActivity = activityTestRule.getActivity();
    waitTillResumed(firstActivity, activityTestRule);
    addProcessObserver(mObserver);
    mObserver.mChangedState = false;
    return firstActivity;
}
 
Example 27
public void scanQrCodeClick() {
    FragmentActivity activity = getActivity();
    if (activity != null) {
        Intent intent = new Intent(activity, ScanQrCodeScreen.class);
        startActivityForResult(intent, Constants.SCAN_QR_CODE_RESULT);
    }
}
 
Example 28
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    FragmentActivity activity = getActivity();
    if (activity != null) {
        String qrCode = qrCodeHelper.parseActivityResult(activity, requestCode, resultCode, data);

        if (!qrCode.isEmpty()){
            addressView.setText(qrCode);
            createChatPresenter.onClickCreateNewChat(qrCode);
            dismiss();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 29
Source Project: android_9.0.0_r45   Source File: ViewModelProviders.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
 * is alive. More detailed explanation is in {@link ViewModel}.
 * <p>
 * It uses the given {@link Factory} to instantiate new ViewModels.
 *
 * @param activity an activity, in whose scope ViewModels should be retained
 * @param factory  a {@code Factory} to instantiate new ViewModels
 * @return a ViewModelProvider instance
 */
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
        @Nullable Factory factory) {
    Application application = checkApplication(activity);
    if (factory == null) {
        factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
    }
    return new ViewModelProvider(activity.getViewModelStore(), factory);
}
 
Example 30
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    FragmentActivity activity = getActivity();
    if (!(activity instanceof EmailLinkPromptEmailListener)) {
        throw new IllegalStateException("Activity must implement EmailLinkPromptEmailListener");
    }
    mListener = (EmailLinkPromptEmailListener) activity;

    initHandler();
}