下面列出了android.view.inputmethod.CorrectionInfo#org.chromium.base.Log 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @see BaseInputConnection#performContextMenuAction(int)
*/
boolean performContextMenuAction(int id) {
if (DEBUG_LOGS) Log.i(TAG, "performContextMenuAction: id [%d]", id);
switch (id) {
case android.R.id.selectAll:
mWebContents.selectAll();
return true;
case android.R.id.cut:
mWebContents.cut();
return true;
case android.R.id.copy:
mWebContents.copy();
return true;
case android.R.id.paste:
mWebContents.paste();
return true;
default:
return false;
}
}
@VisibleForTesting
@SuppressFBWarnings("DM_EXIT")
void launchBrowserIfNecessary(Context context) {
if (BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER)
.isStartupSuccessfullyCompleted()) {
return;
}
// TODO(https://crbug.com/717251): Remove when BackgroundTaskScheduler supports loading the
// native library.
try {
ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup();
} catch (ProcessInitException e) {
Log.e(TAG, "ProcessInitException while starting the browser process.");
// Since the library failed to initialize nothing in the application can work, so kill
// the whole application not just the activity.
System.exit(-1);
}
}
private void showMediaRouteDialog(MediaStateListener player, MediaRouteController controller,
Activity activity) {
FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
if (fm == null) {
throw new IllegalStateException("The activity must be a subclass of FragmentActivity");
}
MediaRouteDialogFactory factory = new MediaRouteChooserDialogFactory(player, controller,
activity);
if (fm.findFragmentByTag(
"android.support.v7.mediarouter:MediaRouteChooserDialogFragment") != null) {
Log.w(TAG, "showDialog(): Route chooser dialog already showing!");
return;
}
MediaRouteChooserDialogFragment f = factory.onCreateChooserDialogFragment();
f.setRouteSelector(controller.buildMediaRouteSelector());
f.show(fm, "android.support.v7.mediarouter:MediaRouteChooserDialogFragment");
}
/**
* Starts the sign-in flow, and executes the callback when finished.
*
* If an activity is provided, it is considered an "interactive" sign-in and the user can be
* prompted to confirm various aspects of sign-in using dialogs inside the activity.
* The sign-in flow goes through the following steps:
*
* - Wait for AccountTrackerService to be seeded.
* - If interactive, confirm the account change with the user.
* - Wait for policy to be checked for the account.
* - If interactive and the account is managed, warn the user.
* - If managed, wait for the policy to be fetched.
* - Complete sign-in with the native SigninManager and kick off token requests.
* - Call the callback if provided.
*
* @param account The account to sign in to.
* @param activity The activity used to launch UI prompts, or null for a forced signin.
* @param callback Optional callback for when the sign-in process is finished.
*/
public void signIn(
Account account, @Nullable Activity activity, @Nullable SignInCallback callback) {
if (account == null) {
Log.w(TAG, "Ignoring sign-in request due to null account.");
if (callback != null) callback.onSignInAborted();
return;
}
if (mSignInState != null) {
Log.w(TAG, "Ignoring sign-in request as another sign-in request is pending.");
if (callback != null) callback.onSignInAborted();
return;
}
if (mFirstRunCheckIsPending) {
Log.w(TAG, "Ignoring sign-in request until the First Run check completes.");
if (callback != null) callback.onSignInAborted();
return;
}
mSignInState = new SignInState(account, activity, callback);
notifySignInAllowedChanged();
progressSignInFlowSeedSystemAccounts();
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
switch (requestCode) {
case REQUEST_ID:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
PhysicalWebUma.onPrefsLocationGranted(getActivity());
Log.d(TAG, "Location permission granted");
PhysicalWeb.startPhysicalWeb(
(ChromeApplication) getActivity().getApplicationContext());
} else {
PhysicalWebUma.onPrefsLocationDenied(getActivity());
Log.d(TAG, "Location permission denied");
}
break;
default:
}
}
@Override
public void onConnected(Bundle connectionHint) {
if (mState != STATE_CONNECTING_TO_API && mState != STATE_API_CONNECTION_SUSPENDED) {
throwInvalidState();
}
// TODO(avayvod): switch to using ConnectedTask class for GoogleApiClient operations.
// See https://crbug.com/522478
if (mState == STATE_API_CONNECTION_SUSPENDED) return;
try {
launchApplication(mApiClient, mSource.getApplicationId(), true)
.setResultCallback(this);
mState = STATE_LAUNCHING_APPLICATION;
} catch (Exception e) {
Log.e(TAG, "Launch application failed: %s", mSource.getApplicationId(), e);
reportError();
}
}
/**
* Starts the current task by calling the appropriate method on the
* {@link ConnectivityChecker}.
* The result will be put in {@link #mResult} when it comes back from the network stack.
*/
public void start(Profile profile, int timeoutMs) {
Log.v(TAG, "Starting task for " + mType);
switch (mType) {
case CHROME_HTTP:
ConnectivityChecker.checkConnectivityChromeNetworkStack(
profile, false, timeoutMs, this);
break;
case CHROME_HTTPS:
ConnectivityChecker.checkConnectivityChromeNetworkStack(
profile, true, timeoutMs, this);
break;
case SYSTEM_HTTP:
ConnectivityChecker.checkConnectivitySystemNetworkStack(false, timeoutMs, this);
break;
case SYSTEM_HTTPS:
ConnectivityChecker.checkConnectivitySystemNetworkStack(true, timeoutMs, this);
break;
default:
Log.e(TAG, "Failed to recognize type " + mType);
}
}
@Override
public void onCharacteristicWrite(
final Wrappers.BluetoothGattCharacteristicWrapper characteristic,
final int status) {
Wrappers.ThreadUtilsWrapper.getInstance().runOnUiThread(new Runnable() {
@Override
public void run() {
ChromeBluetoothRemoteGattCharacteristic chromeCharacteristic =
mWrapperToChromeCharacteristicsMap.get(characteristic);
if (chromeCharacteristic == null) {
// Android events arriving with no Chrome object is expected rarely: only
// when the event races object destruction.
Log.v(TAG, "onCharacteristicWrite when chromeCharacteristic == null.");
} else {
RecordHistogram.recordSparseSlowlyHistogram(
"Bluetooth.Web.Android.onCharacteristicWrite.Status", status);
chromeCharacteristic.onCharacteristicWrite(status);
}
}
});
}
@Override
public void onSnippetsReceived(List<SnippetArticle> listSnippets) {
if (!mWantsSnippets) return;
int newSnippetCount = listSnippets.size();
Log.d(TAG, "Received %d new snippets.", newSnippetCount);
// At first, there might be no snippets available, we wait until they have been fetched.
if (newSnippetCount == 0) return;
loadSnippets(listSnippets);
// We don't want to get notified of other changes.
mWantsSnippets = false;
NewTabPageUma.recordSnippetAction(NewTabPageUma.SNIPPETS_ACTION_SHOWN);
}
/**
* Checks whether the package being targeted is a valid WebAPK and whether the url supplied
* can be fulfilled by that WebAPK.
*
* @param webApkPackage The package name of the requested WebAPK.
* @param url The url to navigate to.
* @return true iff all validation criteria are met.
*/
private boolean isValidWebApk(String webApkPackage, String url) {
if (!CommandLine.getInstance().hasSwitch(ChromeSwitches.ENABLE_WEBAPK)
|| webApkPackage == null) {
return false;
}
if (!WebApkValidator.isValidWebApk(this, webApkPackage)) {
Log.d(TAG, "%s is not valid WebAPK", webApkPackage);
return false;
}
if (!webApkPackage.equals(WebApkValidator.queryWebApkPackage(this, url))) {
Log.d(TAG, "%s is not within scope of %s WebAPK", url, webApkPackage);
return false;
}
return true;
}
@Override
public void onNewSuggestions(@CategoryInt int category) {
@CategoryStatusEnum
int status = mNewTabPageManager.getSuggestionsSource().getCategoryStatus(category);
if (!canLoadSuggestions(category, status)) return;
// We never want to refresh the suggestions if we already have some content.
if (mSections.get(category).hasSuggestions()) return;
List<SnippetArticle> suggestions =
mNewTabPageManager.getSuggestionsSource().getSuggestionsForCategory(category);
Log.d(TAG, "Received %d new suggestions for category %d.", suggestions.size(), category);
// At first, there might be no suggestions available, we wait until they have been fetched.
if (suggestions.isEmpty()) return;
setSuggestions(category, suggestions, status);
}
/**
* Requests an authentication token. If the account is not properly setup, it will result in
* a failure.
*
* @param ctx The application context
* @param requestData The object holding the data related to the current request
* @param features An array of the account features to require, may be null or empty
*/
private void requestTokenWithoutActivity(
Context ctx, RequestData requestData, String[] features) {
if (lacksPermission(ctx, Manifest.permission.GET_ACCOUNTS, true /* onlyPreM */)) {
// Protecting the AccountManager#getAccountsByTypeAndFeatures call.
// API < 23 Requires the GET_ACCOUNTS permission or throws an exception.
// API >= 23 Requires the GET_ACCOUNTS permission (CONTACTS permission group) or
// returns only the accounts whose authenticator has a signature that
// matches our app. Working with this restriction and not requesting
// the permission is a valid use case in the context of WebView, so we
// don't require it on M+
Log.e(TAG, "ERR_MISCONFIGURED_AUTH_ENVIRONMENT: GET_ACCOUNTS permission not "
+ "granted. Aborting authentication.");
nativeSetResult(requestData.nativeResultObject,
NetError.ERR_MISCONFIGURED_AUTH_ENVIRONMENT, null);
return;
}
requestData.accountManager.getAccountsByTypeAndFeatures(mAccountType, features,
new GetAccountsCallback(requestData), new Handler(ThreadUtils.getUiThreadLooper()));
}
/**
* @return Which flavor of Herb is being tested. See {@link ChromeSwitches#HERB_FLAVOR_ANISE}
* and its related switches.
*/
public static String getHerbFlavor() {
Context context = ContextUtils.getApplicationContext();
if (isHerbDisallowed(context)) return ChromeSwitches.HERB_FLAVOR_DISABLED;
if (!sIsHerbFlavorCached) {
sCachedHerbFlavor = null;
// Allowing disk access for preferences while prototyping.
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
sCachedHerbFlavor =
ChromePreferenceManager.getInstance(context).getCachedHerbFlavor();
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
sIsHerbFlavorCached = true;
Log.d(TAG, "Retrieved cached Herb flavor: " + sCachedHerbFlavor);
}
return sCachedHerbFlavor;
}
@Override
public void onResult(Cast.ApplicationConnectionResult result) {
if (mState != STATE_LAUNCHING_APPLICATION
&& mState != STATE_API_CONNECTION_SUSPENDED) {
throwInvalidState();
}
Status status = result.getStatus();
if (!status.isSuccess()) {
Log.e(TAG, "Launch application failed with status: %s, %d, %s",
mSource.getApplicationId(), status.getStatusCode(), status.getStatusMessage());
reportError();
}
mState = STATE_LAUNCH_SUCCEEDED;
reportSuccess(result);
}
/**
* Generate a new token for the intent that has user gesture. This will
* invalidate the token on the previously launched intent with user gesture.
*
* @param intent Intent with user gesture.
*/
public void onNewIntentWithGesture(Intent intent) {
if (mSecureRandomInitializer != null) {
try {
mSecureRandom = mSecureRandomInitializer.get();
} catch (InterruptedException | ExecutionException e) {
Log.e(TAG, "Error fetching SecureRandom", e);
}
mSecureRandomInitializer = null;
}
if (mSecureRandom == null) return;
mIntentToken = new byte[32];
mSecureRandom.nextBytes(mIntentToken);
intent.putExtra(EXTRA_USER_GESTURE_TOKEN, mIntentToken);
mUri = IntentHandler.getUrlFromIntent(intent);
}
/**
* Check the external storage and notify user on error.
*
* @param fullDirPath The dir path to download a file. Normally this is external storage.
* @param externalStorageStatus The status of the external storage.
* @return Whether external storage is ok for downloading.
*/
private boolean checkExternalStorageAndNotify(
String filename, String fullDirPath, String externalStorageStatus) {
if (fullDirPath == null) {
Log.e(TAG, "Download failed: no SD card");
alertDownloadFailure(
filename, DownloadManager.ERROR_DEVICE_NOT_FOUND);
return false;
}
if (!externalStorageStatus.equals(Environment.MEDIA_MOUNTED)) {
int reason = DownloadManager.ERROR_DEVICE_NOT_FOUND;
// Check to see if the SDCard is busy, same as the music app
if (externalStorageStatus.equals(Environment.MEDIA_SHARED)) {
Log.e(TAG, "Download failed: SD card unavailable");
reason = DownloadManager.ERROR_FILE_ERROR;
} else {
Log.e(TAG, "Download failed: no SD card");
}
alertDownloadFailure(filename, reason);
return false;
}
return true;
}
/**
* Atomically writes the given serialized data out to disk.
* @param stateDirectory Directory to save TabModel data into.
* @param selectorIndex Index of the TabModelSelector to write out.
* @param listData TabModel data in the form of a serialized byte array.
*/
public static void saveListToFile(File stateDirectory, int selectorIndex, byte[] listData) {
synchronized (SAVE_LIST_LOCK) {
// Save the index file containing the list of tabs to restore.
File metadataFile = new File(stateDirectory, getStateFileName(selectorIndex));
AtomicFile file = new AtomicFile(metadataFile);
FileOutputStream stream = null;
try {
stream = file.startWrite();
stream.write(listData, 0, listData.length);
file.finishWrite(stream);
} catch (IOException e) {
if (stream != null) file.failWrite(stream);
Log.e(TAG, "Failed to write file: " + metadataFile.getAbsolutePath());
}
}
}
@VisibleForTesting
void showNotificationImmediately(MediaNotificationInfo mediaNotificationInfo) {
// If no notification hasn't been updated in the last THROTTLE_MILLIS, update
// immediately and queue a task for blocking further updates.
mManager.showNotification(mediaNotificationInfo);
mTask = new Runnable() {
@Override
public void run() {
if (mLastPendingInfo != null) {
// If any notification info is pended during the throttling time window,
// update the notification.
showNotificationImmediately(mLastPendingInfo);
mLastPendingInfo = null;
} else {
// Otherwise, clear the task so further update is unthrottled.
mTask = null;
}
}
};
if (!mHandler.postDelayed(mTask, THROTTLE_MILLIS)) {
Log.w(TAG, "Failed to post the throttler task.");
mTask = null;
}
}
private void handleFindAndUploadLastCrash(Intent intent) {
CrashFileManager fileManager = new CrashFileManager(getApplicationContext().getCacheDir());
File[] minidumpFiles = fileManager.getAllMinidumpFiles(MAX_TRIES_ALLOWED);
if (minidumpFiles.length == 0) {
// Try again later. Maybe the minidump hasn't finished being written.
Log.d(TAG, "Could not find any crash dumps to upload");
return;
}
File minidumpFile = minidumpFiles[0];
File logfile = fileManager.getCrashUploadLogFile();
Intent uploadIntent = createUploadIntent(getApplicationContext(), minidumpFile, logfile);
// We should have at least one chance to secure logcat to the minidump now.
uploadIntent.putExtra(FINISHED_LOGCAT_EXTRACTION_KEY, true);
startService(uploadIntent);
}
/**
* Calculates the height of the bottom spacing item, such that there is always enough content
* below the fold to push the header up to to the top of the screen.
*/
int calculateBottomSpacing() {
int firstVisiblePos = mLayoutManager.findFirstVisibleItemPosition();
// We have enough items to fill the view, since the snap point item is not even visible.
if (firstVisiblePos > ARTICLES_HEADER_ITEM_POSITION) return MIN_BOTTOM_SPACING;
// The spacing item is the last item, the last content item is directly above that.
int lastContentItemPosition = getAdapter().getItemCount() - 2;
ViewHolder lastContentItem = findViewHolderForAdapterPosition(lastContentItemPosition);
ViewHolder snapItem = findViewHolderForAdapterPosition(ARTICLES_HEADER_ITEM_POSITION);
int bottomSpacing = getHeight() - mToolbarHeight;
if (lastContentItem == null || snapItem == null) {
// This can happen in several cases, where some elements are not visible and the
// RecyclerView didn't already attach them. We handle it by just adding space to make
// sure that we never run out and force the UI to jump around and get stuck in a
// position that breaks the animations. The height will be properly adjusted at the
// next pass. Known cases that make it necessary:
// - The card list is refreshed while the NTP is not shown, for example when changing
// the sync settings.
// - Dismissing a snippet and having the status card coming to take its place.
// - Refresh while being below the fold, for example by tapping the status card.
if (snapItem != null) bottomSpacing -= snapItem.itemView.getTop();
Log.w(TAG, "The RecyclerView items are not attached, can't determine the content "
+ "height: snap=%s, last=%s. Using full height: %d ",
snapItem, lastContentItem, bottomSpacing);
} else {
int contentHeight = lastContentItem.itemView.getBottom() - snapItem.itemView.getTop();
bottomSpacing -= contentHeight - mCompensationHeight;
}
return Math.max(MIN_BOTTOM_SPACING, bottomSpacing);
}
@CalledByNative
private int queueInputBuffer(
int index, int offset, int size, long presentationTimeUs, int flags) {
resetLastPresentationTimeIfNeeded(presentationTimeUs);
try {
mMediaCodec.queueInputBuffer(index, offset, size, presentationTimeUs, flags);
} catch (Exception e) {
Log.e(TAG, "Failed to queue input buffer", e);
return MediaCodecStatus.ERROR;
}
return MediaCodecStatus.OK;
}
/**
* Just like {@link Bundle#getInt(String, int)} but doesn't throw exceptions.
*/
public static int safeGetInt(Bundle bundle, String name, int defaultValue) {
try {
return bundle.getInt(name, defaultValue);
} catch (Throwable t) {
// Catches un-parceling exceptions.
Log.e(TAG, "getInt failed on bundle " + bundle);
return defaultValue;
}
}
/**
* Handles messages related to the cast session, i.e. messages happening on a established
* connection. All these messages are sent from the page to the Cast SDK.
* @param message The JSONObject message to be handled.
*/
public boolean handleSessionMessage(JSONObject message) throws JSONException {
String messageType = message.getString("type");
if ("v2_message".equals(messageType)) {
return handleCastV2Message(message);
} else if ("app_message".equals(messageType)) {
return handleAppMessage(message);
} else {
Log.e(TAG, "Unsupported message: %s", message);
return false;
}
}
void onCharacteristicWrite(int status) {
Log.i(TAG, "onCharacteristicWrite status:%d==%s", status,
status == android.bluetooth.BluetoothGatt.GATT_SUCCESS ? "OK" : "Error");
if (mNativeBluetoothRemoteGattCharacteristicAndroid != 0) {
nativeOnWrite(mNativeBluetoothRemoteGattCharacteristicAndroid, status);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Ensure that native library is loaded.
try {
ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup();
} catch (ProcessInitException e) {
Log.e(TAG, "Failed to start browser process.", e);
ChromeApplication.reportStartupErrorAndExit(e);
}
}
@GuardedBy("mNativeStreamLock")
private void destroyNativeStreamLocked(boolean sendOnCanceled) {
Log.i(CronetUrlRequestContext.LOG_TAG, "destroyNativeStreamLocked " + this.toString());
if (mNativeStream == 0) {
return;
}
nativeDestroy(mNativeStream, sendOnCanceled);
mRequestContext.onRequestDestroyed();
mNativeStream = 0;
if (mOnDestroyedCallbackForTesting != null) {
mOnDestroyedCallbackForTesting.run();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_id_close) {
finish();
return true;
} else if (id == R.id.menu_id_refresh) {
startRefresh(true, false);
return true;
}
Log.e(TAG, "Unknown menu item selected");
return super.onOptionsItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_id_close) {
finish();
return true;
} else if (id == R.id.menu_id_refresh) {
startRefresh(true, false);
return true;
}
Log.e(TAG, "Unknown menu item selected");
return super.onOptionsItemSelected(item);
}
/**
* Processes pending operation when NFC tag is in proximity.
*/
protected void processPendingOperations(NfcTagHandler tagHandler) {
mTagHandler = tagHandler;
processPendingWatchOperations();
processPendingPushOperation();
if (mTagHandler != null && mTagHandler.isConnected()) {
try {
mTagHandler.close();
} catch (IOException e) {
Log.w(TAG, "Cannot close NFC tag connection.");
}
}
}
/**
* Set the sessions ID using the generator that was registered for GENERATOR_ID.
*/
private void setSessionsId() {
UniqueIdentificationGenerator generator =
UniqueIdentificationGeneratorFactory.getInstance(GENERATOR_ID);
String uniqueTag = generator.getUniqueId(null);
if (uniqueTag.isEmpty()) {
Log.e(TAG, "Unable to get unique tag for sync. "
+ "This may lead to unexpected tab sync behavior.");
return;
}
mProfileSyncService.setSessionsId(SESSION_TAG_PREFIX + uniqueTag);
}