Here are the examples of the java api @android.annotation.SuppressLint(HandlerLeak) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
221 Examples
19
Source : WeatherActivity.java
with Apache License 2.0
from yangxch
with Apache License 2.0
from yangxch
@SuppressLint("HandlerLeak")
private void refresh(boolean useLocal) {
weatherManager.refreshWeather(weatherID, useLocal, new Handler() {
@SuppressLint("StringFormatMatches")
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
contentMian.setVisibility(View.VISIBLE);
swipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
});
if (msg.what == Constant.MSG_ERROR) {
Toast.makeText(WeatherActivity.this, "刷新失败", Toast.LENGTH_SHORT).show();
} else {
WeatherInfo weatherInfo = (WeatherInfo) msg.obj;
Aqi aqi = weatherInfo.getAqi();
// 实时
RealWeather realWeather = weatherInfo.getRealWeather();
mSkyView.setWeather(realWeather.getWeatherCondition(), realWeather.getSunrise(), realWeather.getSundown());
swipeRefreshLayout.setColorSchemeColors(mSkyView.getBackGroundColor());
mCurrentAreaTv.setText(realWeather.getAreaName());
mRealTempTv.setText(realWeather.getTemp() + "");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
mUpdateTimeTv.setText(String.format(getResources().getString(R.string.activity_home_refresh_time), simpleDateFormat.format(realWeather.getLastUpdate())));
mRealAqiTv.setText("空气" + aqi.getQuality() + " " + aqi.getAqi());
mWeatherAndFeelTemp.setText(String.format(getResources().getString(R.string.activity_home_type_and_real_feel_temp), realWeather.getWeatherCondition(), realWeather.getFeeltemp()));
// 周报&&时报
weekForeCastView.setForeCasts(weatherInfo.getWeekForeCasts());
hourForeCastView.setHourForeCasts(weatherInfo.getHourForeCasts());
windForecastView.setForeCasts(weatherInfo.getWeekForeCasts());
// 风速湿度
windViewBig.setWindSpeedDegree(Integer.parseInt(realWeather.getFj().replace("级", "")));
windViewSmall.setWindSpeedDegree(Integer.parseInt(realWeather.getFj().replace("级", "")));
mWindDegreeTv.setText(realWeather.getFx());
mWindLevelTv.setText(realWeather.getFj());
progressBar.setProgress(realWeather.getShidu());
mShiduTv.setText(realWeather.getShidu() + "");
// 空气
mAqi.setProgressAndLabel(aqi.getAqi(), "空气" + aqi.getQuality());
mPm2_5Tv.setText(aqi.getPm2_5() + " μg/m³");
mPm10Tv.setText(aqi.getPm10() + " μg/m³");
mSo2Tv.setText(aqi.getSo2() + " μg/m³");
mNo2Tv.setText(aqi.getNo2() + " μg/m³");
// 日出
mSunRiseView.setSunRiseDownTime(realWeather.getSunrise(), realWeather.getSundown());
// 指数
zhishuList.clear();
zhishuList.addAll(weatherInfo.getZhishu());
mZhiShuAdapter.notifyDataSetChanged();
contentMian.smoothScrollTo(0, 0);
// 预警
final Alarms alarms = weatherInfo.getAlarms();
if (alarms != null) {
mRealAqiTv.setClickable(true);
mRealAqiTv.setText(alarms.getAlarmLevelNoDesc() + alarms.getAlarmTypeDesc());
mRealAqiTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WeatherActivity.this, AlarmActivity.clreplaced);
intent.putExtra("alarminfo", alarms);
startActivity(intent);
}
});
} else
mRealAqiTv.setClickable(false);
}
}
});
}
19
Source : AwWebContentsDelegateAdapter.java
with BSD 3-Clause "New" or "Revised" License
from ridi
with BSD 3-Clause "New" or "Revised" License
from ridi
@Override
@SuppressLint("HandlerLeak")
public void showRepostFormWarningDialog() {
// TODO(mkosiba) We should be using something akin to the JsResultReceiver as the
// callback parameter (instead of WebContents) and implement a way of converting
// that to a pair of messages.
final int msgContinuePendingReload = 1;
final int msgCancelPendingReload = 2;
// TODO(sgurun) Remember the URL to cancel the reload behavior
// if it is different than the most recent NavigationController entry.
final Handler handler = new Handler(ThreadUtils.getUiThreadLooper()) {
@Override
public void handleMessage(Message msg) {
if (mAwContents.getNavigationController() == null)
return;
switch(msg.what) {
case msgContinuePendingReload:
{
mAwContents.getNavigationController().continuePendingReload();
break;
}
case msgCancelPendingReload:
{
mAwContents.getNavigationController().cancelPendingReload();
break;
}
default:
throw new IllegalStateException("WebContentsDelegateAdapter: unhandled message " + msg.what);
}
}
};
Message resend = handler.obtainMessage(msgContinuePendingReload);
Message dontResend = handler.obtainMessage(msgCancelPendingReload);
mContentsClient.getCallbackHelper().postOnFormResubmission(dontResend, resend);
}
19
Source : RxTextViewVertical.java
with Apache License 2.0
from hexingbo
with Apache License 2.0
from hexingbo
/**
* 间隔时间
*
* @param time
*/
@SuppressLint("HandlerLeak")
public void setTextStillTime(final long time) {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case FLAG_START_AUTO_SCROLL:
if (textList.size() > 0) {
currentId++;
setText(textList.get(currentId % textList.size()));
}
handler.sendEmptyMessageDelayed(FLAG_START_AUTO_SCROLL, time);
break;
case FLAG_STOP_AUTO_SCROLL:
handler.removeMessages(FLAG_START_AUTO_SCROLL);
break;
default:
break;
}
}
};
}
19
Source : Hourglass.java
with MIT License
from groverankush
with MIT License
from groverankush
@SuppressLint("HandlerLeak")
private void initHourglreplaced() {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MSG) {
if (!isPaused) {
if (localTime <= time) {
onTimerTick(time - localTime);
localTime += interval;
sendMessageDelayed(handler.obtainMessage(MSG), interval);
} else
stopTimer();
}
}
}
};
}
19
Source : PhotoSelectorDomain.java
with GNU General Public License v3.0
from gallonyin
with GNU General Public License v3.0
from gallonyin
/**
* Created by fengyongge on 2016/5/24
*/
@SuppressLint("HandlerLeak")
public clreplaced PhotoSelectorDomain {
private AlbumController albumController;
public PhotoSelectorDomain(Context context) {
albumController = new AlbumController(context);
}
public void getReccent(final PhotoSelectorActivity.OnLocalReccentListener listener) {
final Handler handler = new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
List<PhotoModel> temp_photos = (List<PhotoModel>) msg.obj;
listener.onPhotoLoaded(temp_photos);
}
};
new Thread(new Runnable() {
@Override
public void run() {
List<PhotoModel> photos = albumController.getCurrent();
Message msg = new Message();
msg.obj = photos;
handler.sendMessage(msg);
}
}).start();
}
/**
* 获取相册列表
*/
public void updateAlbum(final PhotoSelectorActivity.OnLocalAlbumListener listener) {
final Handler handler = new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
List<AlbumModel> albums = (List<AlbumModel>) msg.obj;
int index = 0;
for (int i = 0; i < albums.size(); i++) {
if ("images".equals(albums.get(i).getName())) {
index = i;
}
}
if (albums.size() > 0) {
albums.remove(index);
}
listener.onAlbumLoaded(albums);
}
};
new Thread(new Runnable() {
@Override
public void run() {
List<AlbumModel> albums = albumController.getAlbums();
Message msg = new Message();
msg.obj = albums;
handler.sendMessage(msg);
}
}).start();
}
/**
* 获取单个相册下的所有照片信息
*/
public void getAlbum(final String name, final PhotoSelectorActivity.OnLocalReccentListener listener) {
final Handler handler = new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
listener.onPhotoLoaded((List<PhotoModel>) msg.obj);
}
};
new Thread(new Runnable() {
@Override
public void run() {
List<PhotoModel> photos = albumController.getAlbum(name);
Message msg = new Message();
msg.obj = photos;
handler.sendMessage(msg);
}
}).start();
}
}
19
Source : ContactFragment.java
with Apache License 2.0
from ccfish86
with Apache License 2.0
from ccfish86
@SuppressLint("HandlerLeak")
@Override
protected void initHandler() {
uiHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case HandlerConstant.HANDLER_CHANGE_CONTACT_TAB:
if (null != msg.obj) {
curTabIndex = (Integer) msg.obj;
if (0 == curTabIndex) {
allContactListView.setVisibility(View.VISIBLE);
departmentContactListView.setVisibility(View.GONE);
} else {
departmentContactListView.setVisibility(View.VISIBLE);
allContactListView.setVisibility(View.GONE);
}
}
break;
}
}
};
}
18
Source : DispatchLoading.java
with Apache License 2.0
from yhyzgn
with Apache License 2.0
from yhyzgn
/**
* 初始化
*/
@SuppressLint("HandlerLeak")
private void init() {
// 初始化数据
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 只有要更新的状态不等于当前状态时,才有效
if (null != msg && msg.what != mCurrentState) {
// 更新状态
mCurrentState = msg.what;
// 更新UI
updateUI();
}
}
};
// 创建结果集Handler
mResultHandler = new ResultHandler(mHandler);
// 获取拦截器
if (null == mLoadingInterceptor) {
mLoadingInterceptor = getLoadingInterceptor();
}
if (null == mEmptyInterceptor) {
mEmptyInterceptor = getEmptyInterceptor();
}
if (null == mErrorInterceptor) {
mErrorInterceptor = getErrorInterceptor();
}
if (null == mSuccessInterceptor) {
mSuccessInterceptor = getSuccessInterceptor();
}
// 获取具体页面
if (null == mLoadingView) {
mLoadingView = getLoadingView();
addView(mLoadingView);
mLoadingView.setVisibility(mLoadingInterceptor.processAhead() ? VISIBLE : GONE);
}
if (null == mErrorView) {
mErrorView = getErrorView();
addView(mErrorView);
mErrorView.setVisibility(GONE);
}
if (null == mEmptyView) {
mEmptyView = getEmptyView();
addView(mEmptyView);
mEmptyView.setVisibility(GONE);
}
if (null == mSuccessView) {
mSuccessView = getSuccessView();
addView(mSuccessView);
mSuccessView.setVisibility(GONE);
}
// 当前状态为默认状态
mCurrentState = TpgConst.LoadingStatus.STATE_DEFAULT;
}
18
Source : CountDownTimer.java
with Apache License 2.0
from yangchong211
with Apache License 2.0
from yangchong211
/**
* <pre>
* @author yangchong
* email : [email protected]
* time : 2020/5/26
* desc : 自定义倒计时器
* revise: 支持开始,暂停,恢复暂停,取消等业务逻辑
* 也可以用于多线程中
* </pre>
*/
public clreplaced CountDownTimer {
/**
* 时间,即开始的时间,通俗来说就是倒计时总时间
*/
private long mMillisInFuture;
/**
* 布尔值,表示计时器是否被取消
* 只有调用cancel时才被设置为true
*/
private boolean mCancelled = false;
/**
* 用户接收回调的时间间隔,一般是1秒
*/
private long mCountdownInterval;
/**
* 记录暂停时候的时间
*/
private long mStopTimeInFuture;
/**
* mas.what值
*/
private static final int MSG = 520;
/**
* 暂停时,当时剩余时间
*/
private long mCurrentMillisLeft;
/**
* 是否暂停
* 只有当调用pause时,才设置为true
*/
private boolean mPause = false;
/**
* 监听listener
*/
private TimerListener mCountDownListener;
public CountDownTimer() {
}
public CountDownTimer(long millisInFuture, long countdownInterval) {
this.mMillisInFuture = millisInFuture;
this.mCountdownInterval = countdownInterval;
}
/**
* 开始倒计时,每次点击,都会重新开始
*/
public synchronized final void start() {
if (mMillisInFuture <= 0 && mCountdownInterval <= 0) {
throw new RuntimeException("you must set the millisInFuture > 0 or countdownInterval >0");
}
mCancelled = false;
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mPause = false;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
if (mCountDownListener != null) {
mCountDownListener.onStart();
}
}
/**
* 取消计时器
*/
public synchronized final void cancel() {
if (mHandler != null) {
// 暂停
mPause = false;
mHandler.removeMessages(MSG);
// 取消
mCancelled = true;
}
}
/**
* 按一下暂停,再按一下继续倒计时
*/
public synchronized final void pause() {
if (mHandler != null) {
if (mCancelled) {
return;
}
if (mCurrentMillisLeft < mCountdownInterval) {
return;
}
if (!mPause) {
mHandler.removeMessages(MSG);
mPause = true;
}
}
}
/**
* 恢复暂停,开始
*/
public synchronized final void resume() {
if (mMillisInFuture <= 0 && mCountdownInterval <= 0) {
throw new RuntimeException("you must set the millisInFuture > 0 or countdownInterval >0");
}
if (mCancelled) {
return;
}
// 剩余时长少于
if (mCurrentMillisLeft < mCountdownInterval || !mPause) {
return;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mCurrentMillisLeft;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
mPause = false;
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
synchronized (CountDownTimer.this) {
if (mCancelled) {
return;
}
// 剩余毫秒数
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
mCurrentMillisLeft = 0;
if (mCountDownListener != null) {
mCountDownListener.onFinish();
}
} else if (millisLeft < mCountdownInterval) {
mCurrentMillisLeft = 0;
// 剩余时间小于一次时间间隔的时候,不再通知,只是延迟一下
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
// 有多余的时间
long lastTickStart = SystemClock.elapsedRealtime();
if (mCountDownListener != null) {
mCountDownListener.onTick(millisLeft);
}
mCurrentMillisLeft = millisLeft;
// 考虑用户的onTick需要花费时间,处理用户onTick执行的时间
long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// 特殊情况:用户的onTick方法花费的时间比interval长,那么直接跳转到下一次interval
while (delay < 0) {
delay += mCountdownInterval;
}
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
/**
* 设置倒计时总时间
* @param millisInFuture 毫秒值
*/
public void setMillisInFuture(long millisInFuture) {
this.mMillisInFuture = millisInFuture;
}
/**
* 设置倒计时间隔值
* @param countdownInterval 间隔,一般设置为1000毫秒
*/
public void setCountdownInterval(long countdownInterval) {
this.mCountdownInterval = countdownInterval;
}
/**
* 设置倒计时监听
* @param countDownListener listener
*/
public void setCountDownListener(TimerListener countDownListener) {
this.mCountDownListener = countDownListener;
}
public interface TimerListener {
/**
* 当倒计时开始
*/
void onStart();
/**
* 当倒计时结束
*/
void onFinish();
/**
* @param millisUntilFinished 剩余时间
*/
void onTick(long millisUntilFinished);
}
}
18
Source : WXCircleViewPager.java
with Apache License 2.0
from weexext
with Apache License 2.0
from weexext
/**
*/
@SuppressLint("HandlerLeak")
public clreplaced WXCircleViewPager extends ViewPager implements WXGestureObservable {
private WXGesture wxGesture;
private boolean isAutoScroll;
private long intervalTime = 3 * 1000;
private WXSmoothScroller mScroller;
private boolean needLoop = true;
private boolean scrollable = true;
private int mState = ViewPager.SCROLL_STATE_IDLE;
private Runnable scrollAction = new ScrollAction(this);
@SuppressLint("NewApi")
public WXCircleViewPager(Context context) {
super(context);
init();
}
private void init() {
setOverScrollMode(View.OVER_SCROLL_NEVER);
addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
mState = state;
WXCirclePageAdapter adapter = getCirclePageAdapter();
int currenreplacedemInternal = WXCircleViewPager.super.getCurrenreplacedem();
if (needLoop && state == ViewPager.SCROLL_STATE_IDLE && adapter.getCount() > 1) {
if (currenreplacedemInternal == adapter.getCount() - 1) {
superSetCurrenreplacedem(1, false);
} else if (currenreplacedemInternal == 0) {
superSetCurrenreplacedem(adapter.getCount() - 2, false);
}
}
}
});
postInitViewPager();
}
/**
* Override the Scroller instance with our own clreplaced so we can change the
* duration
*/
private void postInitViewPager() {
if (isInEditMode()) {
return;
}
try {
Field scroller = ViewPager.clreplaced.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = ViewPager.clreplaced.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new WXSmoothScroller(getContext(), (Interpolator) interpolator.get(null));
scroller.set(this, mScroller);
} catch (Exception e) {
WXLogUtils.e("[CircleViewPager] postInitViewPager: ", e);
}
}
@SuppressLint("NewApi")
public WXCircleViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
public int getCurrenreplacedem() {
return getRealCurrenreplacedem();
}
public int superGetCurrenreplacedem() {
return super.getCurrenreplacedem();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!scrollable) {
return true;
}
boolean result = super.onTouchEvent(ev);
if (wxGesture != null) {
result |= wxGesture.onTouch(this, ev);
}
return result;
}
@Override
public void scrollTo(int x, int y) {
if (scrollable || mState != ViewPager.SCROLL_STATE_DRAGGING) {
super.scrollTo(x, y);
}
}
/**
* Start auto scroll. Must be called after {@link #setAdapter(PagerAdapter)}
*/
public void startAutoScroll() {
isAutoScroll = true;
removeCallbacks(scrollAction);
postDelayed(scrollAction, intervalTime);
}
public void pauseAutoScroll() {
removeCallbacks(scrollAction);
}
/**
* Stop auto scroll.
*/
public void stopAutoScroll() {
isAutoScroll = false;
removeCallbacks(scrollAction);
}
public boolean isAutoScroll() {
return isAutoScroll;
}
@Override
public void setCurrenreplacedem(int item) {
setRealCurrenreplacedem(item);
}
/**
* @return the circlePageAdapter
*/
public WXCirclePageAdapter getCirclePageAdapter() {
return (WXCirclePageAdapter) getAdapter();
}
/**
* @param circlePageAdapter the circlePageAdapter to set
*/
public void setCirclePageAdapter(WXCirclePageAdapter circlePageAdapter) {
this.setAdapter(circlePageAdapter);
}
/**
* Get auto scroll interval. The time unit is micro second.
* The default time interval is 3000 micro second
* @return the intervalTime
*/
public long getIntervalTime() {
return intervalTime;
}
/**
* Set auto scroll interval. The time unit is micro second.
* The default time interval is 3000 micro second
* @param intervalTime the intervalTime to set
*/
public void setIntervalTime(long intervalTime) {
this.intervalTime = intervalTime;
}
public void setCircle(boolean circle) {
needLoop = circle;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch(ev.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
removeCallbacks(scrollAction);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (isAutoScroll()) {
postDelayed(scrollAction, intervalTime);
}
break;
}
return super.dispatchTouchEvent(ev);
}
public void destory() {
}
@Override
public void registerGestureListener(WXGesture wxGesture) {
this.wxGesture = wxGesture;
}
public int getRealCurrenreplacedem() {
int i = super.getCurrenreplacedem();
return ((WXCirclePageAdapter) getAdapter()).getRealPosition(i);
}
private void setRealCurrenreplacedem(int item) {
superSetCurrenreplacedem(((WXCirclePageAdapter) getAdapter()).getFirst() + item, false);
}
private void superSetCurrenreplacedem(int item, boolean smooth) {
try {
super.setCurrenreplacedem(item, smooth);
} catch (IllegalStateException e) {
WXLogUtils.e(e.toString());
if (getAdapter() != null) {
getAdapter().notifyDataSetChanged();
super.setCurrenreplacedem(item, smooth);
}
}
}
public int getRealCount() {
return ((WXCirclePageAdapter) getAdapter()).getRealCount();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (IllegalStateException e) {
WXLogUtils.e(e.toString());
if (getAdapter() != null) {
getAdapter().notifyDataSetChanged();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
public boolean isScrollable() {
return scrollable;
}
public void setScrollable(boolean scrollable) {
this.scrollable = scrollable;
}
private void showNexreplacedem() {
if (!needLoop && superGetCurrenreplacedem() == getRealCount() - 1) {
return;
}
if (getRealCount() == 2 && superGetCurrenreplacedem() == 1) {
superSetCurrenreplacedem(0, true);
} else {
superSetCurrenreplacedem(superGetCurrenreplacedem() + 1, true);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeCallbacks(scrollAction);
}
private static final clreplaced ScrollAction implements Runnable {
private WeakReference<WXCircleViewPager> targetRef;
private ScrollAction(WXCircleViewPager target) {
this.targetRef = new WeakReference<>(target);
}
@Override
public void run() {
WXLogUtils.d("[CircleViewPager] trigger auto play action");
WXCircleViewPager target;
if ((target = targetRef.get()) != null) {
target.showNexreplacedem();
target.removeCallbacks(this);
target.postDelayed(this, target.getIntervalTime());
}
}
}
}
18
Source : HttpUtil.java
with Apache License 2.0
from wanliyang1990
with Apache License 2.0
from wanliyang1990
/**
* Created by hlwky001 on 2020/3/9.
*/
public clreplaced HttpUtil {
private static HttpUtil instance;
private HttpResultListener resultListener;
public static HttpUtil getInstance() {
synchronized (HttpUtil.clreplaced) {
if (instance == null) {
instance = new HttpUtil();
}
}
return instance;
}
private HttpURLConnection getHttpURLConnection(String uri, String referer, String method) throws IOException {
URL url = new URL(uri);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
if (referer != null && "".equals(referer)) {
httpConn.setRequestProperty("Referer", referer);
}
httpConn.setRequestMethod(method);
httpConn.setDoInput(true);
return httpConn;
}
private byte[] getBytesFromStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] kb = new byte[1024];
int len;
while ((len = is.read(kb)) != -1) {
baos.write(kb, 0, len);
}
byte[] bytes = baos.toByteArray();
baos.close();
is.close();
return bytes;
}
public void doHttpGet(final String uri, final String code, final String referer, HttpResultListener resultListener) {
this.resultListener = resultListener;
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection httpsConn = getHttpURLConnection(uri, referer, "GET");
byte[] result = getBytesFromStream(httpsConn.getInputStream());
Message message = Message.obtain();
message.obj = new String(result, code);
message.what = 0;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
Message message = Message.obtain();
message.what = -1;
handler.sendMessage(message);
}
}
}).start();
}
@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
String result = (String) msg.obj;
if (resultListener != null) {
resultListener.onSuccess(result);
}
} else if (msg.what == -1) {
if (resultListener != null) {
resultListener.onFail("加载数据失败,请稍后再试");
}
}
}
};
public interface HttpResultListener {
void onSuccess(String result);
void onFail(String msg);
}
}
18
Source : AliPay.java
with Apache License 2.0
from tohodog
with Apache License 2.0
from tohodog
/**
* Created by song
* Contact github.com/tohodog
* Date 2018/3/26
* 支付宝支付
*/
public clreplaced AliPay extends BasePay {
private final int SDK_PAY_FLAG = 1;
public AliPay(PayAPI.Callback callback) {
super(callback);
}
@Override
public void pay(final Activity activity, PayInfo payInfo) {
// EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
final String finalPayParam = payInfo.payParam();
if (finalPayParam.startsWith("http")) {
// 支付宝h5支付
final PayTask task = new PayTask(activity);
boolean isIntercepted = task.payInterceptorWithUrl(finalPayParam, true, new H5PayCallback() {
@Override
public void onPayResult(final H5PayResultModel result) {
Log.i("onPayResult", result.getResultCode());
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// 支付结果返回
if (TextUtils.equals(result.getResultCode(), "9000")) {
// 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
callback.complete(result.getReturnUrl());
} else {
if (TextUtils.equals(result.getResultCode(), "6001"))
callback.cancel();
else
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
callback.fail(result.getReturnUrl());
}
}
});
}
});
if (!isIntercepted) {
throw new IllegalArgumentException("Can't Intercepted URL");
}
return;
}
// SDK支付
Runnable payRunnable = new Runnable() {
@Override
public void run() {
PayTask alipay = new PayTask(activity);
Map<String, String> result = alipay.payV2(finalPayParam, true);
Log.i("onPayResult", result.toString());
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@SuppressWarnings("unused")
public void handleMessage(Message msg) {
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
/**
* 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
*/
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
// 判断resultStatus 为9000则代表支付成功
if (TextUtils.equals(resultStatus, "9000")) {
// 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
callback.complete(resultInfo);
} else {
if (TextUtils.equals(resultStatus, "6001"))
callback.cancel();
else
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
callback.fail(resultStatus + "|" + payResult.getMemo());
}
}
};
}
18
Source : HITAApplication.java
with MIT License
from StupidTrees
with MIT License
from StupidTrees
@SuppressLint("HandlerLeak")
@Override
public void onCreate() {
super.onCreate();
// 初始化顺序不可乱
TPE = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
HContext = this;
defaultSP = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this);
themeCore = new AppThemeCore();
// TimetableCore.getInstance(HContext) = new TimetableCore(getContentResolver());
bmobCacheHelper = new BmobCacheHelper();
jwCore = new JWCore();
initUpgradeDialog();
initServices();
// 务必最后再init
Bugly.init(this, "7c0e87536a", false);
Bmob.initialize(this, "9c9c53cd53b3c7f02c37b7a3e6fd9145");
CurrentUser = BmobUser.getCurrentUser(HITAUser.clreplaced);
themeCore.initAppTheme();
}
18
Source : TerminalSession.java
with GNU General Public License v3.0
from RfidResearchGroup
with GNU General Public License v3.0
from RfidResearchGroup
/**
* A terminal session, consisting of a process coupled to a terminal interface.
* <p>
* The subprocess will be executed by the constructor, and when the size is made known by a call to
* {@link #updateSize(int, int)} terminal emulation will begin and threads will be spawned to handle the subprocess I/O.
* All terminal emulation and callback methods will be performed on the main thread.
* <p>
* The child process may be exited forcefully by using the {@link #finishIfRunning()} method.
* <p>
* NOTE: The terminal session may outlive the EmulatorView, so be careful with callbacks!
*/
public final clreplaced TerminalSession extends TerminalOutput {
/**
* Callback to be invoked when a {@link TerminalSession} changes.
*/
public interface SessionChangedCallback {
void onTextChanged(TerminalSession changedSession);
void onreplacedleChanged(TerminalSession changedSession);
void onSessionFinished(TerminalSession finishedSession);
void onClipboardText(TerminalSession session, String text);
void onBell(TerminalSession session);
void onColorsChanged(TerminalSession session);
}
private static FileDescriptor wrapFileDescriptor(int fileDescriptor) {
FileDescriptor result = new FileDescriptor();
try {
Field descriptorField;
try {
descriptorField = FileDescriptor.clreplaced.getDeclaredField("descriptor");
} catch (NoSuchFieldException e) {
// For desktop java:
descriptorField = FileDescriptor.clreplaced.getDeclaredField("fd");
}
descriptorField.setAccessible(true);
descriptorField.set(result, fileDescriptor);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
Log.wtf(EmulatorDebug.LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
System.exit(1);
}
return result;
}
private static final int MSG_NEW_INPUT = 1;
private static final int MSG_PROCESS_EXITED = 4;
public final String mHandle = UUID.randomUUID().toString();
TerminalEmulator mEmulator;
/**
* A queue written to from a separate thread when the process outputs, and read by main thread to process by
* terminal emulator.
*/
final ByteQueue mProcessToTerminalIOQueue = new ByteQueue(4096);
/**
* A queue written to from the main thread due to user interaction, and read by another thread which forwards by
* writing to the {@link #mTerminalFileDescriptor}.
*/
final ByteQueue mTerminalToProcessIOQueue = new ByteQueue(4096);
/**
* Buffer to write translate code points into utf8 before writing to mTerminalToProcessIOQueue
*/
private final byte[] mUtf8InputBuffer = new byte[5];
/**
* Callback which gets notified when a session finishes or changes replacedle.
*/
final SessionChangedCallback mChangeCallback;
/**
* The pid of the shell process. 0 if not started and -1 if finished running.
*/
int mShellPid;
/**
* The exit status of the shell process. Only valid if ${@link #mShellPid} is -1.
*/
int mShellExitStatus;
/**
* The file descriptor referencing the master half of a pseudo-terminal pair, resulting from calling
* {@link JNI#createSubprocess(String, String, String[], String[], int[], int, int)}.
*/
private int mTerminalFileDescriptor;
/**
* Set by the application for user identification of session, not by terminal.
*/
public String mSessionName;
@SuppressLint("HandlerLeak")
final Handler mMainThreadHandler = new Handler() {
final byte[] mReceiveBuffer = new byte[4 * 1024];
@Override
public void handleMessage(Message msg) {
if (msg.what == MSG_NEW_INPUT && isRunning()) {
int bytesRead = mProcessToTerminalIOQueue.read(mReceiveBuffer, false);
if (bytesRead > 0) {
mEmulator.append(mReceiveBuffer, bytesRead);
notifyScreenUpdate();
}
} else if (msg.what == MSG_PROCESS_EXITED) {
int exitCode = (Integer) msg.obj;
cleanupResources(exitCode);
mChangeCallback.onSessionFinished(TerminalSession.this);
String exitDescription = "\r\n[Process completed";
if (exitCode > 0) {
// Non-zero process exit.
exitDescription += " (code " + exitCode + ")";
} else if (exitCode < 0) {
// Negated signal.
exitDescription += " (signal " + (-exitCode) + ")";
}
exitDescription += " - press Enter]";
byte[] bytesToWrite = exitDescription.getBytes(StandardCharsets.UTF_8);
mEmulator.append(bytesToWrite, bytesToWrite.length);
notifyScreenUpdate();
}
}
};
private final String mShellPath;
private final String mCwd;
private final String[] mArgs;
private final String[] mEnv;
public TerminalSession(String shellPath, String cwd, String[] args, String[] env, SessionChangedCallback changeCallback) {
mChangeCallback = changeCallback;
this.mShellPath = shellPath;
this.mCwd = cwd;
this.mArgs = args;
this.mEnv = env;
}
/**
* Inform the attached pty of the new size and reflow or initialize the emulator.
*/
public void updateSize(int columns, int rows) {
if (mEmulator == null) {
initializeEmulator(columns, rows);
} else {
JNI.setPtyWindowSize(mTerminalFileDescriptor, rows, columns);
mEmulator.resize(columns, rows);
}
}
/**
* The terminal replacedle as set through escape sequences or null if none set.
*/
public String getreplacedle() {
return (mEmulator == null) ? null : mEmulator.getreplacedle();
}
/**
* Set the terminal emulator's window size and start terminal emulation.
*
* @param columns The number of columns in the terminal window.
* @param rows The number of rows in the terminal window.
*/
public void initializeEmulator(int columns, int rows) {
mEmulator = new TerminalEmulator(this, columns, rows, /* transcript= */
2000);
int[] processId = new int[1];
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns);
mShellPid = processId[0];
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor);
new Thread("TermSessionInputReader[pid=" + mShellPid + "]") {
@Override
public void run() {
try (InputStream termIn = new FileInputStream(terminalFileDescriptorWrapped)) {
final byte[] buffer = new byte[4096];
while (true) {
int read = termIn.read(buffer);
if (read == -1)
return;
if (!mProcessToTerminalIOQueue.write(buffer, 0, read))
return;
mMainThreadHandler.sendEmptyMessage(MSG_NEW_INPUT);
}
} catch (Exception e) {
// Ignore, just shutting down.
}
}
}.start();
new Thread("TermSessionOutputWriter[pid=" + mShellPid + "]") {
@Override
public void run() {
final byte[] buffer = new byte[4096];
try (FileOutputStream termOut = new FileOutputStream(terminalFileDescriptorWrapped)) {
while (true) {
int bytesToWrite = mTerminalToProcessIOQueue.read(buffer, true);
if (bytesToWrite == -1)
return;
termOut.write(buffer, 0, bytesToWrite);
}
} catch (IOException e) {
// Ignore.
}
}
}.start();
new Thread("TermSessionWaiter[pid=" + mShellPid + "]") {
@Override
public void run() {
int processExitCode = JNI.waitFor(mShellPid);
mMainThreadHandler.sendMessage(mMainThreadHandler.obtainMessage(MSG_PROCESS_EXITED, processExitCode));
}
}.start();
}
/**
* Write data to the shell process.
*/
@Override
public void write(byte[] data, int offset, int count) {
if (mShellPid > 0)
mTerminalToProcessIOQueue.write(data, offset, count);
}
/**
* Write the Unicode code point to the terminal encoded in UTF-8.
*/
public void writeCodePoint(boolean prependEscape, int codePoint) {
if (codePoint > 1114111 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
// 1114111 (= 2**16 + 1024**2 - 1) is the highest code point, [0xD800,0xDFFF] is the surrogate range.
throw new IllegalArgumentException("Invalid code point: " + codePoint);
}
int bufferPosition = 0;
if (prependEscape)
mUtf8InputBuffer[bufferPosition++] = 27;
if (codePoint <= /* 7 bits */
0b1111111) {
mUtf8InputBuffer[bufferPosition++] = (byte) codePoint;
} else if (codePoint <= /* 11 bits */
0b11111111111) {
/* 110xxxxx leading byte with leading 5 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11000000 | (codePoint >> 6));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
} else if (codePoint <= /* 16 bits */
0b1111111111111111) {
/* 1110xxxx leading byte with leading 4 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11100000 | (codePoint >> 12));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
} else {
/* We have checked codePoint <= 1114111 above, so we have max 21 bits = 0b111111111111111111111 */
/* 11110xxx leading byte with leading 3 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11110000 | (codePoint >> 18));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 12) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
}
write(mUtf8InputBuffer, 0, bufferPosition);
}
public TerminalEmulator getEmulator() {
return mEmulator;
}
/**
* Notify the {@link #mChangeCallback} that the screen has changed.
*/
protected void notifyScreenUpdate() {
mChangeCallback.onTextChanged(this);
}
/**
* Reset state for terminal emulator state.
*/
public void reset() {
mEmulator.reset();
notifyScreenUpdate();
}
/**
* Finish this terminal session by sending SIGKILL to the shell.
*/
public void finishIfRunning() {
if (isRunning()) {
try {
Os.kill(mShellPid, OsConstants.SIGKILL);
} catch (ErrnoException e) {
Log.w("termux", "Failed sending SIGKILL: " + e.getMessage());
}
}
}
/**
* Cleanup resources when the process exits.
*/
void cleanupResources(int exitStatus) {
synchronized (this) {
mShellPid = -1;
mShellExitStatus = exitStatus;
}
// Stop the reader and writer threads, and close the I/O streams
mTerminalToProcessIOQueue.close();
mProcessToTerminalIOQueue.close();
JNI.close(mTerminalFileDescriptor);
}
@Override
public void replacedleChanged(String oldreplacedle, String newreplacedle) {
mChangeCallback.onreplacedleChanged(this);
}
public synchronized boolean isRunning() {
return mShellPid != -1;
}
/**
* Only valid if not {@link #isRunning()}.
*/
public synchronized int getExitStatus() {
return mShellExitStatus;
}
@Override
public void clipboardText(String text) {
mChangeCallback.onClipboardText(this, text);
}
@Override
public void onBell() {
mChangeCallback.onBell(this);
}
@Override
public void onColorsChanged() {
mChangeCallback.onColorsChanged(this);
}
public int getPid() {
return mShellPid;
}
/**
* Returns the shell's working directory or null if it was unavailable.
*/
public String getCwd() {
if (mShellPid < 1) {
return null;
}
try {
final String cwdSymlink = String.format("/proc/%s/cwd/", mShellPid);
String outputPath = new File(cwdSymlink).getCanonicalPath();
String outputPathWithTrailingSlash = outputPath;
if (!outputPath.endsWith("/")) {
outputPathWithTrailingSlash += '/';
}
if (!cwdSymlink.equals(outputPathWithTrailingSlash)) {
return outputPath;
}
} catch (IOException | SecurityException e) {
Log.e(EmulatorDebug.LOG_TAG, "Error getting current directory", e);
}
return null;
}
}
18
Source : CountDownClock.java
with Apache License 2.0
from REBOOTERS
with Apache License 2.0
from REBOOTERS
@SuppressLint("HandlerLeak")
public abstract clreplaced CountDownClock {
/**
* Millis since boot when alarm should stop.
*/
private long mStopTimeInFuture;
/**
* Real time remaining until timer completes
*/
private long mMillisInFuture;
/**
* Total time on timer at start
*/
private final long mTotalCountdown;
/**
* The interval in millis that the user receives callbacks
*/
private final long mCountdownInterval;
/**
* The time remaining on the timer when it was paused, if it is currently
* paused; 0 otherwise.
*/
private long mPauseTimeRemaining;
/**
* True if timer was started running, false if not.
*/
private boolean mRunAtStart;
/**
* @param millisInFuture
* The number of millis in the future from the call to
* {@link #start} until the countdown is done and
* {@link #onFinish()} is called
* @param countDownInterval
* The interval in millis at which to execute
* {@link #onTick(millisUntilFinished)} callbacks
* @param runAtStart
* True if timer should start running, false if not
*/
public CountDownClock(long millisOnTimer, long countDownInterval, boolean runAtStart) {
mMillisInFuture = millisOnTimer;
mTotalCountdown = mMillisInFuture;
mCountdownInterval = countDownInterval;
mRunAtStart = runAtStart;
}
/**
* Cancel the countdown and clears all remaining messages
*/
public final void cancel() {
mHandler.removeCallbacksAndMessages(null);
}
/**
* Create the timer object.
*/
public synchronized final CountDownClock create() {
if (mMillisInFuture <= 0) {
onFinish();
} else {
mPauseTimeRemaining = mMillisInFuture;
}
if (mRunAtStart) {
resume();
}
return this;
}
/**
* Pauses the counter.
*/
public void pause() {
if (isRunning()) {
mPauseTimeRemaining = timeLeft();
cancel();
}
}
/**
* Resumes the counter.
*/
public void resume() {
if (isPaused()) {
mMillisInFuture = mPauseTimeRemaining;
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
mPauseTimeRemaining = 0;
}
}
/**
* Tests whether the timer is paused.
*
* @return true if the timer is currently paused, false otherwise.
*/
public boolean isPaused() {
return (mPauseTimeRemaining > 0);
}
/**
* Tests whether the timer is running. (Performs logical negation on
* {@link #isPaused()})
*
* @return true if the timer is currently running, false otherwise.
*/
public boolean isRunning() {
return (!isPaused());
}
/**
* Returns the number of milliseconds remaining until the timer is finished
*
* @return number of milliseconds remaining until the timer is finished
*/
public long timeLeft() {
long millisUntilFinished;
if (isPaused()) {
millisUntilFinished = mPauseTimeRemaining;
} else {
millisUntilFinished = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisUntilFinished < 0)
millisUntilFinished = 0;
}
return millisUntilFinished;
}
/**
* Returns the number of milliseconds in total that the timer was set to run
*
* @return number of milliseconds timer was set to run
*/
public long totalCountdown() {
return mTotalCountdown;
}
/**
* Returns the number of milliseconds that have elapsed on the timer.
*
* @return the number of milliseconds that have elapsed on the timer.
*/
public long timePreplaceded() {
return mTotalCountdown - timeLeft();
}
/**
* Returns true if the timer has been started, false otherwise.
*
* @return true if the timer has been started, false otherwise.
*/
public boolean hasBeenStarted() {
return (mPauseTimeRemaining <= mMillisInFuture);
}
/**
* Callback fired on regular interval
*
* @param millisUntilFinished
* The amount of time until finished
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
private static final int MSG = 1;
// handles counting down
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownClock.this) {
long millisLeft = timeLeft();
if (millisLeft <= 0) {
cancel();
onFinish();
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = mCountdownInterval - (SystemClock.elapsedRealtime() - lastTickStart);
// special case: user's onTick took more than
// mCountdownInterval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
}
18
Source : CountDownTimer.java
with GNU General Public License v3.0
from rasheedsulayman
with GNU General Public License v3.0
from rasheedsulayman
/**
* Schedule a countdown until a time in the future, with
* regular notifications on intervals along the way.
* <p>
* Example of showing a 30 second countdown in a text field:
*
* <pre clreplaced="prettyprint">
* new CountDownTimer(30000, 1000) {
*
* public void onTick(long millisUntilFinished) {
* mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
* }
*
* public void onFinish() {
* mTextField.setText("done!");
* }
* }.start();
* </pre>
* <p>
* The calls to {@link #onTick(long)} are synchronized to this object so that
* one call to {@link #onTick(long)} won't ever occur before the previous
* callback is complete. This is only relevant when the implementation of
* {@link #onTick(long)} takes an amount of time to execute that is significant
* compared to the countdown interval.
*/
public abstract clreplaced CountDownTimer {
private static final int MSG = 1;
/**
* The interval in millis that the user receives callbacks
*/
private final long mCountdownInterval;
/**
* Millis since epoch when alarm should stop.
*/
private long mMillisInFuture;
private long mStopTimeInFuture;
/**
* boolean representing if the timer was cancelled
*/
private boolean mCancelled = false;
// handles counting down
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (this) {
if (mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart;
long delay;
if (millisLeft < mCountdownInterval) {
// just delay until done
delay = millisLeft - lastTickDuration;
// special case: user's onTick took more than interval to
// complete, trigger onFinish without delay
if (delay < 0)
delay = 0;
} else {
delay = mCountdownInterval - lastTickDuration;
// special case: user's onTick took more than interval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
}
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
/**
* @param millisInFuture The number of millis in the future from the call
* to {@link #start()} until the countdown is done and {@link #onFinish()}
* is called.
* @param countDownInterval The interval along the way to receive
* {@link #onTick(long)} callbacks.
*/
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
public CountDownTimer(long countDownInterval) {
mCountdownInterval = countDownInterval;
}
public void setMillisInFuture(long mMillisInFuture) {
this.mMillisInFuture = mMillisInFuture;
}
/**
* Cancel the countdown.
*/
public synchronized final void cancel() {
mCancelled = true;
mHandler.removeMessages(MSG);
}
/**
* Start the countdown.
*/
public synchronized final CountDownTimer start() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
/**
* Callback fired on regular interval.
*
* @param millisUntilFinished The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
}
18
Source : MainActivity.java
with GNU General Public License v3.0
from peng-zhihui
with GNU General Public License v3.0
from peng-zhihui
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
animateViews();
CheckPermissions(new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET });
// Copy models to SD card
Copyreplacedets();
}
18
Source : TerminalSession.java
with GNU General Public License v3.0
from NeoTerm
with GNU General Public License v3.0
from NeoTerm
/**
* A terminal session, consisting of a process coupled to a terminal interface.
* <p>
* The subprocess will be executed by the constructor, and when the size is made known by a call to
* {@link #updateSize(int, int)} terminal emulation will begin and threads will be spawned to handle the subprocess I/O.
* All terminal emulation and callback methods will be performed on the main thread.
* <p>
* The child process may be exited forcefully by using the {@link #finishIfRunning()} method.
* <p>
* NOTE: The terminal session may outlive the EmulatorView, so be careful with callbacks!
*/
public clreplaced TerminalSession extends TerminalOutput {
/**
* Callback to be invoked when a {@link TerminalSession} changes.
*/
public interface SessionChangedCallback {
void onTextChanged(TerminalSession changedSession);
void onreplacedleChanged(TerminalSession changedSession);
void onSessionFinished(TerminalSession finishedSession);
void onClipboardText(TerminalSession session, String text);
void onBell(TerminalSession session);
void onColorsChanged(TerminalSession session);
}
@SuppressWarnings("JavaReflectionMemberAccess")
private static FileDescriptor wrapFileDescriptor(int fileDescriptor) {
FileDescriptor result = new FileDescriptor();
try {
Field descriptorField;
try {
descriptorField = FileDescriptor.clreplaced.getDeclaredField("descriptor");
} catch (NoSuchFieldException e) {
// For desktop java:
descriptorField = FileDescriptor.clreplaced.getDeclaredField("fd");
}
descriptorField.setAccessible(true);
descriptorField.set(result, fileDescriptor);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
Log.wtf(EmulatorDebug.LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
System.exit(1);
}
return result;
}
private static final int MSG_NEW_INPUT = 1;
private static final int MSG_PROCESS_EXITED = 4;
public final String mHandle = UUID.randomUUID().toString();
private TerminalEmulator mEmulator;
/**
* A queue written to from a separate thread when the process outputs, and read by main thread to process by
* terminal emulator.
*/
private final ByteQueue mProcessToTerminalIOQueue = new ByteQueue(4096);
/**
* A queue written to from the main thread due to user interaction, and read by another thread which forwards by
* writing to the {@link #mTerminalFileDescriptor}.
*/
private final ByteQueue mTerminalToProcessIOQueue = new ByteQueue(4096);
/**
* Buffer to write translate code points into utf8 before writing to mTerminalToProcessIOQueue
*/
private final byte[] mUtf8InputBuffer = new byte[5];
public SessionChangedCallback getSessionChangedCallback() {
return mChangeCallback;
}
/**
* Callback which gets notified when a session finishes or changes replacedle.
*/
private final SessionChangedCallback mChangeCallback;
/**
* The pid of the executablePath process. 0 if not started and -1 if finished running.
*/
private int mShellPid;
/**
* The exit status of the executablePath process. Only valid if ${@link #mShellPid} is -1.
*/
private int mShellExitStatus;
/**
* The file descriptor referencing the master half of a pseudo-terminal pair, resulting from calling
* {@link JNI#createSubprocess(String, String, String[], String[], int[], int, int)}.
*/
private int mTerminalFileDescriptor;
/**
* Set by the application for user identification of session, not by terminal.
*/
public String mSessionName;
@SuppressLint("HandlerLeak")
private final Handler mMainThreadHandler = new Handler() {
final byte[] mReceiveBuffer = new byte[4 * 1024];
@Override
public void handleMessage(Message msg) {
if (msg.what == MSG_NEW_INPUT && isRunning()) {
int bytesRead = mProcessToTerminalIOQueue.read(mReceiveBuffer, false);
if (bytesRead > 0) {
mEmulator.append(mReceiveBuffer, bytesRead);
notifyScreenUpdate();
}
} else if (msg.what == MSG_PROCESS_EXITED) {
int exitCode = (Integer) msg.obj;
cleanupResources(exitCode);
mChangeCallback.onSessionFinished(TerminalSession.this);
String exitDescription = getExitDescription(exitCode);
byte[] bytesToWrite = exitDescription.getBytes(StandardCharsets.UTF_8);
mEmulator.append(bytesToWrite, bytesToWrite.length);
notifyScreenUpdate();
}
}
};
private final String mShellPath;
private final String mCwd;
private final String[] mArgs;
private final String[] mEnv;
public TerminalSession(String shellPath, String cwd, String[] args, String[] env, SessionChangedCallback changeCallback) {
mChangeCallback = changeCallback;
this.mShellPath = shellPath;
this.mCwd = cwd;
this.mArgs = args;
this.mEnv = env;
}
/**
* Inform the attached pty of the new size and reflow or initialize the emulator.
*/
public void updateSize(int columns, int rows) {
if (mEmulator == null) {
initializeEmulator(columns, rows);
} else {
JNI.setPtyWindowSize(mTerminalFileDescriptor, rows, columns);
mEmulator.resize(columns, rows);
}
}
/**
* The terminal replacedle as set through escape sequences or null if none set.
*/
public String getreplacedle() {
return (mEmulator == null) ? null : mEmulator.getreplacedle();
}
/**
* Set the terminal emulator's window size and start terminal emulation.
*
* @param columns The number of columns in the terminal window.
* @param rows The number of rows in the terminal window.
*/
public void initializeEmulator(int columns, int rows) {
mEmulator = new TerminalEmulator(this, columns, rows, /* transcript= */
2000);
int[] processId = new int[1];
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns);
mShellPid = processId[0];
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor);
new Thread("TermSessionInputReader[pid=" + mShellPid + "]") {
@Override
public void run() {
try (InputStream termIn = new FileInputStream(terminalFileDescriptorWrapped)) {
final byte[] buffer = new byte[4096];
while (true) {
int read = termIn.read(buffer);
if (read == -1)
return;
if (!mProcessToTerminalIOQueue.write(buffer, 0, read))
return;
mMainThreadHandler.sendEmptyMessage(MSG_NEW_INPUT);
}
} catch (Exception e) {
// Ignore, just shutting down.
}
}
}.start();
new Thread("TermSessionOutputWriter[pid=" + mShellPid + "]") {
@Override
public void run() {
final byte[] buffer = new byte[4096];
try (FileOutputStream termOut = new FileOutputStream(terminalFileDescriptorWrapped)) {
while (true) {
int bytesToWrite = mTerminalToProcessIOQueue.read(buffer, true);
if (bytesToWrite == -1)
return;
termOut.write(buffer, 0, bytesToWrite);
}
} catch (IOException e) {
// Ignore.
}
}
}.start();
new Thread("TermSessionWaiter[pid=" + mShellPid + "]") {
@Override
public void run() {
int processExitCode = JNI.waitFor(mShellPid);
mMainThreadHandler.sendMessage(mMainThreadHandler.obtainMessage(MSG_PROCESS_EXITED, processExitCode));
}
}.start();
}
/**
* Write data to the executablePath process.
*/
@Override
public void write(byte[] data, int offset, int count) {
if (mShellPid > 0)
mTerminalToProcessIOQueue.write(data, offset, count);
}
/**
* Write the Unicode code point to the terminal encoded in UTF-8.
*/
public void writeCodePoint(boolean prependEscape, int codePoint) {
if (codePoint > 1114111 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
// 1114111 (= 2**16 + 1024**2 - 1) is the highest code point, [0xD800,0xDFFF] is the surrogate range.
throw new IllegalArgumentException("Invalid code point: " + codePoint);
}
int bufferPosition = 0;
if (prependEscape)
mUtf8InputBuffer[bufferPosition++] = 27;
if (codePoint <= /* 7 bits */
0b1111111) {
mUtf8InputBuffer[bufferPosition++] = (byte) codePoint;
} else if (codePoint <= /* 11 bits */
0b11111111111) {
/* 110xxxxx leading byte with leading 5 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11000000 | (codePoint >> 6));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
} else if (codePoint <= /* 16 bits */
0b1111111111111111) {
/* 1110xxxx leading byte with leading 4 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11100000 | (codePoint >> 12));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
} else {
/* We have checked codePoint <= 1114111 above, so we have max 21 bits = 0b111111111111111111111 */
/* 11110xxx leading byte with leading 3 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b11110000 | (codePoint >> 18));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 12) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | ((codePoint >> 6) & 0b111111));
/* 10xxxxxx continuation byte with following 6 bits */
mUtf8InputBuffer[bufferPosition++] = (byte) (0b10000000 | (codePoint & 0b111111));
}
write(mUtf8InputBuffer, 0, bufferPosition);
}
public TerminalEmulator getEmulator() {
return mEmulator;
}
/**
* Notify the {@link #mChangeCallback} that the screen has changed.
*/
private void notifyScreenUpdate() {
mChangeCallback.onTextChanged(this);
}
/**
* Reset state for terminal emulator state.
*/
public void reset() {
mEmulator.reset();
notifyScreenUpdate();
}
/**
* Finish this terminal session by sending SIGKILL to the executablePath.
*/
public void finishIfRunning() {
if (isRunning()) {
try {
Os.kill(mShellPid, OsConstants.SIGKILL);
} catch (ErrnoException e) {
Log.w("neoterm-shell-session", "Failed sending SIGKILL: " + e.getMessage());
}
}
}
protected String getExitDescription(int exitCode) {
String exitDescription = "\r\n[Process completed";
if (exitCode > 0) {
// Non-zero process exit.
exitDescription += " (code " + exitCode + ")";
} else if (exitCode < 0) {
// Negated signal.
exitDescription += " (signal " + (-exitCode) + ")";
}
exitDescription += " - press Enter]";
return exitDescription;
}
/**
* Cleanup resources when the process exits.
*/
private void cleanupResources(int exitStatus) {
synchronized (this) {
mShellPid = -1;
mShellExitStatus = exitStatus;
}
// Stop the reader and writer threads, and close the I/O streams
mTerminalToProcessIOQueue.close();
mProcessToTerminalIOQueue.close();
JNI.close(mTerminalFileDescriptor);
}
@Override
public void replacedleChanged(String oldreplacedle, String newreplacedle) {
mChangeCallback.onreplacedleChanged(this);
}
public synchronized boolean isRunning() {
return mShellPid != -1;
}
/**
* Only valid if not {@link #isRunning()}.
*/
public synchronized int getExitStatus() {
return mShellExitStatus;
}
@Override
public void clipboardText(String text) {
mChangeCallback.onClipboardText(this, text);
}
@Override
public void onBell() {
mChangeCallback.onBell(this);
}
@Override
public void onColorsChanged() {
mChangeCallback.onColorsChanged(this);
}
public int getPid() {
return mShellPid;
}
}
18
Source : DownloaderManager.java
with Apache License 2.0
from Mp5A5
with Apache License 2.0
from Mp5A5
/**
* describe:
* author :mp5a5 on 2019/4/4 16:13
* email:[email protected]
*/
public clreplaced DownloaderManager {
private ProgressListener progressListener;
private String url;
private OkHttpClient client;
private Call call;
private Response originalResponse;
private static final int DOWNLOAD_FAIL = 0;
private static final int DOWNLOAD_UPDATE = 1;
private static final int DOWNLOAD_EXECUTE = 2;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case DOWNLOAD_FAIL:
if (progressListener != null) {
progressListener.onFail();
}
break;
case DOWNLOAD_UPDATE:
UpdateMsg updateMsg = (UpdateMsg) msg.obj;
if (progressListener != null) {
progressListener.update(updateMsg.totalBytes, updateMsg.done);
}
break;
case DOWNLOAD_EXECUTE:
if (progressListener != null) {
progressListener.onPreExecute(getProgressResponseBody().contentLength());
}
default:
break;
}
}
};
@SuppressLint("CheckResult")
public DownloaderManager(String url, ProgressListener progressListener) {
this.url = url;
this.progressListener = progressListener;
// 判断URL
// 如果项目中不想使用RxJava则自己开个线程将判断加到里面就可以了
Observable.create(new ObservableOnSubscribe<Boolean>() {
@Override
public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
if (checkURL(url)) {
e.onNext(true);
} else {
e.onNext(false);
}
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean aBoolean) throws Exception {
if (!aBoolean) {
mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
}
}
});
// 在下载、暂停后的继续下载中可复用同一个client对象
client = getProgressClient();
}
/**
* 每次下载需要新建新的Call对象
*
* @param startPoints 开始下载节点
*/
private Call newCall(long startPoints) {
Request request = new Request.Builder().url(url).header("RANGE", "bytes=" + startPoints + "-").build();
return client.newCall(request);
}
public OkHttpClient getProgressClient() {
// 拦截器,用上ProgressResponseBody
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(getProgressResponseBody()).build();
}
};
return new OkHttpClient.Builder().addNetworkInterceptor(interceptor).build();
}
private ProgressResponseBody getProgressResponseBody() {
return new ProgressResponseBody(originalResponse.body(), progressListener);
}
/**
* startsPoint 指定开始下载的点
*
* @param startPoint
*/
public void downloadStartPoint(final long startPoint) {
call = newCall(startPoint);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
downloadSave(response, startPoint);
}
});
}
public void pause() {
if (call != null) {
call.cancel();
}
}
public void cancelDownload() {
if (call != null || !call.isCanceled()) {
call.cancel();
}
if (mHandler != null) {
mHandler.removeMessages(DOWNLOAD_EXECUTE);
mHandler.removeMessages(DOWNLOAD_FAIL);
mHandler.removeMessages(DOWNLOAD_UPDATE);
}
}
private void downloadSave(Response response, long startsPoint) {
ResponseBody body = response.body();
InputStream in = Objects.requireNonNull(body).byteStream();
FileChannel channelOut = null;
// 随机访问文件,可以指定断点续传的起始位置
RandomAccessFile randomAccessFile = null;
try {
File file = DownloadFileUtils.getFileFromUrl(url);
randomAccessFile = new RandomAccessFile(file, "rwd");
// Chanel NIO中的用法,由于RandomAccessFile没有使用缓存策略,直接使用会使得下载速度变慢,亲测缓存下载3.3秒的文件,用普通的RandomAccessFile需要20多秒。
channelOut = randomAccessFile.getChannel();
// 内存映射,直接使用RandomAccessFile,是用其seek方法指定下载的起始位置,使用缓存下载,在这里指定下载位置。
MappedByteBuffer mappedBuffer = channelOut.map(FileChannel.MapMode.READ_WRITE, startsPoint, body.contentLength());
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
mappedBuffer.put(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
if (channelOut != null) {
channelOut.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean checkURL(String url) {
boolean value = false;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
int code = conn.getResponseCode();
if (code != 200) {
value = false;
} else {
value = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
private clreplaced ProgressResponseBody extends ResponseBody {
private final ResponseBody responseBody;
private final ProgressListener progressListener;
private BufferedSource bufferedSource;
private ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
this.responseBody = responseBody;
this.progressListener = progressListener;
mHandler.sendEmptyMessage(DOWNLOAD_EXECUTE);
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytes = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
totalBytes += bytesRead != -1 ? bytesRead : 0;
Message message = new Message();
UpdateMsg updateMsg = new UpdateMsg(totalBytes, bytesRead == -1);
message.what = DOWNLOAD_UPDATE;
message.obj = updateMsg;
mHandler.sendMessage(message);
return bytesRead;
}
};
}
}
/**
* 下载回调
*/
public interface ProgressListener {
/**
* 下载之前操作
*
* @param contentLength 下载的总长度
*/
void onPreExecute(long contentLength);
/**
* 下载更新
*
* @param totalBytes 下载累计长度
* @param done 是否下载完成
*/
void update(long totalBytes, boolean done);
/**
* 下载失败
*/
void onFail();
}
/**
* 下载进度
*/
private clreplaced UpdateMsg {
UpdateMsg(long totalBytes, boolean done) {
this.totalBytes = totalBytes;
this.done = done;
}
public long totalBytes;
public boolean done;
}
}
18
Source : MemoryShakeActivity.java
with MIT License
from liuhuiAndroid
with MIT License
from liuhuiAndroid
/**
* 模拟内存抖动的界面
*/
public clreplaced MemoryShakeActivity extends AppCompatActivity implements View.OnClickListener {
@SuppressLint("HandlerLeak")
private static Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 创造内存抖动
for (int index = 0; index <= 100; index++) {
String[] arg = new String[100000];
}
mHandler.sendEmptyMessageDelayed(0, 30);
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
findViewById(R.id.bt_memory).setOnClickListener(this);
}
@Override
public void onClick(View v) {
mHandler.sendEmptyMessage(0);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}
18
Source : AliPay.java
with MIT License
from kingofglory
with MIT License
from kingofglory
/**
* 文 件 名: AliPay
* 创 建 人: King
* 创建日期: 2017/2/13 17:36
* 邮 箱: [email protected]
* 博 客: www.smilevenus.com
* @see <a href="https://docs.open.alipay.com/204/">Des</a>
*/
public clreplaced AliPay implements IPayStrategy<AlipayInfoImpli> {
private static final int SDK_PAY_FLAG = 6406;
private Activity mActivity;
private AlipayInfoImpli alipayInfoImpli;
private static IPayCallback sPayCallback;
@Override
public void pay(Activity activity, AlipayInfoImpli payInfo, IPayCallback payCallback) {
this.mActivity = activity;
this.alipayInfoImpli = payInfo;
sPayCallback = payCallback;
Runnable payRunnable = new Runnable() {
@Override
public void run() {
// 构造PayTask 对象
PayTask alipay = new PayTask(mActivity);
// 调用支付接口,获取支付结果
Map<String, String> result = alipay.payV2(alipayInfoImpli.getOrderInfo(), true);
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
// 必须异步调用
Thread payThread = new Thread(payRunnable);
payThread.start();
}
@SuppressLint("HandlerLeak")
private static Handler mHandler = new Handler() {
@SuppressWarnings("unused")
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SDK_PAY_FLAG:
{
AliPayResult payResult = new AliPayResult((Map<String, String>) msg.obj);
/**
* 同步返回的结果必须放置到服务端进行验证(验证的规则请看https://doc.open.alipay.com/doc2/
* detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
* docType=1) 建议商户依赖异步通知
*/
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
// 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档:
// https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.IXE2Zj&treeId=59&articleId=103671&docType=1
if (TextUtils.equals(resultStatus, ResultCode.CODE_SUCCESS)) {
if (sPayCallback != null) {
sPayCallback.success();
}
} else if (TextUtils.equals(resultStatus, ResultCode.CODE_CANCEL)) {
if (sPayCallback != null) {
sPayCallback.cancel();
}
} else {
// 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
if (sPayCallback != null) {
sPayCallback.failed(ResultCode.getIntCodeByString(resultStatus), ResultCode.getTextByCode(resultStatus));
}
}
break;
}
default:
break;
}
}
};
}
18
Source : Pay.java
with GNU Affero General Public License v3.0
from JasonQS
with GNU Affero General Public License v3.0
from JasonQS
public clreplaced Pay {
String TAG = "Pay";
Activity activity;
private static final int SDK_PAY_FLAG = 1;
private static final int SDK_AUTH_FLAG = 2;
public Pay(Activity activity) {
this.activity = activity;
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@SuppressWarnings("unused")
public void handleMessage(Message msg) {
switch(msg.what) {
case SDK_PAY_FLAG:
{
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
/*
对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
*/
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
// 判断resultStatus 为9000则代表支付成功
if (TextUtils.equals(resultStatus, "9000")) {
// 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
} else {
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
Toast.makeText(activity, "支付失败 " + resultInfo, Toast.LENGTH_SHORT).show();
Log.i(TAG, "handleMessage: error: " + resultStatus + " " + resultInfo);
}
break;
}
case SDK_AUTH_FLAG:
{
@SuppressWarnings("unchecked")
AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
String resultStatus = authResult.getResultStatus();
// 判断resultStatus 为“9000”且result_code
// 为“200”则代表授权成功,具体状态码代表含义可参考授权接口文档
if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
// 获取alipay_open_id,调支付时作为参数external_token 的value 传入,则支付账户为该授权账户
Toast.makeText(activity, "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
} else {
// 其他状态值则为授权失败
Toast.makeText(activity, "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
}
break;
}
default:
break;
}
}
};
/**
* 支付宝支付业务
*/
public void pay(String type) {
StringRequest request = new StringRequest(Request.Method.POST, "http://ar.qsboy.com/j/pay", response -> {
Log.i(TAG, "sendMsg: " + response);
Runnable payRunnable = () -> {
PayTask alipay = new PayTask(activity);
Map<String, String> result = alipay.payV2(response, true);
Log.i("msp", result.toString());
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}, error -> Log.e(TAG, "sendMsg: " + error)) {
@Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("type", type);
return map;
}
};
RequestQueue queue = Volley.newRequestQueue(activity);
queue.add(request);
}
}
18
Source : ResultActivity.java
with Apache License 2.0
from itlwy
with Apache License 2.0
from itlwy
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
initView();
init();
}
18
Source : MyScrollView.java
with GNU General Public License v3.0
from ihewro
with GNU General Public License v3.0
from ihewro
/**
* <pre>
* author : hewro
* e-mail : [email protected]
* time : 2019/05/28
* desc :
* version: 1.0
* </pre>
*/
public clreplaced MyScrollView extends NestedScrollView {
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private int lastY = 0;
private int touchEventId = -9983761;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
View scroller = (View) msg.obj;
if (msg.what == touchEventId) {
if (lastY == scroller.getScrollY()) {
handleStop(scroller);
} else {
handler.sendMessageDelayed(handler.obtainMessage(touchEventId, scroller), 200);
lastY = scroller.getScrollY();
}
}
}
};
private int mLastX = 0;
private int mLastY = 0;
// 当前是否是上下滚动的
private boolean is_current_scroll = false;
private boolean is_vertical_scroll = false;
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
{
// ALog.d("ACTION_DOWN");
// 让父容器不拦截ACTION_DOWN事件
getParent().getParent().requestDisallowInterceptTouchEvent(true);
break;
}
case MotionEvent.ACTION_MOVE:
{
// ALog.d("ACTION_MOVE");
int deltaX = x - mLastX;
int deltaY = y - mLastY;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
// 水平滑动
// ALog.d("水平滑动");
if (!is_current_scroll) {
// 如果水平方向滑动的距离多一点,那就表示让父容器水平滑动,子控件不滑动,让父容器拦截、消费事件
getParent().getParent().requestDisallowInterceptTouchEvent(false);
}
} else {
// 上下滑动
is_current_scroll = true;
// ALog.d("上下滑动");
}
break;
}
case MotionEvent.ACTION_UP:
{
// 水平滑动的时候,没有这个事件,因为被上级recyclerview消费掉了
// ALog.d("ACTION_UP");
is_current_scroll = false;
handler.sendMessageDelayed(handler.obtainMessage(touchEventId, MyScrollView.this), 5);
break;
}
default:
break;
}
mLastX = x;
mLastY = y;
return super.dispatchTouchEvent(event);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
is_current_scroll = true;
/* if ((t-oldt) > 1){
is_current_scroll = true;
}else {
is_current_scroll = false;
}*/
// ALog.d("上下滑动距离"+(t-oldt));
}
// 这里写真正的事件
private void handleStop(Object view) {
// ALog.d("停止滑动了");
is_current_scroll = false;
/*ScrollView scroller = (ScrollView) view;
System.out.println(scroller.getScrollY());
System.out.println(scroller.getHeight());*/
// Do Something
}
}
18
Source : OnlineMusicActivity.java
with GNU General Public License v3.0
from Hui4401
with GNU General Public License v3.0
from Hui4401
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onlinemusic);
// 初始化
initActivity();
mainHanlder = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case 60:
// 更新一首歌曲
Music music = (Music) msg.obj;
onlinemusic_list.add(music);
adapter.notifyDataSetChanged();
musicCountView.setText("播放全部(共" + onlinemusic_list.size() + "首)");
break;
}
}
};
// 列表项点击事件
musicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Music music = onlinemusic_list.get(position);
serviceBinder.addPlayList(music);
}
});
// 列表项中更多按钮的点击事件
adapter.setOnMoreButtonListener(new MusicAdapter.onMoreButtonListener() {
@Override
public void onClick(final int i) {
final Music music = onlinemusic_list.get(i);
final String[] items = new String[] { "收藏到我的音乐", "添加到播放列表", "删除" };
AlertDialog.Builder builder = new AlertDialog.Builder(OnlineMusicActivity.this);
builder.setreplacedle(music.replacedle + "-" + music.artist);
builder.sereplacedems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which) {
case 0:
MainActivity.addMymusic(music);
break;
case 1:
serviceBinder.addPlayList(music);
break;
case 2:
// 从列表中删除
onlinemusic_list.remove(i);
adapter.notifyDataSetChanged();
musicCountView.setText("播放全部(共" + onlinemusic_list.size() + "首)");
break;
}
}
});
builder.create().show();
}
});
}
18
Source : ImageLoadUtil.java
with MIT License
from hubcarl
with MIT License
from hubcarl
@SuppressLint("HandlerLeak")
public clreplaced ImageLoadUtil {
// 磁盘缓存的两种限制方式: 限制最大的条数,限制最大的体积
public static final int MAX_DISK_CACHE_FILE_COUNT = 100;
public static final int MAX_DISK_CACHE_FILE_SIZE = 30 * 1024 * 1024;
public static final int MAX_POOL_THREAD_SIZE = 5;
public static ImageLoader imageLoader = null;
public enum ImageStyle {
CIRCLE_MEMBER, USER_MEMBER, PHOTO, BIG_LOGO
}
public static ImageLoader getInstance() {
return imageLoader;
}
// 初始化 图片加载器
public static void configuration(Context context) {
if (imageLoader == null) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().discCacheSize(MAX_DISK_CACHE_FILE_SIZE).discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
}
}
/**
* 构造图片显示的配置选项
*
* @param placeHolderImgRes 默认的占位显示图片
* @param emptyUrlImgRes 空链接显示的图片
* @param failedImgRes 加载失败显示的图片
* @param cacheInMemory 是否内存缓存,图片过大,建议不要内存缓存
* @return
*/
private static DisplayImageOptions constructDisplayOption(String url, int placeHolderImgRes, int emptyUrlImgRes, int failedImgRes, boolean cacheInMemory, BitmapDisplayer displayer) {
DisplayImageOptions.Builder bulider = new DisplayImageOptions.Builder();
// 默认开启磁盘缓存 缓存在默认位置
bulider.cacheOnDisc(true);
// /sdcard/Android/data/[package_name]/cache
bulider.cacheInMemory(cacheInMemory);
bulider.resetViewBeforeLoading(true);
bulider.bitmapConfig(Bitmap.Config.RGB_565);
// bulider.displayer(new FadeInBitmapDisplayer(200));//加载动画
if (displayer != null) {
bulider.displayer(displayer);
}
if (placeHolderImgRes > 0) {
bulider.showStubImage(placeHolderImgRes);
}
if (emptyUrlImgRes > 0) {
bulider.showImageForEmptyUri(emptyUrlImgRes);
}
if (failedImgRes > 0) {
bulider.showImageOnFail(failedImgRes);
}
return bulider.build();
}
/**
* *
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* 默认的占位显示图片
*/
public static void loadImage(ImageView imageView, String url, ImageStyle imageStyle) {
int loadImageRes = 0;
if (imageStyle == ImageStyle.USER_MEMBER) {
loadImageRes = R.drawable.ic_launcher;
} else if (imageStyle == ImageStyle.CIRCLE_MEMBER) {
loadImageRes = R.drawable.ic_launcher;
} else if (imageStyle == ImageStyle.PHOTO) {
loadImageRes = R.drawable.ic_launcher;
} else if (imageStyle == ImageStyle.BIG_LOGO) {
loadImageRes = R.drawable.bg_video_big;
}
loadImage(imageView, url, loadImageRes);
}
public static void loadImageByResId(ImageView imageView, String url, int resId) {
loadImage(imageView, url, resId);
}
/**
* 加载显示图片
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* @param placeHolderImg 默认的占位显示图片
*/
public static void loadImage(ImageView imageView, String url, int placeHolderImg) {
loadImage(imageView, url, placeHolderImg, true);
}
/**
* 加载显示图片
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* @param placeHolderImg 默认的占位显示图片
* @param cacheInMemory 是否将图片缓存到内存中(大图不建议缓存到内存中)
*/
public static void loadImage(ImageView imageView, String url, int placeHolderImg, boolean cacheInMemory) {
loadImage(imageView, url, placeHolderImg, 0, 0, cacheInMemory, null);
}
public static void loadRoundImage(ImageView imageView, String url, int defaultImg) {
loadImage(imageView, url, defaultImg, 0, 0, true, new RoundedBitmapDisplayer(5));
}
/**
* 加载显示图片
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* @param placeHolderImg 默认的占位显示图片
* @param emptyUrlImgRes 空链接显示的图片,不定义请置 0
* @param failedImgRes 加载失败显示的图片,不定义请置 0
* @param cacheInMemory 是否将图片缓存到内存中 (大图不建议缓存到内存中)
*/
public static void loadImage(ImageView imageView, String url, int placeHolderImg, int emptyUrlImgRes, int failedImgRes, boolean cacheInMemory, BitmapDisplayer displayer) {
DisplayImageOptions option = constructDisplayOption(url, placeHolderImg, emptyUrlImgRes, failedImgRes, cacheInMemory, displayer);
if (Strings.isEmpty(url) || (!url.endsWith(".jpg") && !url.endsWith(".jpeg") && !url.endsWith(".png") && !url.endsWith(".JPG") && !url.endsWith(".JPEG") && !url.endsWith(".PNG"))) {
if (placeHolderImg != 0) {
imageView.setImageResource(placeHolderImg);
}
return;
}
imageLoader.displayImage(url, imageView, option);
}
/**
* 单纯缓存下来先,下次再用
*
* @param url
*/
public static void loadImage(String url) {
imageLoader.loadImage(url, null);
}
/**
* 尝试获取图片资源
*
* @param url
* @return
*/
private static boolean connectImageUrl(String url) {
try {
// 创建URL对象。
URL imageUrl = new URL(url);
// 创建一个连接对象。
URLConnection uc = imageUrl.openConnection();
// 获取连接对象输入字节流。如果地址无效则会抛出异常。
InputStream in = uc.getInputStream();
in.close();
return true;
} catch (Exception e) {
Log.e("connectImageUrl", "图片资源" + url + "不存在");
return false;
}
}
public static String getPath4Url(Context context, String url) {
File file = StorageUtils.getIndividualCacheDirectory(context);
String filePath = file.getAbsolutePath() + "/" + getName4Url(url);
return filePath;
}
public static String getName4Url(String url) {
return new Md5FileNameGenerator().generate(url);
}
}
18
Source : ImageLoadUtil.java
with MIT License
from hubcarl
with MIT License
from hubcarl
@SuppressLint("HandlerLeak")
public clreplaced ImageLoadUtil {
// 磁盘缓存的两种限制方式: 限制最大的条数,限制最大的体积
public static final int MAX_DISK_CACHE_FILE_COUNT = 100;
public static final int MAX_DISK_CACHE_FILE_SIZE = 30 * 1024 * 1024;
public static final int MAX_POOL_THREAD_SIZE = 5;
public static ImageLoader imageLoader = null;
public enum ImageStyle {
CIRCLE_MEMBER, USER_MEMBER, PHOTO
}
public static ImageLoader getInstance() {
return imageLoader;
}
// 初始化 图片加载器
public static void configuration(Context context) {
if (imageLoader == null) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().discCacheSize(MAX_DISK_CACHE_FILE_SIZE).discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
}
}
/**
* 构造图片显示的配置选项
*
* @param placeHolderImgRes 默认的占位显示图片
* @param emptyUrlImgRes 空链接显示的图片
* @param failedImgRes 加载失败显示的图片
* @param cacheInMemory 是否内存缓存,图片过大,建议不要内存缓存
* @return
*/
private static DisplayImageOptions constructDisplayOption(String url, int placeHolderImgRes, int emptyUrlImgRes, int failedImgRes, boolean cacheInMemory, BitmapDisplayer displayer) {
DisplayImageOptions.Builder bulider = new DisplayImageOptions.Builder();
// 默认开启磁盘缓存 缓存在默认位置
bulider.cacheOnDisc(true);
// /sdcard/Android/data/[package_name]/cache
bulider.cacheInMemory(cacheInMemory);
bulider.resetViewBeforeLoading(true);
bulider.bitmapConfig(Bitmap.Config.RGB_565);
// bulider.displayer(new FadeInBitmapDisplayer(200));//加载动画
if (displayer != null) {
bulider.displayer(displayer);
}
if (placeHolderImgRes > 0) {
bulider.showStubImage(placeHolderImgRes);
}
if (emptyUrlImgRes > 0) {
bulider.showImageForEmptyUri(emptyUrlImgRes);
}
if (failedImgRes > 0) {
bulider.showImageOnFail(failedImgRes);
}
return bulider.build();
}
/**
* *
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* 默认的占位显示图片
*/
public static void loadImage(ImageView imageView, String url, ImageStyle imageStyle) {
int loadImageRes = 0;
if (imageStyle == ImageStyle.USER_MEMBER) {
loadImageRes = R.drawable.ic_launcher;
} else if (imageStyle == ImageStyle.CIRCLE_MEMBER) {
loadImageRes = R.drawable.ic_launcher;
} else if (imageStyle == ImageStyle.PHOTO) {
loadImageRes = R.drawable.ic_launcher;
}
loadImage(imageView, url, loadImageRes);
}
public static void loadImageByResId(ImageView imageView, String url, int resId) {
loadImage(imageView, url, resId);
}
/**
* 加载显示图片
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* @param placeHolderImg 默认的占位显示图片
*/
public static void loadImage(ImageView imageView, String url, int placeHolderImg) {
loadImage(imageView, url, placeHolderImg, true);
}
/**
* 加载显示图片
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* @param placeHolderImg 默认的占位显示图片
* @param cacheInMemory 是否将图片缓存到内存中(大图不建议缓存到内存中)
*/
public static void loadImage(ImageView imageView, String url, int placeHolderImg, boolean cacheInMemory) {
loadImage(imageView, url, placeHolderImg, 0, 0, cacheInMemory, null);
}
/**
* 绘制圆形头像 0表示没有边框
*
* @param imageView
* @param url
* @param color 请用getresrouce.getcolor
*/
public static void loadCircleImage(ImageView imageView, String url, int color) {
loadImage(imageView, url, R.drawable.icon_default_avatar, 0, 0, true, new CircleDisplayer(color));
}
public static void loadRoundImage(ImageView imageView, String url, int defaultImg) {
loadImage(imageView, url, defaultImg, 0, 0, true, new RoundedBitmapDisplayer(5));
}
/**
* 加载显示图片
*
* @param imageView 显示图片的组件
* @param url 图片加载的URL
* @param placeHolderImg 默认的占位显示图片
* @param emptyUrlImgRes 空链接显示的图片,不定义请置 0
* @param failedImgRes 加载失败显示的图片,不定义请置 0
* @param cacheInMemory 是否将图片缓存到内存中 (大图不建议缓存到内存中)
*/
public static void loadImage(ImageView imageView, String url, int placeHolderImg, int emptyUrlImgRes, int failedImgRes, boolean cacheInMemory, BitmapDisplayer displayer) {
DisplayImageOptions option = constructDisplayOption(url, placeHolderImg, emptyUrlImgRes, failedImgRes, cacheInMemory, displayer);
if (Strings.isEmpty(url) || (!url.endsWith(".jpg") && !url.endsWith(".jpeg") && !url.endsWith(".png") && !url.endsWith(".JPG") && !url.endsWith(".JPEG") && !url.endsWith(".PNG"))) {
if (placeHolderImg != 0) {
imageView.setImageResource(placeHolderImg);
}
return;
}
imageLoader.displayImage(url, imageView, option);
}
/**
* 单纯缓存下来先,下次再用
*
* @param url
*/
public static void loadImage(String url) {
imageLoader.loadImage(url, null);
}
/**
* 尝试获取图片资源
*
* @param url
* @return
*/
private static boolean connectImageUrl(String url) {
try {
// 创建URL对象。
URL imageUrl = new URL(url);
// 创建一个连接对象。
URLConnection uc = imageUrl.openConnection();
// 获取连接对象输入字节流。如果地址无效则会抛出异常。
InputStream in = uc.getInputStream();
in.close();
return true;
} catch (Exception e) {
Log.e("connectImageUrl", "图片资源" + url + "不存在");
return false;
}
}
public static String getPath4Url(Context context, String url) {
File file = StorageUtils.getIndividualCacheDirectory(context);
String filePath = file.getAbsolutePath() + "/" + getName4Url(url);
return filePath;
}
public static String getName4Url(String url) {
return new Md5FileNameGenerator().generate(url);
}
}
18
Source : WXCircleViewPager.java
with MIT License
from erguotou520
with MIT License
from erguotou520
/**
*/
@SuppressLint("HandlerLeak")
public clreplaced WXCircleViewPager extends ViewPager implements WXGestureObservable {
private WXGesture wxGesture;
private boolean isAutoScroll;
private long intervalTime = 3 * 1000;
private WXSmoothScroller mScroller;
private boolean needLoop = true;
private boolean scrollable = true;
private int mState = ViewPager.SCROLL_STATE_IDLE;
private Runnable scrollAction = new Runnable() {
@Override
public void run() {
// don't override ViewPager#setCurrenreplacedem(int item, bool smoothScroll)
WXLogUtils.d("[CircleViewPager] trigger auto play action");
superSetCurrenreplacedem(WXCircleViewPager.super.getCurrenreplacedem() + 1, true);
removeCallbacks(this);
postDelayed(this, intervalTime);
}
};
@SuppressLint("NewApi")
public WXCircleViewPager(Context context) {
super(context);
init();
}
private void init() {
setOverScrollMode(View.OVER_SCROLL_NEVER);
addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
mState = state;
WXCirclePageAdapter adapter = getCirclePageAdapter();
int currenreplacedemInternal = WXCircleViewPager.super.getCurrenreplacedem();
if (needLoop && state == ViewPager.SCROLL_STATE_IDLE && adapter.getCount() > 1) {
if (currenreplacedemInternal == adapter.getCount() - 1) {
superSetCurrenreplacedem(1, false);
} else if (currenreplacedemInternal == 0) {
superSetCurrenreplacedem(adapter.getCount() - 2, false);
}
}
}
});
postInitViewPager();
}
/**
* Override the Scroller instance with our own clreplaced so we can change the
* duration
*/
private void postInitViewPager() {
if (isInEditMode()) {
return;
}
try {
Field scroller = ViewPager.clreplaced.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = ViewPager.clreplaced.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new WXSmoothScroller(getContext(), (Interpolator) interpolator.get(null));
scroller.set(this, mScroller);
} catch (Exception e) {
WXLogUtils.e("[CircleViewPager] postInitViewPager: ", e);
}
}
@SuppressLint("NewApi")
public WXCircleViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
public int getCurrenreplacedem() {
return getRealCurrenreplacedem();
}
public int superGetCurrenreplacedem() {
return super.getCurrenreplacedem();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!scrollable) {
return true;
}
boolean result = super.onTouchEvent(ev);
if (wxGesture != null) {
result |= wxGesture.onTouch(this, ev);
}
return result;
}
@Override
public void scrollTo(int x, int y) {
if (scrollable || mState != ViewPager.SCROLL_STATE_DRAGGING) {
super.scrollTo(x, y);
}
}
/**
* Start auto scroll. Must be called after {@link #setAdapter(PagerAdapter)}
*/
public void startAutoScroll() {
isAutoScroll = true;
removeCallbacks(scrollAction);
postDelayed(scrollAction, intervalTime);
}
public void pauseAutoScroll() {
removeCallbacks(scrollAction);
}
/**
* Stop auto scroll.
*/
public void stopAutoScroll() {
isAutoScroll = false;
removeCallbacks(scrollAction);
}
public boolean isAutoScroll() {
return isAutoScroll;
}
@Override
public void setCurrenreplacedem(int item) {
setRealCurrenreplacedem(item);
}
/**
* @return the circlePageAdapter
*/
public WXCirclePageAdapter getCirclePageAdapter() {
return (WXCirclePageAdapter) getAdapter();
}
/**
* @param circlePageAdapter the circlePageAdapter to set
*/
public void setCirclePageAdapter(WXCirclePageAdapter circlePageAdapter) {
this.setAdapter(circlePageAdapter);
}
/**
* Get auto scroll interval. The time unit is micro second.
* The default time interval is 3000 micro second
* @return the intervalTime
*/
public long getIntervalTime() {
return intervalTime;
}
/**
* Set auto scroll interval. The time unit is micro second.
* The default time interval is 3000 micro second
* @param intervalTime the intervalTime to set
*/
public void setIntervalTime(long intervalTime) {
this.intervalTime = intervalTime;
}
public void setCircle(boolean circle) {
needLoop = circle;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch(ev.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
removeCallbacks(scrollAction);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (isAutoScroll()) {
postDelayed(scrollAction, intervalTime);
}
break;
}
return super.dispatchTouchEvent(ev);
}
public void destory() {
}
@Override
public void registerGestureListener(WXGesture wxGesture) {
this.wxGesture = wxGesture;
}
public int getRealCurrenreplacedem() {
int i = super.getCurrenreplacedem();
return ((WXCirclePageAdapter) getAdapter()).getRealPosition(i);
}
private void setRealCurrenreplacedem(int item) {
superSetCurrenreplacedem(((WXCirclePageAdapter) getAdapter()).getFirst() + item, false);
}
private void superSetCurrenreplacedem(int item, boolean smooth) {
try {
super.setCurrenreplacedem(item, smooth);
} catch (IllegalStateException e) {
WXLogUtils.e(e.toString());
if (getAdapter() != null) {
getAdapter().notifyDataSetChanged();
super.setCurrenreplacedem(item, smooth);
}
}
}
public int getRealCount() {
return ((WXCirclePageAdapter) getAdapter()).getRealCount();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (IllegalStateException e) {
WXLogUtils.e(e.toString());
if (getAdapter() != null) {
getAdapter().notifyDataSetChanged();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
public boolean isScrollable() {
return scrollable;
}
public void setScrollable(boolean scrollable) {
this.scrollable = scrollable;
}
}
18
Source : AliPayTools.java
with Apache License 2.0
from duboAndroid
with Apache License 2.0
from duboAndroid
public clreplaced AliPayTools {
private static final int SDK_PAY_FLAG = 1;
private static OnRequestListener sOnRequestListener;
@SuppressLint("HandlerLeak")
private static Handler mHandler = new Handler() {
@SuppressWarnings("unused")
public void handleMessage(Message msg) {
switch(msg.what) {
case SDK_PAY_FLAG:
{
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
// 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
// 判断resultStatus 为9000则代表支付成功
if (TextUtils.equals(resultStatus, "9000")) {
sOnRequestListener.onSuccess(resultStatus);
} else {
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
sOnRequestListener.onError(resultStatus);
}
break;
}
default:
break;
}
}
};
public static void aliPay(final Activity activity, String appid, boolean isRsa2, String alipay_rsa_private, AliPayModel aliPayModel, OnRequestListener onRxHttp1) {
sOnRequestListener = onRxHttp1;
Map<String, String> params = AliPayOrderInfoUtil.buildOrderParamMap(appid, isRsa2, aliPayModel.getOut_trade_no(), aliPayModel.getName(), aliPayModel.getMoney(), aliPayModel.getDetail());
String orderParam = AliPayOrderInfoUtil.buildOrderParam(params);
String privateKey = alipay_rsa_private;
String sign = AliPayOrderInfoUtil.getSign(params, privateKey, isRsa2);
final String orderInfo = orderParam + "&" + sign;
Runnable payRunnable = new Runnable() {
@Override
public void run() {
PayTask alipay = new PayTask(activity);
Map<String, String> result = alipay.payV2(orderInfo, true);
Log.i("msp", result.toString());
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}
}
18
Source : AsynAdapterHelper.java
with Apache License 2.0
from crazysunj
with Apache License 2.0
from crazysunj
/**
* @author: sunjian
* created on: 2017/4/1
* description:
* 异步适配器,数据差异的计算在子线程完成,避免不必要的数据量过大计算而引起的ANR,如果计算时间过长可考虑直接刷新全部数据
* 刷新全部数据时注意,不可改变mData的引用,不然刷新无效
*/
public clreplaced AsynAdapterHelper<T extends MulreplacedypeEnreplacedy> extends RecyclerViewAdapterHelper<T> {
private static final int HANDLE_DATA_UPDATE = 1;
protected ExecutorService mExecutor = Executors.newSingleThreadExecutor();
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
if (msg.what == HANDLE_DATA_UPDATE) {
DiffUtil.DiffResult diffResult = (DiffUtil.DiffResult) msg.obj;
handleResult(diffResult);
}
}
};
public AsynAdapterHelper() {
}
public AsynAdapterHelper(int mode) {
super(mode);
}
@Override
protected void startRefresh(HandleBase<T> refreshData) {
mExecutor.execute(new HandleTask(refreshData));
}
@Override
public void release() {
if (!mExecutor.isShutdown()) {
mExecutor.shutdown();
}
super.release();
}
/**
* 重置刷新队列
*/
public void reset() {
clearQueue();
}
private final clreplaced HandleTask implements Runnable {
private HandleBase<T> mHandleBase;
HandleTask(HandleBase<T> handleBase) {
mHandleBase = handleBase;
}
@Override
public void run() {
final List<T> newData = mHandleBase.getNewData();
final T newHeader = mHandleBase.getNewHeader();
final T newFooter = mHandleBase.getNewFooter();
final int refreshType = mHandleBase.getRefreshType();
final int level = mHandleBase.getLevel();
DiffUtil.DiffResult result = handleRefresh(newData, newHeader, newFooter, level, refreshType);
Message message = mHandler.obtainMessage(HANDLE_DATA_UPDATE);
message.obj = result;
message.sendToTarget();
}
}
}
18
Source : SendMailUtil.java
with Apache License 2.0
from AndroidCoderPeng
with Apache License 2.0
from AndroidCoderPeng
/**
* @author: Pengxh
* @email: [email protected]
* @description: TODO
* @date: 2020/1/16 15:39
*/
public clreplaced SendMailUtil {
public static void send(String toAddress, String emailMessage) {
new Thread(() -> {
new MailSender().sendTextMail(createMail(toAddress, emailMessage));
}).start();
}
static void sendAttachFileEmail(String toAddress, String filePath) {
File file = new File(filePath);
if (!file.exists()) {
EasyToast.showToast("打卡记录不存在,请检查", EasyToast.ERROR);
return;
}
new Thread(() -> {
boolean isSendSuccess = new MailSender().sendAccessoryMail(createAttachMail(toAddress, file));
if (isSendSuccess) {
handler.sendEmptyMessage(0);
} else {
handler.sendEmptyMessage(1);
}
}).start();
}
@SuppressLint("HandlerLeak")
private static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case 0:
EasyToast.showToast("导出到邮箱成功", EasyToast.SUCCESS);
break;
case 1:
EasyToast.showToast("导出到邮箱失败", EasyToast.ERROR);
break;
}
}
};
@NonNull
private static MailInfo createMail(String toAddress, String emailMessage) {
MailInfo mailInfo = new MailInfo();
// 发送方邮箱服务器
mailInfo.setMailServerHost("smtp.qq.com");
// 发送方邮箱端口号
mailInfo.setMailServerPort("587");
mailInfo.setValidate(true);
// 发送者邮箱地址
mailInfo.setUserName("[email protected]");
// 邮箱授权码,不是密码
mailInfo.setPreplacedword("gqvwykjvpnvfbjid");
// 接收者邮箱
mailInfo.setToAddress(toAddress);
// 发送者邮箱
mailInfo.setFromAddress("[email protected]");
// 邮件主题
mailInfo.setSubject("自动打卡通知");
if (emailMessage.equals("")) {
// 邮件文本
mailInfo.setContent("未监听到打卡成功的通知,请手动登录检查" + TimeOrDateUtil.timestampToDate(System.currentTimeMillis()));
} else {
// 邮件文本
mailInfo.setContent(emailMessage);
}
return mailInfo;
}
@NonNull
private static MailInfo createAttachMail(String toAddress, File file) {
MailInfo mailInfo = new MailInfo();
// 发送方邮箱服务器
mailInfo.setMailServerHost("smtp.qq.com");
// 发送方邮箱端口号
mailInfo.setMailServerPort("587");
mailInfo.setValidate(true);
// 发送者邮箱地址
mailInfo.setUserName("[email protected]");
// 邮箱授权码,不是密码
mailInfo.setPreplacedword("gqvwykjvpnvfbjid");
// 接收者邮箱
mailInfo.setToAddress(toAddress);
// 发送者邮箱
mailInfo.setFromAddress("[email protected]");
// 邮件主题
mailInfo.setSubject("打卡记录");
mailInfo.setAttachFile(file);
return mailInfo;
}
}
18
Source : WelcomeActivity.java
with Apache License 2.0
from AndroidCoderPeng
with Apache License 2.0
from AndroidCoderPeng
public clreplaced WelcomeActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
private static final int PERMISSIONS_CODE = 999;
private static final String[] USER_PERMISSIONS = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE };
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 判断是否有权限,如果版本大于5.1才需要判断(即6.0以上),其他则不需要判断。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission(this, USER_PERMISSIONS)) {
startMainActivity();
} else {
new PermissionDialog.Builder().setContext(this).setPermission(USER_PERMISSIONS).setOnDialogClickListener(new PermissionDialog.onDialogClickListener() {
@Override
public void onButtonClick() {
EasyPermissions.requestPermissions(WelcomeActivity.this, "需要获取相关权限", PERMISSIONS_CODE, USER_PERMISSIONS);
}
@Override
public void onCancelClick() {
EasyToast.showToast("用户取消授权", EasyToast.WARING);
}
}).build().show();
}
} else {
startMainActivity();
}
}
private boolean checkPermission(Activity mActivity, String[] perms) {
return EasyPermissions.hasPermissions(mActivity, perms);
}
private void startMainActivity() {
startActivity(new Intent(this, MainActivity.clreplaced));
finish();
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
startMainActivity();
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
if (perms.size() == USER_PERMISSIONS.length) {
// 授权全部失败,则提示用户
EasyToast.showToast("授权失败", EasyToast.ERROR);
handler.sendEmptyMessageDelayed(1, 1500);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// 将请求结果传递EasyPermission库处理
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
finish();
}
super.handleMessage(msg);
}
};
}
17
Source : QPMFloatViewSimpleComponent.java
with Apache License 2.0
from ZhuoKeTeam
with Apache License 2.0
from ZhuoKeTeam
/**
* 精简模式
*/
public clreplaced QPMFloatViewSimpleComponent extends QPMFloatViewBaseComponent {
private LinearLayout containerLayout;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler();
@Override
public void onCreate(final Context context) {
super.onCreate(context);
addCallback();
}
private void addCallback() {
QPMCallBackManager.getInstance().addCallBack(new IreplacedysisCallback() {
@Override
public void refreshInfo(String type, final QPMRreplacedysisResult replacedysisResult) {
refrereplacedemViewToFloatView();
}
});
}
private void refrereplacedemViewToFloatView() {
mHandler.post(new Runnable() {
@Override
public void run() {
QPMFloatViewManager.getInstance().rendererFloatViewBean();
}
});
}
@Override
public void refreshContainerLayout() {
containerLayout.removeAllViews();
List<IFloatViewRenderer> items = QPMFloatViewManager.getInstance().gereplacedems();
for (IFloatViewRenderer item : items) {
if (item.isShow()) {
containerLayout.addView(item.getView());
}
}
}
@Override
public void onDestroy(Context context) {
super.onDestroy(context);
containerLayout.removeAllViews();
mHandler.removeCallbacksAndMessages(null);
QPMCallBackManager.getInstance().removeAllCallBack();
}
@Override
protected View getLayout(final Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.jm_gt_layout_float_view_simple, null);
containerLayout = view.findViewById(R.id.ll_container);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, QPMMainMenuActivity.clreplaced);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
return view;
}
}
17
Source : QPMFloatViewCustomComponent.java
with Apache License 2.0
from ZhuoKeTeam
with Apache License 2.0
from ZhuoKeTeam
/**
* 自定义模式
*/
public clreplaced QPMFloatViewCustomComponent extends QPMFloatViewBaseComponent {
private LinearLayout containerLayout;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler();
@Override
public void onCreate(final Context context) {
super.onCreate(context);
addCallback();
}
private void addCallback() {
QPMCallBackManager.getInstance().addCallBack(new IreplacedysisCallback() {
@Override
public void refreshInfo(String type, final QPMRreplacedysisResult replacedysisResult) {
refrereplacedemViewToFloatView();
}
});
}
private void refrereplacedemViewToFloatView() {
mHandler.post(new Runnable() {
@Override
public void run() {
QPMFloatViewManager.getInstance().rendererFloatViewBean();
}
});
}
@Override
public void refreshContainerLayout() {
containerLayout.removeAllViews();
List<IFloatViewRenderer> items = QPMFloatViewManager.getInstance().gereplacedems();
for (IFloatViewRenderer item : items) {
if (item.isShow()) {
containerLayout.addView(item.getView());
}
}
}
@Override
public void onDestroy(Context context) {
super.onDestroy(context);
containerLayout.removeAllViews();
mHandler.removeCallbacksAndMessages(null);
QPMCallBackManager.getInstance().removeAllCallBack();
}
@Override
protected View getLayout(final Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.jm_gt_layout_float_view, null);
ImageView jmIcon = view.findViewById(R.id.jm_icon);
jmIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, QPMMainMenuActivity.clreplaced);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
containerLayout = view.findViewById(R.id.ll_container);
return view;
}
}
17
Source : M3u8InfoManger.java
with Apache License 2.0
from yangchong211
with Apache License 2.0
from yangchong211
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/11/9
* desc : 获取M3U8信息的管理器
* revise:
* </pre>
*/
public clreplaced M3u8InfoManger {
private static M3u8InfoManger mM3U8InfoManger;
private OnM3u8InfoListener onM3U8InfoListener;
private static final int WHAT_ON_ERROR = 1101;
private static final int WHAT_ON_SUCCESS = 1102;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case WHAT_ON_ERROR:
onM3U8InfoListener.onError((Throwable) msg.obj);
break;
case WHAT_ON_SUCCESS:
onM3U8InfoListener.onSuccess((M3u8) msg.obj);
break;
}
}
};
private M3u8InfoManger() {
}
public static M3u8InfoManger getInstance() {
synchronized (M3u8InfoManger.clreplaced) {
if (mM3U8InfoManger == null) {
mM3U8InfoManger = new M3u8InfoManger();
}
}
return mM3U8InfoManger;
}
/**
* 获取m3u8信息
*
* @param url
* @param onM3U8InfoListener
*/
public synchronized void getM3U8Info(final String url, OnM3u8InfoListener onM3U8InfoListener) {
this.onM3U8InfoListener = onM3U8InfoListener;
onM3U8InfoListener.onStart();
new Thread() {
@Override
public void run() {
try {
// Log.e("hdltag", "run(M3U8InfoManger.java:62):" + url);
M3u8 m3u8 = M3u8FileUtils.parseIndex(url);
handlerSuccess(m3u8);
} catch (IOException e) {
// e.printStackTrace();
handlerError(e);
}
}
}.start();
}
/**
* 通知异常
*
* @param e
*/
private void handlerError(Throwable e) {
Message msg = mHandler.obtainMessage();
msg.obj = e;
msg.what = WHAT_ON_ERROR;
mHandler.sendMessage(msg);
}
/**
* 通知成功
*
* @param m3u8
*/
private void handlerSuccess(M3u8 m3u8) {
Message msg = mHandler.obtainMessage();
msg.obj = m3u8;
msg.what = WHAT_ON_SUCCESS;
mHandler.sendMessage(msg);
}
}
17
Source : Test3Fragment.java
with Apache License 2.0
from yangchong211
with Apache License 2.0
from yangchong211
public clreplaced Test3Fragment extends BaseStateFragment {
private static final int LOADING = 1;
private static final int CONTENT = 2;
private List<String> lists = new ArrayList<>();
private RecyclerAdapter adapter;
private int size;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case LOADING:
showLoading();
break;
case CONTENT:
showContent();
break;
default:
break;
}
}
};
@Override
public void onDestroy() {
super.onDestroy();
if (handler != null) {
handler.removeCallbacksAndMessages(null);
handler = null;
}
}
@Override
protected void initStatusLayout() {
statusLayoutManager = StateLayoutManager.newBuilder(activity, true).contentView(R.layout.base_recycler_view).build();
showContent();
StateViewLayout.debug(BuildConfig.DEBUG);
StateViewLayout.initDefault(new GlobalAdapter());
DisplayMetrics dm = getResources().getDisplayMetrics();
size = dm.widthPixels >> 1;
}
@Override
public void initView(View view) {
RecyclerView recyclerView = view.findViewById(R.id.recycleView);
GridLayoutManager layoutManager = new GridLayoutManager(activity, 2);
layoutManager.setOrientation(OrientationHelper.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL));
recyclerView.sereplacedemAnimator(new DefaulreplacedemAnimator());
adapter = new RecyclerAdapter(initData());
recyclerView.setAdapter(adapter);
}
@Override
public void initListener() {
}
private List<String> initData() {
int size = 20;
List<String> list = new ArrayList<>(size + 4);
list.add("");
list.add(getRandomImage());
list.add(getRandomImage());
list.add(getErrorImage());
for (int i = 0; i < size; i++) {
list.add(getRandomImage());
}
return list;
}
clreplaced RecyclerAdapter extends RecyclerView.Adapter<ViewHolder> {
List<String> list;
RecyclerAdapter(List<String> list) {
this.list = list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ImageView imageView = new ImageView(parent.getContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(size, size));
StateViewLayout.Holder holder = StateViewLayout.getDefault().wrap(imageView);
holder.withData(Constants.HIDE_LOADING_STATUS_MSG);
return new ViewHolder(holder, imageView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.showImage(list.get(position));
}
@Override
public int gereplacedemCount() {
return list.size();
}
}
clreplaced ViewHolder extends RecyclerView.ViewHolder implements Runnable {
private StateViewLayout.Holder holder;
ImageView imageView;
private String curUrl;
ViewHolder(StateViewLayout.Holder holder, ImageView imageView) {
super(holder.getWrapper());
this.imageView = imageView;
this.holder = holder;
this.holder.withRetry(this);
}
void showImage(String url) {
curUrl = url;
holder.showLoading();
Glide.with(activity).load(url).listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.showLoadFailed();
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, com.bumptech.glide.load.DataSource dataSource, boolean isFirstResource) {
holder.showLoadSuccess();
return false;
}
}).into(imageView);
}
@Override
public void run() {
showImage(curUrl);
}
}
@Override
protected void loadData() {
}
}
17
Source : PayActivity.java
with GNU General Public License v3.0
from YangChengTeam
with GNU General Public License v3.0
from YangChengTeam
/**
* Created by sunshey on 2019/5/14.
*/
public abstract clreplaced PayActivity extends BaseSlidingActivity {
private static final int SDK_PAY_FLAG = 1;
private static final int SDK_AUTH_FLAG = 2;
private IWXAPI mMsgApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMsgApi = WXAPIFactory.createWXAPI(this, null);
// 将该app注册到微信
// mMsgApi.registerApp(ConstantKey.WX_APP_ID);
}
public void toWxPay(OrdersInitBean.ParamsBean paramsBean) {
PayReq request = new PayReq();
/*request.appId = "wxd930ea5d5a258f4f";
request.partnerId = "1900000109";
request.prepayId= "1101000000140415649af9fc314aa427";
request.packageValue = "Sign=WXPay";
request.nonceStr= "1101000000140429eb40476f8896f4c9";
request.timeStamp= "1398746574";
request.sign= "7FFECB600D7157C5AA49810D2D8F28BC2811827B";*/
ConstantKey.WX_APP_ID = paramsBean.appid;
request.appId = paramsBean.appid;
request.partnerId = paramsBean.mch_id;
request.prepayId = paramsBean.prepay_id;
request.packageValue = "Sign=WXPay";
request.nonceStr = paramsBean.nonce_str;
request.timeStamp = paramsBean.timestamp;
request.sign = paramsBean.sign;
mMsgApi.registerApp(ConstantKey.WX_APP_ID);
mMsgApi.sendReq(request);
}
public void toZfbPay(final String orderInfo) {
Runnable payRunnable = () -> {
PayTask alipay = new PayTask(PayActivity.this);
Map<String, String> result = alipay.payV2(orderInfo, true);
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
};
// 必须异步调用
Thread payThread = new Thread(payRunnable);
payThread.start();
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@SuppressWarnings("unused")
public void handleMessage(Message msg) {
switch(msg.what) {
case SDK_PAY_FLAG:
{
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
/**
* 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
*/
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
Log.d("mylog", "handleMessage: resultStatus " + resultStatus);
// 判断resultStatus 为9000则代表支付成功
if (TextUtils.equals(resultStatus, "9000")) {
// 该笔订单是否真实支付成功,需要依赖服务端的异步通知。
onZfbPauResult(true, "支付成功");
// showAlert(PayActivity.this, "001 Payment success:" + payResult);
} else if (TextUtils.equals(resultStatus, "6001")) {
onZfbPauResult(false, "支付取消");
} else {
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
onZfbPauResult(false, "支付失败");
// showAlert(PayActivity.this, "002 Payment failed:" + payResult); //用户取消
}
break;
}
case SDK_AUTH_FLAG:
{
@SuppressWarnings("unchecked")
AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
String resultStatus = authResult.getResultStatus();
// 判断resultStatus 为“9000”且result_code
// 为“200”则代表授权成功,具体状态码代表含义可参考授权接口文档
if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
// 获取alipay_open_id,调支付时作为参数extern_token 的value
// 传入,则支付账户为该授权账户
showAlert(PayActivity.this, "003 Authentication success:" + authResult);
} else {
// 其他状态值则为授权失败
showAlert(PayActivity.this, "004 Authentication failed:" + authResult);
}
break;
}
default:
break;
}
}
};
protected abstract void onZfbPauResult(boolean result, String des);
private void showAlert(Context ctx, String info) {
showAlert(ctx, info, null);
}
private void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
new AlertDialog.Builder(ctx).setMessage(info).setPositiveButton("Confirm", null).setOnDismissListener(onDismiss).show();
}
}
17
Source : AudioRecordButton.java
with GNU General Public License v3.0
from xmmmmmovo
with GNU General Public License v3.0
from xmmmmmovo
@SuppressLint("AppCompatCustomView")
public clreplaced AudioRecordButton extends Button implements AudioManager.AudioStageListener {
private static final int STATE_NORMAL = 1;
private static final int STATE_RECORDING = 2;
private static final int STATE_WANT_TO_CANCEL = 3;
private static final int DISTANCE_Y_CANCEL = 50;
private static final int OVERTIME = 60;
private int mCurrentState = STATE_NORMAL;
// 已经开始录音
private boolean isRecording = false;
private DialogManager mDialogManager;
private float mTime = 0;
// 是否触发了onlongclick,准备好了
private boolean mReady;
private AudioManager mAudioManager;
private String saveDir = PathUtils.getSaveVoicePath(getContext());
@SuppressLint("HandlerLeak")
private Handler mp3handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch(msg.what) {
case AudioManager.MSG_ERROR_AUDIO_RECORD:
Toast.makeText(getContext(), "录音权限被屏蔽或者录音设备损坏!\n请在设置中检查是否开启权限!", Toast.LENGTH_SHORT).show();
mDialogManager.dimissDialog();
mAudioManager.cancel();
reset();
break;
default:
break;
}
}
};
/**
* 先实现两个参数的构造方法,布局会默认引用这个构造方法, 用一个 构造参数的构造方法来引用这个方法 * @param context
*/
public AudioRecordButton(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
}
public AudioRecordButton(Context context, AttributeSet attrs) {
super(context, attrs);
mDialogManager = new DialogManager(getContext());
mAudioManager = AudioManager.getInstance(PathUtils.getSaveVoicePath(getContext()));
mAudioManager.setOnAudioStageListener(this);
mAudioManager.setHandle(mp3handler);
setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// TODO Auto-generated method
mAudioManager.setVocDir(saveDir);
mListener.onStart();
mReady = true;
mAudioManager.prepareAudio();
return false;
}
});
// TODO Auto-generated constructor stub
}
public void setSaveDir(String saveDir) {
this.saveDir = saveDir + saveDir;
}
/**
* 录音完成后的回调,回调给activiy,可以获得mtime和文件的路径
*/
public interface AudioFinishRecorderListener {
void onStart();
void onFinished(float seconds, String filePath);
}
private AudioFinishRecorderListener mListener;
public void setAudioFinishRecorderListener(AudioFinishRecorderListener listener) {
mListener = listener;
}
// 获取音量大小的runnable
private Runnable mGetVoiceLevelRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (isRecording) {
try {
Thread.sleep(100);
mTime += 0.1f;
mhandler.sendEmptyMessage(MSG_VOICE_CHANGE);
if (mTime >= OVERTIME) {
mTime = 60;
mhandler.sendEmptyMessage(MSG_OVERTIME_SEND);
isRecording = false;
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
// 准备三个常量
private static final int MSG_AUDIO_PREPARED = 0X110;
private static final int MSG_VOICE_CHANGE = 0X111;
private static final int MSG_DIALOG_DIMISS = 0X112;
private static final int MSG_OVERTIME_SEND = 0X113;
@SuppressLint("HandlerLeak")
private Handler mhandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_AUDIO_PREPARED:
// 显示应该是在audio end prepare之后回调
if (isTouch) {
mTime = 0;
mDialogManager.showRecordingDialog();
isRecording = true;
new Thread(mGetVoiceLevelRunnable).start();
}
// 需要开启一个线程来变换音量
break;
case MSG_VOICE_CHANGE:
mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel(3));
break;
case MSG_DIALOG_DIMISS:
isRecording = false;
mDialogManager.dimissDialog();
break;
case MSG_OVERTIME_SEND:
mDialogManager.tooLong();
// 持续1.3s
mhandler.sendEmptyMessageDelayed(MSG_DIALOG_DIMISS, 1300);
if (mListener != null) {
// 并且callbackActivity,保存录音
File file = new File(mAudioManager.getCurrentFilePath());
if (PathUtils.isFileExists(file)) {
mListener.onFinished(mTime, mAudioManager.getCurrentFilePath());
} else {
mp3handler.sendEmptyMessage(AudioManager.MSG_ERROR_AUDIO_RECORD);
}
}
isRecording = false;
// 恢复标志位
reset();
break;
}
}
};
// 在这里面发送一个handler的消息
@Override
public void wellPrepared() {
// TODO Auto-generated method stub
mhandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
}
/**
* 直接复写这个监听函数
*/
private boolean isTouch = false;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch(action) {
case MotionEvent.ACTION_DOWN:
isTouch = true;
changeState(STATE_RECORDING);
break;
case MotionEvent.ACTION_MOVE:
if (isRecording) {
// 根据x,y来判断用户是否想要取消
if (wantToCancel(x, y)) {
changeState(STATE_WANT_TO_CANCEL);
} else {
changeState(STATE_RECORDING);
}
}
break;
case MotionEvent.ACTION_UP:
// 首先判断是否有触发onlongclick事件,没有的话直接返回reset
isTouch = false;
if (!mReady) {
reset();
return super.onTouchEvent(event);
}
// 如果按的时间太短,还没准备好或者时间录制太短,就离开了,则显示这个dialog
if (!isRecording || mTime < 0.6f) {
mDialogManager.tooShort();
mAudioManager.cancel();
// 持续1.3s
mhandler.sendEmptyMessageDelayed(MSG_DIALOG_DIMISS, 1300);
} else if (mCurrentState == STATE_RECORDING) {
// 正常录制结束
mDialogManager.dimissDialog();
// release释放一个mediarecorder
mAudioManager.release();
if (mListener != null) {
// 并且callbackActivity,保存录音
BigDecimal b = new BigDecimal(mTime);
float f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
String currentFilePath = mAudioManager.getCurrentFilePath();
Log.i("AudioRecordButton", "filePath:" + currentFilePath);
File file = new File(currentFilePath);
if (PathUtils.isFileExists(file)) {
mListener.onFinished(f1, currentFilePath);
} else {
mp3handler.sendEmptyMessage(AudioManager.MSG_ERROR_AUDIO_RECORD);
}
}
} else if (mCurrentState == STATE_WANT_TO_CANCEL) {
mAudioManager.cancel();
mDialogManager.dimissDialog();
}
isRecording = false;
// 恢复标志位
reset();
break;
case MotionEvent.ACTION_CANCEL:
isTouch = false;
reset();
break;
}
return super.onTouchEvent(event);
}
/**
* 回复标志位以及状态
*/
private void reset() {
// TODO Auto-generated method stub
isRecording = false;
changeState(STATE_NORMAL);
mReady = false;
mTime = 0;
}
private boolean wantToCancel(int x, int y) {
// TODO Auto-generated method stub
if (x < 0 || x > getWidth()) {
// 判断是否在左边,右边,上边,下边
return true;
}
if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
return true;
}
return false;
}
private void changeState(int state) {
// TODO Auto-generated method stub
if (mCurrentState != state) {
mCurrentState = state;
switch(mCurrentState) {
case STATE_NORMAL:
setBackgroundResource(R.drawable.button_recordnormal);
setText(R.string.normal);
break;
case STATE_RECORDING:
setBackgroundResource(R.drawable.button_recording);
setText(R.string.recording);
if (isRecording) {
mDialogManager.recording();
// 复写dialog.recording();
}
break;
case STATE_WANT_TO_CANCEL:
setBackgroundResource(R.drawable.button_recording);
setText(R.string.want_to_cancle);
// dialog want to cancel
mDialogManager.wantToCancel();
break;
}
}
}
@Override
public boolean onPreDraw() {
// TODO Auto-generated method stub
return false;
}
}
17
Source : IndicatorView.java
with Apache License 2.0
from xiaohaibin
with Apache License 2.0
from xiaohaibin
/**
* Author: Mr.xiao on 2017/5/23
* @mail:[email protected]
* @github:https://github.com/xiaohaibin
* @describe: 指示器
*/
public clreplaced IndicatorView extends View {
private int indicatorColor;
private int indicatorColorSelected;
private int indicatorWidth = 0;
private int gravity = 0;
private Paint mPaint;
private int indicatorCount = 0;
private int currentIndicator = 0;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x12) {
invalidate();
}
}
};
public IndicatorView(Context context) {
this(context, null, 0);
}
public IndicatorView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public IndicatorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.IndicatorView);
indicatorColor = typedArray.getColor(R.styleable.IndicatorView_indicatorColor, Color.rgb(0, 0, 0));
indicatorColorSelected = typedArray.getColor(R.styleable.IndicatorView_indicatorColorSelected, Color.rgb(0, 0, 0));
indicatorWidth = ScreenUtil.dip2px(typedArray.getInt(R.styleable.IndicatorView_indicatorWidth, 0));
gravity = typedArray.getInt(R.styleable.IndicatorView_gravity, 0);
typedArray.recycle();
}
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
indicatorColor = Color.rgb(0, 0, 0);
indicatorColorSelected = Color.rgb(0, 0, 0);
}
@Override
protected void onDraw(Canvas canvas) {
int viewWidth = getWidth();
int viewHeight = getHeight();
int totalWidth = indicatorWidth * (2 * indicatorCount - 1);
if (indicatorCount > 0) {
for (int i = 0; i < indicatorCount; i++) {
if (i == currentIndicator) {
mPaint.setColor(indicatorColorSelected);
} else {
mPaint.setColor(indicatorColor);
}
int left = (viewWidth - totalWidth) / 2 + (i * 2 * indicatorWidth);
switch(gravity) {
case 0:
left = (viewWidth - totalWidth) / 2 + (i * 2 * indicatorWidth);
break;
case 1:
left = i * 2 * indicatorWidth;
break;
case 2:
left = viewWidth - totalWidth + (i * 2 * indicatorWidth);
break;
default:
break;
}
int top = (viewHeight - indicatorWidth) / 2;
int right = left + indicatorWidth;
int bottom = top + indicatorWidth;
RectF rectF = new RectF(left, top, right, bottom);
canvas.drawOval(rectF, mPaint);
}
}
}
public void setIndicatorCount(int indicatorCount) {
this.indicatorCount = indicatorCount;
}
public void setCurrentIndicator(int currentIndicator) {
this.currentIndicator = currentIndicator;
handler.sendEmptyMessage(0x12);
}
}
17
Source : BaseBottomWindow.java
with Apache License 2.0
from TommyLemon
with Apache License 2.0
from TommyLemon
/**
* 基础底部弹出界面Activity
* @author Lemon
* @warn 不要在子类重复这个类中onCreate中的代码
* @use extends BaseBottomWindow, 具体参考.DemoBottomWindow
*/
public abstract clreplaced BaseBottomWindow extends BaseActivity {
private static final String TAG = "BaseBottomWindow";
public static final String INTENT_ITEMS = "INTENT_ITEMS";
public static final String INTENT_ITEM_IDS = "INTENT_ITEM_IDS";
public static final String RESULT_replacedLE = "RESULT_replacedLE";
public static final String RESULT_ITEM = "RESULT_ITEM";
public static final String RESULT_ITEM_ID = "RESULT_ITEM_ID";
// UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 子Activity全局背景View
protected View vBaseBottomWindowRoot;
/**
* 如果在子类中调用(即super.initView());则view必须含有initView中初始化用到的id(非@Nullable标记)且id对应的View的类型全部相同;
* 否则必须在子类initView中重写这个类中initView内的代码(所有id替换成可用id)
*/
@Override
public void initView() {
// 必须调用
enterAnim = exitAnim = R.anim.null_anim;
vBaseBottomWindowRoot = findViewById(R.id.vBaseBottomWindowRoot);
vBaseBottomWindowRoot.startAnimation(AnimationUtils.loadAnimation(context, R.anim.bottom_window_enter));
}
// UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Data数据区(存在数据获取或处理代码,但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
@Override
public void initData() {
// 必须调用
}
/**
* 设置需要返回的结果
*/
protected abstract void setResult();
// Data数据区(存在数据获取或处理代码,但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
@Override
public void initEvent() {
// 必须调用
// vBaseBottomWindowRoot.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// finish();
// }
// });
}
@Override
public void onForwardClick(View v) {
setResult();
finish();
}
@SuppressLint("HandlerLeak")
public Handler exitHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
BaseBottomWindow.super.finish();
}
};
// 系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
private boolean isExit = false;
/**
* 带动画退出,并使退出事件只响应一次
*/
@Override
public void finish() {
Log.d(TAG, "finish >>> isExit = " + isExit);
if (isExit) {
return;
}
isExit = true;
vBaseBottomWindowRoot.startAnimation(AnimationUtils.loadAnimation(context, R.anim.bottom_window_exit));
vBaseBottomWindowRoot.setVisibility(View.GONE);
exitHandler.sendEmptyMessageDelayed(0, 200);
}
@Override
protected void onDestroy() {
super.onDestroy();
vBaseBottomWindowRoot = null;
}
// 类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// 系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// 内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
17
Source : MainActivity.java
with Apache License 2.0
from SShineTeam
with Apache License 2.0
from SShineTeam
public clreplaced MainActivity extends SherlockFragmentActivity implements OnClickListener, ISimpleDialogListener {
// 用户信息
private ImageButton imgbtn_UserInfo;
// 设置
private ImageButton imgbtn_shezhi;
// 更新离线数据
private ImageButton btnUpdate;
// 退出
private ImageButton btnQuit;
// 火车行介绍
private ImageButton imgbtn_huochexing;
// 安全防盗
private ImageButton imgbtn_fangdao;
// 我的车次
private ImageButton imgbtn_wodecheci;
// 添加车次
private ImageButton imgbtn_tianjia;
// 最新资讯
private ImageButton imgbtn_zixun;
// 车友聊天
private ImageButton imgbtn_liaotian;
// 列车查询
private ImageButton imgbtn_chaxun;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch(msg.what) {
case A6Util.MSG_TOAST:
showMsg((CharSequence) msg.obj);
break;
}
}
};
private static final int REQUEST_SET_TIMEZONE = 0;
long waitTime = 2000;
long touchTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aty_main);
initActionBar();
initViews();
}
private void initActionBar() {
com.actionbarsherlock.app.ActionBar actionBar = getSupportActionBar();
actionBar.hide();
}
private void initViews() {
imgbtn_huochexing = (ImageButton) findViewById(R.id.help);
imgbtn_huochexing.setOnClickListener(this);
imgbtn_UserInfo = (ImageButton) findViewById(R.id.userInfo);
imgbtn_UserInfo.setOnClickListener(this);
imgbtn_wodecheci = (ImageButton) findViewById(R.id.wodecheci);
imgbtn_wodecheci.setOnClickListener(this);
imgbtn_tianjia = (ImageButton) findViewById(R.id.add);
imgbtn_tianjia.setOnClickListener(this);
imgbtn_zixun = (ImageButton) findViewById(R.id.info);
imgbtn_zixun.setOnClickListener(this);
imgbtn_liaotian = (ImageButton) findViewById(R.id.chat);
imgbtn_liaotian.setOnClickListener(this);
imgbtn_chaxun = (ImageButton) findViewById(R.id.query);
imgbtn_chaxun.setOnClickListener(this);
imgbtn_shezhi = (ImageButton) findViewById(R.id.setup);
imgbtn_shezhi.setOnClickListener(this);
imgbtn_fangdao = (ImageButton) findViewById(R.id.anreplacedheft);
imgbtn_fangdao.setOnClickListener(this);
findViewById(R.id.order).setOnClickListener(this);
btnUpdate = (ImageButton) findViewById(R.id.update);
btnUpdate.setOnClickListener(this);
btnQuit = (ImageButton) findViewById(R.id.quit);
btnQuit.setOnClickListener(this);
// 检测时区
String strTest = ":" + TimeZone.getDefault().getRawOffset() + "," + TimeZone.getDefault().getRawOffset();
if (TimeZone.getDefault().getRawOffset() != 28800000) {
SimpleDialogFragment.createBuilder(getApplicationContext(), getSupportFragmentManager()).setCancelable(true).setreplacedle("时区错误提示" + strTest).setMessage(R.string.setTimezoneStr).setRequestCode(REQUEST_SET_TIMEZONE).setPositiveButtonText("是(推荐)").setNegativeButtonText("否").show();
}
}
protected void onResume() {
// 设置头像
try {
int headIconId = Integer.parseInt(MyApp.getInstance().getUserInfoSPUtil().getHeadIcon());
imgbtn_UserInfo.setBackgroundResource(headIconId);
} catch (Exception e) {
e.printStackTrace();
}
super.onResume();
MobclickAgent.onResume(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.help:
startActivity(new Intent(this, HuoCheXingAty.clreplaced));
break;
case R.id.userInfo:
if (!MyApp.getInstance().getUserInfoSPUtil().isLogin()) {
startActivity(new Intent(MainActivity.this, LoginAty.clreplaced));
return;
}
startActivity(new Intent(this, UserInfoAty.clreplaced));
break;
case R.id.wodecheci:
startActivity(new Intent(this, TrainInfoAty.clreplaced));
break;
case R.id.add:
startActivity(new Intent(this, AddInfoAty.clreplaced));
break;
case R.id.info:
startActivity(new Intent(this, TicketInfoAty.clreplaced));
break;
case R.id.chat:
startActivity(new Intent(this, ChatRoomAty.clreplaced));
break;
case R.id.query:
startActivity(new Intent(this, TrainSchAty.clreplaced));
break;
case R.id.setup:
startActivity(new Intent(this, MoreAty.clreplaced));
break;
case R.id.anreplacedheft:
startActivity(new Intent(this, AnreplacedheftAty.clreplaced));
break;
case R.id.order:
startActivity(new Intent(MainActivity.this, A6OrderAty.clreplaced));
break;
case R.id.update:
checkUpdate();
break;
case R.id.quit:
startActivity(new Intent(this, MonitorMangAty.clreplaced));
break;
}
}
public void checkUpdate() {
UmengUpdateAgent.setUpdateAutoPopup(false);
UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
@Override
public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
switch(updateStatus) {
case // has update
UpdateStatus.Yes:
UmengUpdateAgent.showUpdateDialog(MainActivity.this, updateInfo);
break;
case // has no update
UpdateStatus.No:
showMsg("当前已是最新版本" + SF.TIP);
break;
case // time out
UpdateStatus.Timeout:
showMsg("检测超时" + SF.FAIL);
break;
}
UmengUpdateAgent.setUpdateAutoPopup(true);
UmengUpdateAgent.setUpdateListener(null);
}
});
showMsg("检测更新中,请稍候...");
UmengUpdateAgent.update(this);
}
@Override
public void onBackPressed() {
long currentTime = System.currentTimeMillis();
if ((currentTime - touchTime) >= waitTime) {
Toast.makeText(this, "再按一次退出火车行" + SF.TIP, Toast.LENGTH_SHORT).show();
touchTime = currentTime;
} else {
quit();
}
}
public void quit() {
MobclickAgent.onKillProcess(this);
MyApp myApp = ((MyApp) getApplication());
L.i("isAnreplacedheftServiceStarted:" + myApp.isAnreplacedheftServiceStarted);
L.i("isBgdService2Started:" + myApp.isBgdService2Started);
if (myApp.isAnreplacedheftServiceStarted || myApp.isBgdService2Started) {
MainActivity.this.finish();
} else {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
System.exit(0);
}
// 确认是否在退出后取消接收聊天信息
SettingSPUtil setSP = MyApp.getInstance().getSettingSPUtil();
if (!setSP.isChatReceiveMsgAlways()) {
PushManager.stopWork(getApplicationContext());
}
}
@Override
public void onPositiveButtonClicked(int requestCode) {
switch(requestCode) {
case REQUEST_SET_TIMEZONE:
startActivity(new Intent(Settings.ACTION_DATE_SETTINGS));
break;
}
}
private void showMsg(CharSequence cs1) {
Toast.makeText(this, cs1, Toast.LENGTH_SHORT).show();
}
@Override
public void onNegativeButtonClicked(int requestCode) {
switch(requestCode) {
case REQUEST_SET_TIMEZONE:
break;
}
}
public void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
}
17
Source : AliPayTools.java
with Apache License 2.0
from sdwfqin
with Apache License 2.0
from sdwfqin
/**
* 描述:支付宝支付工具类
*
* @author 张钦
* @date 2018/1/25
*/
public clreplaced AliPayTools {
private static final int SDK_PAY_FLAG = 1;
private static OnRequestListener sOnRequestListener;
@SuppressLint("HandlerLeak")
private static Handler mHandler = new Handler() {
@SuppressWarnings("unused")
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SDK_PAY_FLAG:
{
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
// 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
String memo = payResult.getMemo();
// 判断resultStatus 为9000则代表支付成功
int status = 0;
try {
status = Integer.parseInt(resultStatus);
} catch (NumberFormatException e) {
status = -1;
}
sOnRequestListener.onCallback(status, memo);
break;
}
default:
break;
}
}
};
/**
* 支付
*
* @param activity
* @param appid 支付宝分配给开发者的应用ID
* @param isRsa2 签名类型
* @param alipay_rsa_private 签名私钥
* @param aliPayModel
* @param onRequestListener 回调监听
*/
public static void aliPay(final Activity activity, String appid, boolean isRsa2, String alipay_rsa_private, AliPayModel aliPayModel, OnRequestListener onRequestListener) {
sOnRequestListener = onRequestListener;
Map<String, String> params = AliPayOrderInfoUtil.buildOrderParamMap(appid, isRsa2, aliPayModel);
String orderParam = AliPayOrderInfoUtil.buildOrderParam(params);
String privateKey = alipay_rsa_private;
String sign = AliPayOrderInfoUtil.getSign(params, privateKey, isRsa2);
final String orderInfo = orderParam + "&" + sign;
Runnable payRunnable = () -> {
PayTask alipay = new PayTask(activity);
Map<String, String> result = alipay.payV2(orderInfo, true);
Log.i("msp", result.toString());
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}
/**
* 支付 服务端返回orderInfo
*
* @param activity
* @param orderInfo
* @param onRequestListener
*/
public static void aliPay(final Activity activity, String orderInfo, OnRequestListener onRequestListener) {
sOnRequestListener = onRequestListener;
Runnable payRunnable = () -> {
PayTask alipay = new PayTask(activity);
Map<String, String> result = alipay.payV2(orderInfo, true);
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}
/**
* 销毁
*/
public static void detach() {
sOnRequestListener = null;
}
}
17
Source : SearchBookPrensenter.java
with Apache License 2.0
from MissZzz1
with Apache License 2.0
from MissZzz1
/**
* Created by zhao on 2017/7/26.
*/
public clreplaced SearchBookPrensenter extends BasePresenter {
private SearchBookActivity mSearchBookActivity;
private SearchBookAdapter mSearchBookAdapter;
// 搜索关键字
private String searchKey;
private ArrayList<Book> mBooks = new ArrayList<>();
private ArrayList<SearchHistory> mSearchHistories = new ArrayList<>();
private ArrayList<String> mSuggestions = new ArrayList<>();
private SearchHistoryService mSearchHistoryService;
private SearchHistoryAdapter mSearchHistoryAdapter;
// 搜索输入确认
private int inputConfirm = 0;
// 搜索输入确认时间(毫秒)
private int confirmTime = 1000;
private static String[] suggestion = { "斗罗大陆4终极斗罗", "左道倾天", "诡秘之主", "元尊", "天下第九", "三寸人间", "万族之劫", "大奉打更人" };
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case 1:
search();
break;
case 2:
initSearchList();
break;
case 3:
// mSearchBookActivity.getLvSearchBooksList().setAdapter(null);
mSearchBookActivity.getPbLoading().setVisibility(View.GONE);
break;
}
}
};
SearchBookPrensenter(SearchBookActivity searchBookActivity) {
super(searchBookActivity, searchBookActivity.getLifecycle());
mSearchBookActivity = searchBookActivity;
mSearchHistoryService = new SearchHistoryService();
Collections.addAll(mSuggestions, suggestion);
}
@Override
public void create() {
mSearchBookActivity.getTvreplacedleText().setText("搜索");
mSearchBookActivity.getLlreplacedleBack().setOnClickListener(view -> mSearchBookActivity.finish());
mSearchBookActivity.getEtSearchKey().addTextChangedListener(new Texreplacedcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(final Editable editable) {
searchKey = editable.toString();
if (StringHelper.isEmpty(searchKey)) {
search();
}
}
});
mSearchBookActivity.getEtSearchKey().setOnKeyListener((v, keyCode, event) -> {
// 是否是回车键
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
// 隐藏键盘
((InputMethodManager) mSearchBookActivity.getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(mSearchBookActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// 搜索
search();
}
return false;
});
mSearchBookActivity.getLvSearchBooksList().setOnItemClickListener((adapterView, view, i, l) -> {
Intent intent = new Intent(mSearchBookActivity, BookInfoActivity.clreplaced);
intent.putExtra(APPCONST.BOOK, mBooks.get(i));
mSearchBookActivity.startActivity(intent);
});
mSearchBookActivity.getTvSearchConform().setOnClickListener(view -> search());
mSearchBookActivity.getTgSuggestBook().setOnTagClickListener(tag -> {
mSearchBookActivity.getEtSearchKey().setText(tag);
search();
});
mSearchBookActivity.getLvHistoryList().setOnItemClickListener((parent, view, position, id) -> {
mSearchBookActivity.getEtSearchKey().setText(mSearchHistories.get(position).getContent());
search();
});
mSearchBookActivity.getLlClearHistory().setOnClickListener(v -> {
mSearchHistoryService.clearHistory();
initHistoryList();
});
initSuggestionBook();
initHistoryList();
}
/**
* 初始化建议书目
*/
private void initSuggestionBook() {
mSearchBookActivity.getTgSuggestBook().setTags(suggestion);
}
/**
* 初始化历史列表
*/
private void initHistoryList() {
mSearchHistories = mSearchHistoryService.findAllSearchHistory();
if (mSearchHistories == null || mSearchHistories.size() == 0) {
mSearchBookActivity.getLlHistoryView().setVisibility(View.GONE);
} else {
mSearchHistoryAdapter = new SearchHistoryAdapter(mSearchBookActivity, R.layout.listview_search_history_item, mSearchHistories);
mSearchBookActivity.getLvHistoryList().setAdapter(mSearchHistoryAdapter);
mSearchBookActivity.getLlHistoryView().setVisibility(View.VISIBLE);
}
}
/**
* 初始化搜索列表
*/
private void initSearchList() {
mSearchBookAdapter = new SearchBookAdapter(mSearchBookActivity, R.layout.listview_search_book_item, mBooks);
mSearchBookActivity.getLvSearchBooksList().setAdapter(mSearchBookAdapter);
mSearchBookActivity.getLvSearchBooksList().setVisibility(View.VISIBLE);
mSearchBookActivity.getLlSuggestBooksView().setVisibility(View.GONE);
mSearchBookActivity.getLlHistoryView().setVisibility(View.GONE);
mSearchBookActivity.getPbLoading().setVisibility(View.GONE);
}
/**
* 获取搜索数据
*/
private void getData() {
mBooks.clear();
CommonApi.searchTl(searchKey, new ResultCallback() {
@Override
public void onFinish(Object o, int code) {
mBooks.addAll((ArrayList<Book>) o);
mHandler.sendMessage(mHandler.obtainMessage(2));
}
@Override
public void onError(Exception e) {
mHandler.sendMessage(mHandler.obtainMessage(3));
}
});
CommonApi.searchBqg(searchKey, new ResultCallback() {
@Override
public void onFinish(Object o, int code) {
mBooks.addAll((ArrayList<Book>) o);
mHandler.sendMessage(mHandler.obtainMessage(2));
}
@Override
public void onError(Exception e) {
mHandler.sendMessage(mHandler.obtainMessage(3));
}
});
}
/**
* 搜索
*/
private void search() {
mSearchBookActivity.getPbLoading().setVisibility(View.VISIBLE);
if (StringHelper.isEmpty(searchKey)) {
mSearchBookActivity.getPbLoading().setVisibility(View.GONE);
mSearchBookActivity.getLvSearchBooksList().setVisibility(View.GONE);
mSearchBookActivity.getLlSuggestBooksView().setVisibility(View.VISIBLE);
initHistoryList();
mSearchBookActivity.getLvSearchBooksList().setAdapter(null);
} else {
mSearchBookActivity.getLvSearchBooksList().setVisibility(View.VISIBLE);
mSearchBookActivity.getLlSuggestBooksView().setVisibility(View.GONE);
mSearchBookActivity.getLlHistoryView().setVisibility(View.GONE);
getData();
mSearchHistoryService.addOrUpadteHistory(searchKey);
}
}
boolean onBackPressed() {
if (StringHelper.isEmpty(searchKey)) {
return false;
} else {
mSearchBookActivity.getEtSearchKey().setText("");
return true;
}
}
}
17
Source : BookcasePresenter.java
with Apache License 2.0
from MissZzz1
with Apache License 2.0
from MissZzz1
/**
* Created by zhao on 2017/7/25.
*/
public clreplaced BookcasePresenter extends BasePresenter {
private BookcaseFragment mBookcaseFragment;
// 书目数组
private ArrayList<Book> mBooks = new ArrayList<>();
private BookcaseDragAdapter mBookcaseAdapter;
private BookService mBookService;
private MainActivity mMainActivity;
// private ChapterService mChapterService;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case 1:
mBookcaseAdapter.notifyDataSetChanged();
mBookcaseFragment.getSrlContent().finishRefresh();
break;
case 2:
mBookcaseFragment.getSrlContent().finishRefresh();
break;
}
}
};
BookcasePresenter(BookcaseFragment bookcaseFragment) {
super(bookcaseFragment.getContext(), bookcaseFragment.getLifecycle());
mBookcaseFragment = bookcaseFragment;
mBookService = new BookService();
}
@Override
public void start() {
mMainActivity = ((MainActivity) (mBookcaseFragment.getContext()));
mBookcaseFragment.getSrlContent().setEnableRefresh(false);
mBookcaseFragment.getSrlContent().setEnableHeaderTranslationContent(false);
mBookcaseFragment.getSrlContent().setEnableLoadMore(false);
mBookcaseFragment.getSrlContent().setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
initNoReadNum();
}
});
mBookcaseFragment.getLlNoDataTips().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mBookcaseFragment.getContext(), SearchBookActivity.clreplaced);
mBookcaseFragment.startActivity(intent);
}
});
mBookcaseFragment.getGvBook().setOnItemLongClickListener((parent, view, position, id) -> {
if (!mBookcaseAdapter.ismEditState()) {
mBookcaseFragment.getSrlContent().setEnableRefresh(false);
mBookcaseAdapter.setmEditState(true);
mBookcaseFragment.getGvBook().setDragModel(DragSortGridView.DRAG_BY_LONG_CLICK);
mBookcaseAdapter.notifyDataSetChanged();
mMainActivity.getRlCommonreplacedle().setVisibility(View.GONE);
mMainActivity.getRlEditreplacedile().setVisibility(View.VISIBLE);
VibratorUtil.Vibrate(mBookcaseFragment.getActivity(), 200);
// mBookcaseFragment.getGvBook().setOnItemClickListener(null);
}
return true;
});
mMainActivity.getTvEditFinish().setOnClickListener(v -> {
mMainActivity.getRlCommonreplacedle().setVisibility(View.VISIBLE);
mMainActivity.getRlEditreplacedile().setVisibility(View.GONE);
// mBookcaseFragment.getSrlContent().setEnableRefresh(true);
mBookcaseFragment.getGvBook().setDragModel(-1);
mBookcaseAdapter.setmEditState(false);
mBookcaseAdapter.notifyDataSetChanged();
});
}
private void init() {
initBook();
if (mBooks == null || mBooks.size() == 0) {
mBookcaseFragment.getGvBook().setVisibility(View.GONE);
mBookcaseFragment.getLlNoDataTips().setVisibility(View.VISIBLE);
} else {
if (mBookcaseAdapter == null) {
mBookcaseAdapter = new BookcaseDragAdapter(mBookcaseFragment.getContext(), R.layout.gridview_book_item, mBooks, false);
mBookcaseFragment.getGvBook().setDragModel(-1);
mBookcaseFragment.getGvBook().setTouchClashparent(((MainActivity) (mBookcaseFragment.getContext())).getVpContent());
/* mBookcaseFragment.getGvBook().setDragModel(DragSortGridView.DRAG_BY_LONG_CLICK);
((MainActivity) (mBookcaseFragment.getActivity())).setViewPagerScroll(false);*/
mBookcaseFragment.getGvBook().setAdapter(mBookcaseAdapter);
} else {
mBookcaseAdapter.notifyDataSetChanged();
}
mBookcaseFragment.getLlNoDataTips().setVisibility(View.GONE);
mBookcaseFragment.getGvBook().setVisibility(View.VISIBLE);
}
}
public void getData() {
init();
initNoReadNum();
}
private void initBook() {
mBooks.clear();
mBooks.addAll(mBookService.getAllBooks());
for (int i = 0; i < mBooks.size(); i++) {
if (mBooks.get(i).getSortCode() != i + 1) {
mBooks.get(i).setSortCode(i + 1);
mBookService.updateEnreplacedy(mBooks.get(i));
}
}
}
private void initNoReadNum() {
for (final Book book : mBooks) {
CommonApi.getBookChapters(book, new ResultCallback() {
@Override
public void onFinish(Object o, int code) {
final ArrayList<Chapter> chapters = (ArrayList<Chapter>) o;
int noReadNum = chapters.size() - book.getChapterTotalNum();
if (noReadNum > 0) {
book.setNoReadNum(noReadNum);
mHandler.sendMessage(mHandler.obtainMessage(1));
} else {
book.setNoReadNum(0);
mHandler.sendMessage(mHandler.obtainMessage(2));
}
mBookService.updateEnreplacedy(book);
}
@Override
public void onError(Exception e) {
mHandler.sendMessage(mHandler.obtainMessage(1));
}
});
}
}
private void setThemeColor(int colorPrimary, int colorPrimaryDark) {
// mToolbar.setBackgroundResource(colorPrimary);
mBookcaseFragment.getSrlContent().setPrimaryColorsId(colorPrimary, android.R.color.white);
if (Build.VERSION.SDK_INT >= 21) {
mBookcaseFragment.getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(mBookcaseFragment.getContext(), colorPrimaryDark));
}
}
@Override
public void resume() {
getData();
}
}
17
Source : StartActivity.java
with Apache License 2.0
from krait-team
with Apache License 2.0
from krait-team
/**
* @author 权那他(Kraity)
* @date 2019/7/1.
* GitHub:https://github.com/kraity
* WebSite:https://krait.cn
* email:[email protected]
*/
public clreplaced StartActivity extends InitialActivity {
private ProgressBar progressBar;
@Override
@SuppressLint("CheckResult")
@SuppressWarnings("ResultOfMethodCallIgnored")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView(R.layout.activity_start);
Initialization();
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions.request(Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean granted) throws Exception {
new Thread() {
@Override
public void run() {
super.run();
switch(personage.getLoginInt()) {
case 1:
XMLRPCService XMLRPCService = new XMLRPCService();
XMLRPCService.init(personage.getSiteUrl(), personage.getId(), personage.getName(), personage.getPreplacedword());
try {
XMLRPCUtils util = new XMLRPCUtils(personage, personageACache, XMLRPCService);
util.setPersonage();
if (personageACache.getreplacedtring("unRefresh") == null) {
util.setStat();
util.setGravatar();
personageACache.put("unRefresh", true);
}
runOnUiThread(1);
} catch (Exception e) {
e.printStackTrace();
Message msg = handler.obtainMessage();
msg.what = 2;
handler.sendMessage(msg);
}
break;
case 0:
runOnUiThread(0);
}
}
}.start();
}
});
}
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(@NotNull final android.os.Message msg) {
final int what = msg.what;
if (what == 2) {
AlertDialog();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent;
if (what == 1) {
intent = new Intent(StartActivity.this, MainActivity.clreplaced);
} else {
intent = new Intent(StartActivity.this, LoginActivity.clreplaced);
}
startActivity(intent);
StartActivity.this.finish();
}
}, 100);
}
}
};
private void runOnUiThread(final int s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Message msg = handler.obtainMessage();
msg.what = s;
handler.sendMessage(msg);
}
});
}
private void AlertDialog() {
new AlertDialog.Builder(StartActivity.this).setreplacedle("请求失败").setMessage("尝试请求连接客官的博客失败\n可能是因为密码错误或者博客发生异常").setPositiveButton("再试连接", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(StartActivity.this, StartActivity.clreplaced).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}).setNegativeButton("修改账户", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(StartActivity.this, LoginActivity.clreplaced).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
dialogInterface.dismiss();
}
}).create().show();
}
/**
* 状态栏和导航栏消失且全屏
*/
public void init() {
requestWindowFeature(Window.FEATURE_NO_replacedLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
window.setAttributes(params);
}
public void Initialization() {
ContourView contourView = findViewById(R.id.contourView);
contourView.setBackgroundColor(setting.getColorPrimary());
contourView.setShaderEndColor(setting.getColorAccent());
contourView.setShaderStartColor(setting.getColorPrimary());
progressBar = (ProgressBar) findViewById(R.id.spin_kit);
Sprite threeBounce = new ThreeBounce();
progressBar.setIndeterminateDrawable(threeBounce);
}
}
17
Source : RegisterLastFragment.java
with Apache License 2.0
from krait-team
with Apache License 2.0
from krait-team
/**
* @author 权那他(Kraity)
* @date 2019/8/23.
* GitHub:https://github.com/kraity
* WebSite:https://krait.cn
* email:[email protected]
*/
public clreplaced RegisterLastFragment extends Fragment {
private Personage personage;
private ProgressDialog progress;
private String XMLRPCUrl;
private String name;
private Object[] domain;
private String preplacedword;
RegisterLastFragment(Personage p, Object[] u) {
personage = p;
domain = u;
XMLRPCUrl = (String) u[3];
}
@SuppressLint("HandlerLeak")
private Handler handler = new // 全局共享
Handler() {
public void handleMessage(android.os.Message msg) {
// 处理消息时需要知道是成功的消息还是失败的消息
switch(msg.what) {
case 1:
OtherUtil.toast(getContext(), (String) msg.obj);
break;
case 0:
PersonageObject p = (PersonageObject) msg.obj;
personage.setId(p.uid());
personage.setName(p.name());
personage.setScreenName(p.screenName());
personage.setEmail(p.mail());
personage.setPreplacedword(preplacedword);
personage.setSiteUrl(XMLRPCUrl);
personage.setDomain((String) domain[1]);
personage.setSslAble((boolean) domain[0]);
personage.setPseudoAble((boolean) domain[2]);
personage.addAccount();
personage.setLogin(true);
/* 转跳到 StartActivity 重新启动 */
startActivity(new Intent(getActivity(), StartActivity.clreplaced));
Objects.requireNonNull(getActivity()).finish();
}
progress.dismiss();
}
};
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register_last, container, false);
progress = new ProgressDialog(getContext());
progress.setMessage("加载中...");
progress.setIndeterminate(true);
progress.setCancelable(true);
final EditText etName = view.findViewById(R.id.et_name);
final EditText etPreplacedword = view.findViewById(R.id.et_preplacedword);
view.findViewById(R.id.btn_show_login).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (etName.getText().toString().isEmpty()) {
OtherUtil.toast(getContext(), "客官必须输入账号");
return;
}
if (etPreplacedword.getText().toString().isEmpty()) {
OtherUtil.toast(getContext(), "客官必须输入密码");
return;
}
name = etName.getText().toString();
preplacedword = etPreplacedword.getText().toString();
progress.show();
new loginThread().start();
}
});
return view;
}
public clreplaced loginThread extends Thread {
public void run() {
Message msg = handler.obtainMessage();
// 增加部分
Looper.prepare();
try {
XMLRPCService XMLRPCService = new XMLRPCService();
XMLRPCService.init(XMLRPCUrl, 1, name, preplacedword);
Object[] obj = XMLRPCService.getUser();
PersonageObject p = new PersonageObject(obj[1]);
/* 检查登录的账户是否为管理员权限 */
if (!p.group().contains("administrator")) {
msg.obj = "客官,你的账号非管理员权限";
msg.what = 1;
handler.sendMessage(msg);
return;
}
msg.what = 0;
msg.obj = p;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
msg.obj = "客官,无法登陆, 密码错误";
msg.what = 1;
handler.sendMessage(msg);
}
// 增加部分
Looper.loop();
}
}
}
17
Source : MainActivity.java
with Apache License 2.0
from HMS-Core
with Apache License 2.0
from HMS-Core
public clreplaced MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "PushDemoLog";
private TextView tvSetPush;
private TextView tvSetAAID;
private TextView tvSetAutoInit;
private final static int GET_AAID = 1;
private final static int DELETE_AAID = 2;
private final static String CODELABS_ACTION = "com.huawei.codelabpush.action";
private MyReceiver receiver;
@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
switch(msg.what) {
case GET_AAID:
tvSetAAID.setText(R.string.get_aaid);
break;
case DELETE_AAID:
tvSetAAID.setText(R.string.delete_aaid);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvSetPush = findViewById(R.id.btn_set_push);
tvSetAAID = findViewById(R.id.btn_get_aaid);
tvSetAutoInit = findViewById(R.id.btn_set_autoInit_enabled);
tvSetPush.setOnClickListener(this);
tvSetAAID.setOnClickListener(this);
tvSetAutoInit.setOnClickListener(this);
findViewById(R.id.btn_add_topic).setOnClickListener(this);
findViewById(R.id.btn_get_token).setOnClickListener(this);
findViewById(R.id.btn_delete_token).setOnClickListener(this);
findViewById(R.id.btn_delete_topic).setOnClickListener(this);
findViewById(R.id.btn_action).setOnClickListener(this);
findViewById(R.id.btn_generate_intent).setOnClickListener(this);
findViewById(R.id.btn_is_autoInit_enabled).setOnClickListener(this);
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(CODELABS_ACTION);
registerReceiver(receiver, filter);
}
@Override
public void onClick(View view) {
int viewId = view.getId();
switch(viewId) {
case R.id.btn_get_aaid:
setAAID(tvSetAAID.getText().toString().equals(getString(R.string.get_aaid)));
break;
case R.id.btn_get_token:
getToken();
break;
case R.id.btn_delete_token:
deleteToken();
break;
case R.id.btn_set_push:
setReceiveNotifyMsg(tvSetPush.getText().toString().equals(getString(R.string.set_push_enable)));
break;
case R.id.btn_add_topic:
addTopic();
break;
case R.id.btn_delete_topic:
deleteTopic();
break;
case R.id.btn_action:
openActivityByAction();
break;
case R.id.btn_generate_intent:
generateIntentUri();
break;
case R.id.btn_is_autoInit_enabled:
isAutoInitEnabled();
break;
case R.id.btn_set_autoInit_enabled:
setAutoInitEnabled(tvSetAutoInit.getText().toString().equals(getString(R.string.AutoInitEnabled)));
break;
default:
break;
}
}
/**
* getAAID(), This method is used to obtain an AAID in asynchronous mode. You need to add a listener to listen to the operation result.
* deleteAAID(), delete a local AAID and its generation timestamp.
* @param isGet getAAID or deleteAAID
*/
private void setAAID(boolean isGet) {
if (isGet) {
Task<AAIDResult> idResult = HmsInstanceId.getInstance(this).getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaId = aaidResult.getId();
Log.i(TAG, "getAAID success:" + aaId);
showLog("getAAID success:" + aaId);
handler.sendEmptyMessage(DELETE_AAID);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "getAAID failed:" + e);
showLog("getAAID failed." + e);
}
});
} else {
new Thread() {
@Override
public void run() {
try {
HmsInstanceId.getInstance(MainActivity.this).deleteAAID();
showLog("delete aaid and its generation timestamp success.");
handler.sendEmptyMessage(GET_AAID);
} catch (Exception e) {
Log.e(TAG, "deleteAAID failed. " + e);
showLog("deleteAAID failed." + e);
}
}
}.start();
}
}
/**
* getToken(String appId, String scope), This method is used to obtain a token required for accessing HUAWEI Push Kit.
* If there is no local AAID, this method will automatically generate an AAID when it is called because the Huawei Push server needs to generate a token based on the AAID.
* This method is a synchronous method, and you cannot call it in the main thread. Otherwise, the main thread may be blocked.
*/
private void getToken() {
showLog("getToken:begin");
new Thread() {
@Override
public void run() {
try {
// read from agconnect-services.json
String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, "HCM");
Log.i(TAG, "get token:" + token);
if (!TextUtils.isEmpty(token)) {
sendRegTokenToServer(token);
}
showLog("get token:" + token);
} catch (ApiException e) {
Log.e(TAG, "get token failed, " + e);
showLog("get token failed, " + e);
}
}
}.start();
}
/**
* void deleteToken(String appId, String scope) throws ApiException
* This method is used to obtain a token. After a token is deleted, the corresponding AAID will not be deleted.
* This method is a synchronous method. Do not call it in the main thread. Otherwise, the main thread may be blocked.
*/
private void deleteToken() {
showLog("deleteToken:begin");
new Thread() {
@Override
public void run() {
try {
// read from agconnect-services.json
String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
HmsInstanceId.getInstance(MainActivity.this).deleteToken(appId, "HCM");
Log.i(TAG, "deleteToken success.");
showLog("deleteToken success");
} catch (ApiException e) {
Log.e(TAG, "deleteToken failed." + e);
showLog("deleteToken failed." + e);
}
}
}.start();
}
/**
* Set up enable or disable the display of notification messages.
* @param enable enabled or not
*/
private void setReceiveNotifyMsg(final boolean enable) {
showLog("Control the display of notification messages:begin");
if (enable) {
HmsMessaging.getInstance(this).turnOnPush().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
showLog("turnOnPush Complete");
tvSetPush.setText(R.string.set_push_unable);
} else {
showLog("turnOnPush failed: cause=" + task.getException().getMessage());
}
}
});
} else {
HmsMessaging.getInstance(this).turnOffPush().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
showLog("turnOffPush Complete");
tvSetPush.setText(R.string.set_push_enable);
} else {
showLog("turnOffPush failed: cause =" + task.getException().getMessage());
}
}
});
}
}
/**
* to subscribe to topics in asynchronous mode.
*/
private void addTopic() {
final TopicDialog topicDialog = new TopicDialog(this, true);
topicDialog.setOnDialogClickListener(new OnDialogClickListener() {
@Override
public void onConfirmClick(String msg) {
topicDialog.dismiss();
try {
HmsMessaging.getInstance(MainActivity.this).subscribe(msg).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "subscribe Complete");
showLog("subscribe Complete");
} else {
showLog("subscribe failed: ret=" + task.getException().getMessage());
}
}
});
} catch (Exception e) {
showLog("subscribe failed: exception=" + e.getMessage());
}
}
@Override
public void onCancelClick() {
topicDialog.dismiss();
}
});
topicDialog.show();
}
/**
* to unsubscribe to topics in asynchronous mode.
*/
private void deleteTopic() {
final TopicDialog topicDialog = new TopicDialog(this, false);
topicDialog.setOnDialogClickListener(new OnDialogClickListener() {
@Override
public void onConfirmClick(String msg) {
topicDialog.dismiss();
try {
HmsMessaging.getInstance(MainActivity.this).unsubscribe(msg).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
showLog("unsubscribe Complete");
} else {
showLog("unsubscribe failed: ret=" + task.getException().getMessage());
}
}
});
} catch (Exception e) {
showLog("unsubscribe failed: exception=" + e.getMessage());
}
}
@Override
public void onCancelClick() {
topicDialog.dismiss();
}
});
topicDialog.show();
}
/**
* MyReceiver
*/
public clreplaced MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.getString("msg") != null) {
String content = bundle.getString("msg");
showLog(content);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
public void showLog(final String log) {
runOnUiThread(new Runnable() {
@Override
public void run() {
View tvView = findViewById(R.id.tv_log);
View svView = findViewById(R.id.sv_log);
if (tvView instanceof TextView) {
((TextView) tvView).setText(log);
}
if (svView instanceof ScrollView) {
((ScrollView) svView).fullScroll(View.FOCUS_DOWN);
}
}
});
}
private void sendRegTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
/**
* In Opening a Specified Page of an App, how to Generate Intent parameters.
*/
private void generateIntentUri() {
Intent intent = new Intent(Intent.ACTION_VIEW);
// You can add parameters in either of the following ways:
// Define a scheme protocol, for example, pushscheme://com.huawei.codelabpush/deeplink?.
// way 1 start: Use ampersands (&) to separate key-value pairs. The following is an example:
intent.setData(Uri.parse("pushscheme://com.huawei.codelabpush/deeplink?name=abc&age=180"));
// way 1 end. In this example, name=abc and age=180 are two key-value pairs separated by an ampersand (&).
// way 2 start: Directly add parameters to the Intent.
// intent.setData(Uri.parse("pushscheme://com.huawei.codelabpush/deeplink?"));
// intent.putExtra("name", "abc");
// intent.putExtra("age", 180);
// way 2 end.
// The following flag is mandatory. If it is not added, duplicate messages may be displayed.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String intentUri = intent.toUri(Intent.URI_INTENT_SCHEME);
// The value of intentUri will be replacedigned to the intent parameter in the message to be sent.
Log.d("intentUri", intentUri);
showLog(intentUri);
// You can start the deep link activity with the following code.
// intent.setClreplaced(this, DeeplinkActivity.clreplaced);
// startActivity(intent);
}
/**
* Simulate pulling up the application custom page by action.
*/
private void openActivityByAction() {
Intent intent = new Intent("com.huawei.codelabpush.intent.action.test");
// You can start the deep link activity with the following code.
intent.setClreplaced(this, Deeplink2Activity.clreplaced);
startActivity(intent);
}
private void isAutoInitEnabled() {
Log.i(TAG, "isAutoInitEnabled:" + HmsMessaging.getInstance(this).isAutoInitEnabled());
showLog("isAutoInitEnabled:" + HmsMessaging.getInstance(this).isAutoInitEnabled());
}
private void setAutoInitEnabled(final boolean enable) {
if (enable) {
HmsMessaging.getInstance(this).setAutoInitEnabled(true);
Log.i(TAG, "setAutoInitEnabled: true");
showLog("setAutoInitEnabled: true");
tvSetAutoInit.setText(R.string.AutoInitDisabled);
} else {
HmsMessaging.getInstance(this).setAutoInitEnabled(false);
Log.i(TAG, "setAutoInitEnabled: false");
showLog("setAutoInitEnabled: false");
tvSetAutoInit.setText(R.string.AutoInitEnabled);
}
}
}
17
Source : AliPayTool.java
with Apache License 2.0
from hexingbo
with Apache License 2.0
from hexingbo
/**
* @author vondear
*/
public clreplaced AliPayTool {
private static final int SDK_PAY_FLAG = 1;
private static OnSuccessAndErrorListener sOnSuccessAndErrorListener;
@SuppressLint("HandlerLeak")
private static Handler mHandler = new Handler() {
@SuppressWarnings("unused")
public void handleMessage(Message msg) {
switch(msg.what) {
case SDK_PAY_FLAG:
{
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
// 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。
// 同步返回需要验证的信息
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
// 判断resultStatus 为9000则代表支付成功
if (TextUtils.equals(resultStatus, "9000")) {
sOnSuccessAndErrorListener.onSuccess(resultStatus);
} else {
// 该笔订单真实的支付结果,需要依赖服务端的异步通知。
sOnSuccessAndErrorListener.onError(resultStatus);
}
break;
}
default:
break;
}
}
};
public static void aliPay(final Activity activity, String appid, boolean isRsa2, String alipay_rsa_private, AliPayModel aliPayModel, OnSuccessAndErrorListener onRxHttp1) {
sOnSuccessAndErrorListener = onRxHttp1;
Map<String, String> params = AliPayOrderTool.buildOrderParamMap(appid, isRsa2, aliPayModel.getOutTradeNo(), aliPayModel.getName(), aliPayModel.getMoney(), aliPayModel.getDetail());
String orderParam = AliPayOrderTool.buildOrderParam(params);
String privateKey = alipay_rsa_private;
String sign = AliPayOrderTool.getSign(params, privateKey, isRsa2);
final String orderInfo = orderParam + "&" + sign;
Runnable payRunnable = new Runnable() {
@Override
public void run() {
PayTask alipay = new PayTask(activity);
Map<String, String> result = alipay.payV2(orderInfo, true);
Log.i("msp", result.toString());
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
Thread payThread = new Thread(payRunnable);
payThread.start();
}
}
17
Source : ActivityZipEncrypt.java
with Apache License 2.0
from hexingbo
with Apache License 2.0
from hexingbo
/**
* @author vondear
*/
public clreplaced ActivityZipEncrypt extends ActivityBase {
@BindView(R.id.btn_create_folder)
Button mBtnCreateFolder;
@BindView(R.id.btn_zip)
Button mBtnZip;
@BindView(R.id.tv_state)
TextView mTvState;
@BindView(R.id.rx_replacedle)
Rxreplacedle mRxreplacedle;
@BindView(R.id.btn_upzip)
Button mBtnUpzip;
@BindView(R.id.btn_zip_delete_dir)
Button mBtnZipDeleteDir;
@BindView(R.id.Progress)
ProgressBar mProgress;
private File fileDir;
private File fileTempDir;
private File unZipDirFile;
private File fileZip;
private String zipPath;
private String zipParentPath;
private String zipTempDeletePath;
private String unzipPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zip_encrypt);
ButterKnife.bind(this);
mRxreplacedle.setLeftFinish(mContext);
zipParentPath = RxFileTool.getRootPath().getAbsolutePath() + File.separator + "RxTool";
zipTempDeletePath = RxFileTool.getRootPath().getAbsolutePath() + File.separator + "RxTool" + File.separator + "RxTempTool";
unzipPath = RxFileTool.getRootPath().getAbsolutePath() + File.separator + "解压缩文件夹";
zipPath = RxFileTool.getRootPath().getAbsolutePath() + File.separator + "Rxtool.zip";
unZipDirFile = new File(unzipPath);
if (!unZipDirFile.exists()) {
unZipDirFile.mkdirs();
}
}
@OnClick({ R.id.btn_create_folder, R.id.btn_zip, R.id.btn_upzip, R.id.btn_zip_delete_dir })
public void onViewClicked(View view) {
switch(view.getId()) {
case R.id.btn_create_folder:
fileDir = new File(zipParentPath);
fileTempDir = new File(zipTempDeletePath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
if (!fileTempDir.exists()) {
fileTempDir.mkdirs();
}
try {
File file = File.createTempFile("被压缩文件ŐεŐ", ".txt", fileDir);
File file1 = File.createTempFile("待删除文件o(╥﹏╥)o", ".txt", fileTempDir);
} catch (IOException e) {
e.printStackTrace();
}
mTvState.setText("临时文件 创建成功,文件位于根目录的RxTool里(✺ω✺)");
break;
case R.id.btn_zip:
fileZip = new File(zipPath);
if (fileZip.exists()) {
RxFileTool.deleteFile(fileZip);
Logger.d("导出文件已存在,将之删除");
}
if (fileDir != null) {
if (fileDir.exists()) {
String result = RxZipTool.zipEncrypt(fileDir.getAbsolutePath(), fileZip.getAbsolutePath(), true, "123456");
mTvState.setText("压缩并加密成功,路径" + result);
} else {
RxToast.error("导出的文件不存在");
}
} else {
RxToast.error("导出的文件不存在");
}
break;
case R.id.btn_upzip:
List<File> zipFiles = RxZipTool.unzipFileByKeyword(fileZip, unZipDirFile, "123456");
String str = "导出文件列表(*▽*)\n";
if (zipFiles != null) {
for (File zipFile : zipFiles) {
str += zipFile.getAbsolutePath() + "\n\n";
}
}
mTvState.setText(str);
// RxZipTool.Unzip(fileZip, unZipDirFile.getAbsolutePath(), "123456", "GBK", _handler, false);
break;
case R.id.btn_zip_delete_dir:
if (RxZipTool.removeDirFromZipArchive(zipPath, "RxTool" + File.separator + "RxTempTool")) {
mTvState.setText("RxTempTool 删除成功");
} else {
mTvState.setText("RxTempTool 删除失败");
}
break;
default:
break;
}
}
@SuppressLint("HandlerLeak")
private Handler _handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case RxZipTool.CompressStatus.START:
{
mTvState.setText("Start...");
mProgress.setVisibility(View.VISIBLE);
break;
}
case RxZipTool.CompressStatus.HANDLING:
{
Bundle bundle = msg.getData();
int percent = bundle.getInt(RxZipTool.CompressKeys.PERCENT);
mTvState.setText(percent + "%");
mProgress.setProgress(percent);
break;
}
case RxZipTool.CompressStatus.ERROR:
{
Bundle bundle = msg.getData();
String error = bundle.getString(RxZipTool.CompressKeys.ERROR);
mTvState.setText(error);
break;
}
case RxZipTool.CompressStatus.COMPLETED:
{
mTvState.setText("Completed");
mProgress.setVisibility(View.INVISIBLE);
break;
}
default:
break;
}
}
};
}
17
Source : MainApplication.java
with MIT License
from Haocen2004
with MIT License
from Haocen2004
public clreplaced MainApplication extends Application {
private SharedPreferences app_pref;
@Override
public void onCreate() {
super.onCreate();
CrashReport.initCrashReport(getApplicationContext(), "4bfa7b722e", true);
AVOSCloud.initialize(this, "VMh6lRyykuNDyhXxoi996cGI-gzGzoHsz", "RWvHCY9qXzX1BH4L72J9RI1I", "https://vmh6lryy.lc-cn-n1-shared.com");
if (DEBUG) {
AVOSCloud.setLogLevel(AVLogger.Level.DEBUG);
}
app_pref = getDefaultSharedPreferences(this);
if (app_pref.getBoolean("is_first_run", true) || app_pref.getInt("version", 1) < VERSION_CODE) {
app_pref.edit().putBoolean("is_first_run", false).putInt("version", VERSION_CODE).apply();
if (!app_pref.contains("auto_confirm")) {
app_pref.edit().putBoolean("auto_confirm", false).apply();
}
if (!app_pref.contains("enable_ad")) {
app_pref.edit().putBoolean("enable_ad", true).apply();
}
if (!app_pref.contains("server_type")) {
app_pref.edit().putString("server_type", "Official").apply();
}
if (!app_pref.contains("showBetaInfo")) {
app_pref.edit().putBoolean("showBetaInfo", DEBUG).apply();
}
if (!app_pref.contains("custom_username")) {
app_pref.edit().putString("custom_username", "崩坏3扫码器用户").apply();
}
if (!app_pref.contains("check_update")) {
app_pref.edit().putBoolean("check_update", !getPackageName().contains("dev")).apply();
}
if (!app_pref.contains("official_type")) {
app_pref.edit().putInt("official_type", 0).apply();
}
}
CHECK_VER = app_pref.getBoolean("check_update", true);
if (CHECK_VER) {
new Thread(update_rb).start();
}
}
@SuppressLint("HandlerLeak")
Handler update_check_hd = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String feedback = data.getString("value");
feedback = feedback.substring(1, feedback.length() - 1).replaceAll("\\\\", "");
BuglyLog.i("Update", "handleMessage: " + feedback);
try {
JSONObject json = new JSONObject(feedback);
app_pref.edit().putString("bh_ver", json.getString("bh_ver")).apply();
int sp_ver = app_pref.getInt("sponsors_db_ver", 0);
if (sp_ver < json.getInt("sponsors_db_ver")) {
new SponsorRepo(getApplicationContext()).refreshSponsors();
app_pref.edit().putInt("sponsors_db_ver", json.getInt("sponsors_db_ver")).apply();
}
if (!getPackageName().contains("dev") && app_pref.getInt("version", VERSION_CODE) < json.getInt("ver")) {
showUpdateDialog(json.getString("ver_name"), json.getString("update_url"), json.getString("logs").replaceAll("&n", "\n"));
}
} catch (Exception e) {
e.printStackTrace();
BuglyLog.d("Update", "Check Update Failed");
app_pref.edit().putString("bh_ver", BH_VER).apply();
}
BH_VER = app_pref.getString("bh_ver", BH_VER);
}
};
private void showUpdateDialog(String ver, String url, String logs) {
final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
normalDialog.setreplacedle("获取到新版本: " + ver);
normalDialog.setMessage("更新日志:\n" + logs);
normalDialog.setPositiveButton("打开更新链接", (dialog, which) -> {
openUrl(url, this);
dialog.dismiss();
});
normalDialog.setCancelable(false);
normalDialog.show();
}
Runnable update_rb = () -> {
String feedback = Network.sendPost("https://service-beurmroh-1256541670.sh.apigw.tencentcs.com/version", "");
try {
if (feedback.isEmpty()) {
return;
}
} catch (Exception e) {
return;
}
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", feedback);
msg.setData(data);
update_check_hd.sendMessage(msg);
};
}
17
Source : Vivo.java
with MIT License
from Haocen2004
with MIT License
from Haocen2004
public clreplaced Vivo implements LoginImpl {
private final Activity activity;
private boolean isLogin;
private String uid;
private String token;
private RoleData roleData;
private final String device_id;
private static final String TAG = "Vivo Login";
private final VivoAccountCallback callback = new VivoAccountCallback() {
@Override
public void onVivoAccountLogin(String s, String s1, String s2) {
uid = s1;
token = s2;
doBHLogin();
// roleData = new RoleData()
}
@Override
public void onVivoAccountLogout(int i) {
makeToast(activity.getString(R.string.logout));
isLogin = false;
}
@Override
public void onVivoAccountLoginCancel() {
isLogin = false;
}
};
public Vivo(Activity activity) {
this.activity = activity;
device_id = Tools.getDeviceID(activity);
VivoUnionSDK.initSdk(activity, VIVO_APP_KEY, BuildConfig.DEBUG);
VivoUnionSDK.registerAccountCallback(activity, callback);
}
@Override
public void login() {
VivoUnionSDK.login(activity);
}
@Override
public void logout() {
}
@Override
public RoleData getRole() {
return roleData;
}
@Override
public boolean isLogin() {
return isLogin;
}
@SuppressLint("HandlerLeak")
Handler login_handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String feedback = data.getString("value");
// Logger.debug(feedback);
BuglyLog.d(TAG, "handleMessage: " + feedback);
JSONObject feedback_json = null;
try {
feedback_json = new JSONObject(feedback);
} catch (JSONException e) {
e.printStackTrace();
}
// Logger.info(feedback);
BuglyLog.i(TAG, "handleMessage: " + feedback);
try {
if (feedback_json.getInt("retcode") == 0) {
JSONObject data_json2 = feedback_json.getJSONObject("data");
String combo_id = data_json2.getString("combo_id");
String open_id = data_json2.getString("open_id");
String combo_token = data_json2.getString("combo_token");
String account_type = data_json2.getString("account_type");
roleData = new RoleData(activity, open_id, "", combo_id, combo_token, "19", account_type, "vivo", 2);
isLogin = true;
makeToast(activity.getString(R.string.login_succeed));
} else {
makeToast(feedback_json.getString("message"));
isLogin = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Runnable login_runnable = new Runnable() {
@Override
public void run() {
String data_json = "{\"authtoken\":\"" + token + "\"}";
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", verifyAccount(activity, "19", data_json));
msg.setData(data);
login_handler.sendMessage(msg);
}
};
public void doBHLogin() {
new Thread(login_runnable).start();
}
@SuppressLint("ShowToast")
private void makeToast(String result) {
try {
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Looper.prepare();
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
Looper.loop();
}
}
}
See More Examples