下面列出了怎么用android.content.Context的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onPatchDownloadFail(Exception e, Integer newVersion, Integer currentVersion) {
TinkerLog.w(TAG, "onPatchDownloadFail e:" + e);
//check network
TinkerServerClient client = TinkerServerClient.get();
//due to network, just return
if (!NetStatusUtil.isConnected(client.getContext())) {
TinkerLog.e(TAG, "onPatchDownloadFail, not connect to internet just return");
return;
}
Context context = client.getContext();
if (increaseDownloadError(context)) {
client.reportPatchFail(newVersion, ERROR_DOWNLOAD_FAIL);
}
}
void bind(Context context, final FileMessage message, GroupChannel channel, boolean isNewDay, final OnItemClickListener listener) {
bind(message, isNewDay);
fileNameText.setText(message.getName());
timeText.setText(DateUtils.formatTime(message.getCreatedAt()));
if (listener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onFileMessageItemClick(message);
}
});
}
messageStatusView.drawMessageStatus(channel, message);
}
@Override
public void onUpdateComplete() {
Context context = trackerBinding.getRoot().getContext();
Tracker tracker = DatabaseManager.getInstance(context).getTracker(trackerId);
trackerBinding.name.setText(tracker.name);
trackerBinding.codeDetection.setText(tracker.codeSignature);
trackerBinding.networkDetection.setText(tracker.networkSignature);
trackerBinding.description.setText(Html.fromHtml(Utils.markdownToHtml(tracker.description)));
trackerBinding.description.setMovementMethod(LinkMovementMethod.getInstance());
trackerBinding.description.setClickable(true);
trackerBinding.trackerUrl.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(tracker.website));
startActivity(intent);
});
displayAppListAsync();
}
/**
* 设置手机号码回调
*
* @param context
* @param jPushMessage
*/
public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
int sequence = jPushMessage.getSequence();
LogUtil.i(TAG, "action - onMobileNumberOperatorResult, sequence:" + sequence + ",mobileNumber:" + jPushMessage.getMobileNumber());
init(context);
if (jPushMessage.getErrorCode() == 0) {
LogUtil.i(TAG, "action - set mobile number Success,sequence:" + sequence);
setActionCache.remove(sequence);
} else {
String logs = "Failed to set mobile number, errorCode:" + jPushMessage.getErrorCode();
LogUtil.e(TAG, logs);
if (!RetrySetMobileNumberActionIfNeeded(jPushMessage.getErrorCode(), jPushMessage.getMobileNumber())) {
ExampleUtil.showToast(logs, context);
}
}
}
public AnimatedHoldButton(Context context, AttributeSet attrs) {
super(context, attrs);
CLICK_HOLD_TIME = ViewUtils.getLongClickTimeout(context);
mPrimaryText = "";
mNormalDrawable = getBackground();
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AnimatedHoldButton, 0, 0);
try {
mPrimaryText = ta.getString(R.styleable.AnimatedHoldButton_primary_text);
mPressedColor = ta.getColor(R.styleable.AnimatedHoldButton_pressed_color,
ContextCompat.getColor(context, R.color.op_button_pressed));
} finally {
ta.recycle();
}
//this is needed for so paint knows what to measure in layoutText
setText(mPrimaryText);
}
private void initView(Context context) {
this.context = context;
View v = LayoutInflater.from(context).inflate(R.layout.view_video_controller, null);
addView(v);
mVideoView = findView(R.id.videoView);
mVideoView.setOnTouchListener(this);
mVideoView.setOnPreparedListener(this);
mVideoView.setOnBufferingUpdateListener(this);
mVideoView.setOnCompletionListener(this);
mProgressWheel = findView(R.id.progressWheel);
mProgressWheel.startSpinning();
viewPlay = findView(R.id.button_play);
slider = findView(R.id.slider);
slider.setOnValueChangedListener(this);
slider.setOnNumberIndicatorConvert(new Slider.OnNumberIndicatorConvert() {
@Override
public String covert(long val) {
return MediaPlayerUtils.getVideoDisplayTime(val);
}
});
setVideoPlayButton();
}
public BaldFrameLayoutButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.sharedPreferences = context.getSharedPreferences(D.BALD_PREFS, Context.MODE_PRIVATE);
this.longPresses = sharedPreferences.getBoolean(BPrefs.LONG_PRESSES_KEY, BPrefs.LONG_PRESSES_DEFAULT_VALUE);
this.longPressesShorter = sharedPreferences.getBoolean(BPrefs.LONG_PRESSES_SHORTER_KEY, BPrefs.LONG_PRESSES_SHORTER_DEFAULT_VALUE);
this.vibrationFeedback = sharedPreferences.getBoolean(BPrefs.VIBRATION_FEEDBACK_KEY, BPrefs.VIBRATION_FEEDBACK_DEFAULT_VALUE);
this.vibrator = this.vibrationFeedback ? (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE) : null;
longer = longPresses ? BaldToast.from(context).setText(context.getText(R.string.press_longer)).setType(BaldToast.TYPE_DEFAULT).setLength(0).build() : null;
if (longPresses)
if (longPressesShorter) {
baldButtonTouchListener = new BaldButtonTouchListener(this);
super.setOnTouchListener(baldButtonTouchListener);
super.setOnClickListener(D.EMPTY_CLICK_LISTENER);
} else {
super.setOnLongClickListener(this);
super.setOnClickListener(this);
}
else
super.setOnClickListener(this);
}
/**
* Get a Resources instance with the currently selected locale applied.
*/
public static Resources getLocalizedResources(Context context) {
final Resources currentResources = context.getResources();
final Locale currentLocale = LocaleManager.getInstance().getCurrentLocale(context);
@SuppressWarnings("deprecation") final Locale viewLocale = currentResources.getConfiguration().locale;
if (currentLocale == null || viewLocale == null) {
return currentResources;
}
if (currentLocale.toLanguageTag().equals(viewLocale.toLanguageTag())) {
return currentResources;
}
final Configuration configuration = new Configuration(currentResources.getConfiguration());
configuration.setLocale(currentLocale);
return context.createConfigurationContext(configuration).getResources();
}
private static void saveWallpaperCardPreference(@NonNull final Context context, final WallpaperCard wallpaperCard) {
final SharedPreferences pref = context.getSharedPreferences(CURRENT_CARD_PREF, MODE_PRIVATE);
// Save to preference.
final SharedPreferences.Editor prefEditor = pref.edit();
prefEditor.putString("name", wallpaperCard.getName());
prefEditor.putString("path", wallpaperCard.getPath());
switch (wallpaperCard.getType()) {
case INTERNAL:
prefEditor.putString("type", "INTERNAL");
break;
case EXTERNAL:
prefEditor.putString("type", "EXTERNAL");
break;
}
prefEditor.apply();
}
public static URI getURI(Context c, String path, String query) throws URISyntaxException {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(c);
String scheme = getScheme(preferences);
String host = preferences.getString(Constants.PREFERENCE_MDS_URL,
c.getString(R.string.host_mds));
int port = getPort(c);
String root = c.getString(R.string.path_root);
Log.i(TAG, " path:" + root + path);
URI uri = new URI(scheme, null, host, port, root + path, query, null);
Log.i(TAG, "uri: " + uri.toString() + ", path:" + path);
return uri;
}
@Override
public void onReceive(Context context, Intent intent) {
if(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()).getBoolean("wifi_sync_only", false)) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
int networkType = connManager.getActiveNetworkInfo().getType();
if(networkType != ConnectivityManager.TYPE_WIFI){
sendDebugNotification("Not on WiFi, not syncing...", context);
return;
}
}
sendDebugNotification("Syncing with server...", context);
FlashManager flashManager = new FlashManager(context);
flashManager.refresh();
sendDebugNotification("Sync completed!", context);
}
private void checkRegistering(@NonNull final Context context,
@NonNull final OPFPushHelper helper,
@NonNull final String providerName) {
OPFLog.logMethod(context, helper, providerName);
if (helper.isRegistering()) {
Settings.getInstance(context).saveState(State.UNREGISTERED);
helper.registerNextAvailableProvider(providerName);
}
}
/**
* Gets SSID of Connected WiFi
*
* You need to declare the below permission in the manifest file to use this properly
*
* <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
*
* @return Returns the service set identifier (SSID) of the current 802.11 network
*/
@RequiresPermission(allOf = {
Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE
})
public final String getWifiSSID() {
String result = null;
if (PermissionUtil.hasPermission(context, Manifest.permission.ACCESS_WIFI_STATE)) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo == null) {
result = null;
}
if (networkInfo != null && networkInfo.isConnected()) {
final WifiManager wifiManager =
(WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
result = connectionInfo.getSSID();
}
}
}
}
}
return CheckValidityUtil.checkValidData(result);
}
public void doText(NewsViewHolder holder, Submission submission, Context mContext,
String baseSub) {
SpannableStringBuilder t = SubmissionCache.getTitleLine(submission, mContext);
SpannableStringBuilder l = SubmissionCache.getInfoLine(submission, mContext, baseSub);
int[] textSizeAttr = new int[]{R.attr.font_cardtitle, R.attr.font_cardinfo};
TypedArray a = mContext.obtainStyledAttributes(textSizeAttr);
int textSizeT = a.getDimensionPixelSize(0, 18);
int textSizeI = a.getDimensionPixelSize(1, 14);
a.recycle();
t.setSpan(new AbsoluteSizeSpan(textSizeT), 0, t.length(), 0);
l.setSpan(new AbsoluteSizeSpan(textSizeI), 0, l.length(), 0);
SpannableStringBuilder s = new SpannableStringBuilder();
if (SettingValues.titleTop) {
s.append(t);
s.append("\n");
s.append(l);
} else {
s.append(l);
s.append("\n");
s.append(t);
}
holder.title.setText(s);
}
/**
* Only when the app's target SDK is 23 or higher, it requests each dangerous permissions it
* needs when the app is running.
*/
private static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private void init(Context context, AttributeSet attrs, int defStyle) {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ScrimInsetsRelativeLayout, defStyle, 0);
mInsetForeground = a.getDrawable(R.styleable.ScrimInsetsRelativeLayout_appInsetForeground);
mConsumeInsets = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_appConsumeInsets, true);
mFitTop = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitTop, true);
mFitBottom = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitBottom, false);
mFitLeft = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitLeft, false);
mFitRight = a.getBoolean(R.styleable.ScrimInsetsRelativeLayout_fitRight, false);
a.recycle();
setWillNotDraw(true);
ViewCompat.setOnApplyWindowInsetsListener(this, (v, insets) -> {
if (!mConsumeInsets) {
if (mOnInsetsCallback != null) {
mOnInsetsCallback.onInsetsChanged(new Rect(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()));
}
return insets.consumeSystemWindowInsets();
}
if (null == ScrimInsetsRelativeLayout.this.mInsets) {
ScrimInsetsRelativeLayout.this.mInsets = new Rect();
}
ScrimInsetsRelativeLayout.this.mInsets.set(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
ScrimInsetsRelativeLayout.this.onInsetsChanged(ScrimInsetsRelativeLayout.this.mInsets);
ScrimInsetsRelativeLayout.this.setWillNotDraw(!insets.hasSystemWindowInsets() || ScrimInsetsRelativeLayout.this.mInsetForeground == null);
ViewCompat.postInvalidateOnAnimation(ScrimInsetsRelativeLayout.this);
return insets.consumeSystemWindowInsets();
});
}
/**
* 检查 files 目录下个某个文件是否已经为最新(比 assets 目录下的新)
*
* @param c
* @param filename
* @return 如果文件比 assets 下的同名文件的时间戳旧,或者文件不存在,则返回 false.
*/
public static boolean isFileUpdated(Context c, String filename) {
File file = c.getFileStreamPath(filename);
if (file == null) {
return false;
}
if (!file.exists()) {
return false;
}
long timestampOfFile = getFileTimestamp(c, filename);
long timestampOfAsset = getBundleTimestamp(c, filename);
return (timestampOfAsset <= timestampOfFile);
}
protected boolean isMobileNetworkCapable() {
ConnectivityManager connectivityManager =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
// Android telephony team said it is OK to continue using getNetworkInfo() for our purposes.
// We cannot use ConnectivityManager#getAllNetworks() because that one only reports enabled
// networks. See crbug.com/532455.
@SuppressWarnings("deprecation")
NetworkInfo networkInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return networkInfo != null;
}
@Override public void registerComponents(Context context, Glide glide) {
// just to see the headers actually went through, Stetho or proxy can also be used for this
glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(new OkHttpClient.Builder()
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build()));
// override default loader with one that attaches headers
glide.register(String.class, InputStream.class, new HeaderedLoader.Factory());
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
UILApplication.initImageLoader(context);
final int widgetCount = appWidgetIds.length;
for (int i = 0; i < widgetCount; i++) {
int appWidgetId = appWidgetIds[i];
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
public static TreeMap<String, String> getRestrictions(Context context) {
Collator collator = Collator.getInstance(Locale.getDefault());
TreeMap<String, String> tmRestriction = new TreeMap<String, String>(collator);
for (String restrictionName : getRestrictions()) {
int stringId = context.getResources().getIdentifier("restrict_" + restrictionName, "string",
context.getPackageName());
tmRestriction.put(stringId == 0 ? restrictionName : context.getString(stringId), restrictionName);
}
return tmRestriction;
}
public LetvMediaPlayerControl4D build(Context context, Type type) {
LogTag.i("Create player, type=" + (type != null ? type.toString() : "null") + ", version=" + 1.4f);
switch ($SWITCH_TABLE$com$letv$component$player$fourd$LetvVideoViewBuilder4D$Type()[type.ordinal()]) {
case 1:
return new VideoViewH264mp4_4D(context);
case 2:
return new VideoViewH264m3u8_4D(context);
case 3:
return new VideoViewH264m3u8Hw_4D(context);
case 4:
return new VideoViewH264LeMobile_4D(context);
default:
return null;
}
}
public CardContainer(Context context) {
super(context);
setOrientation(Orientation.Disordered);
setGravity(Gravity.CENTER);
init();
}
@Override
public void onReceive(Context context, Intent intent)
{
unregisterAccListener();
setSurfaceFlingerTranslate(0, 0);
Log.d(TAG, "Screen is off");
}
/**
* Public constructor with only Context, millisToVibrate and pressureLimit is setted by default
* @param context Context
* @param forceTouchExecution Callback
* @param isProgressive boolean
*/
public ForceTouchListener(Context context, boolean isProgressive, boolean isVibrate, Callback forceTouchExecution){
this.context = context;
this.millisToVibrate = DEFAULT_MILLIS_TO_VIBRATE;
this.pressureLimit = DEFAULT_PRESSURE_LIMIT;
this.forceTouchExecution = forceTouchExecution;
this.isProgressive = isProgressive;
this.isVibrate = isVibrate;
}
public static void writeFile(Context context){
try {
OutputStream os = getLogStream(context);
os.write(getInformation(context).getBytes("utf-8"));
os.flush();
os.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void initLesoApplication() {
AMapLocationTool.getInstance().location();
if (!isFirstInitLeso) {
Class clazz_lesoinit = JarLoader.loadClass(LetvApplication.getInstance().getApplicationContext(), "LetvLeso.apk", JarConstant.LETV_LESO_PACKAGENAME, "utils.LesoInitData");
if (clazz_lesoinit != null && clazz_lesoinit != null) {
JarLoader.invokeStaticMethod(clazz_lesoinit, "initData", new Class[]{Context.class}, new Object[]{LetvApplication.getInstance().getApplicationContext()});
isFirstInitLeso = true;
}
}
}
public static String load(Context context, String fileName) {
try {
return IOUtils.toString(context.getResources().getAssets().open(fileName));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public File createFile(Uri uri, @NonNull Context context) {
InputStream in;
ContentResolver resolver = context.getContentResolver();
String type = resolver.getType(uri);
String extension;
if ("image/png".equals(type)) {
extension = ".gif";
} else if ("image/png".equals(type)) {
extension = ".png";
} else {
extension = ".jpg";
}
try {
in = resolver.openInputStream(uri);
} catch (FileNotFoundException e) {
return null;
}
// Create files from a uri in our cache directory so they eventually get deleted
String timeStamp = String.valueOf(System.currentTimeMillis());
File cacheDir = ((Reddit) context.getApplicationContext()).getImageLoader()
.getDiskCache()
.getDirectory();
File tempFile = new File(cacheDir, timeStamp + extension);
if (writeInputStreamToFile(in, tempFile)) {
return tempFile;
} else {
// If writeInputStreamToFile fails, delete the excess file
tempFile.delete();
}
return null;
}
public TvShowSearch(Context context, String query) {
mContext = context;
mQueryText = query;
// Execute the AsyncTask
execute();
}