Commit fe51a9a1 by qyw

update

parent d4ea460a
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.ifavine.pay"
minSdkVersion 16
targetSdkVersion 25
versionCode 120
versionName "1.2.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
maven {
url "http://dl.bintray.com/lukaville/maven"
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile project(':library')
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:design:25.1.1'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.squareup.okhttp3:okhttp:3.7.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.android.support:support-v4:25.1.1'
testCompile 'junit:junit:4.12'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.github.jdsjlzx:LRecyclerView:1.3.4'
compile 'com.android.support:recyclerview-v7:25.1.1'
compile 'com.mph.okdroid:okdroid:1.0.0'
compile files('libs/ScanerLibrary V1.5.jar')
compile 'com.android.support:cardview-v7:25.1.1'
compile 'pub.devrel:easypermissions:0.2.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.feezu.liuli:timeselector:1.1.3+'
compile 'com.jph.takephoto:takephoto_library:4.0.3'
compile 'org.greenrobot:greendao:3.2.2'
compile 'com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1'
compile 'com.github.franmontiel:PersistentCookieJar:v1.0.1'
compile 'com.gjiazhe:wavesidebar:1.3'
compile 'com.nbsp:library:1.6'
compile 'com.github.sendtion:XRichText:1.1'
compile 'me.yokeyword:swipebackfragment:0.3.0'
compile 'com.github.Hitomis.transferee:Transferee:v1.0.0'
compile 'com.github.Hitomis.transferee:GlideLoader:v1.0.0' // load with glide
compile 'com.github.Hitomis.transferee:UniversalLoader:v1.0.0'
// load with universal-image-loader
compile project(path: ':lib-zxing')
compile 'pub.devrel:easypermissions:0.2.0'
testCompile 'junit:junit:4.12'
compile 'com.github.w446108264:XhsEmoticonsKeyboard:2.0.3'
compile 'com.github.w446108264:AndroidEmoji:1.3-withsource'
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in E:\Android_soft_new\sdk_studio\android-sdk-windows/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ifavine.pay">
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 向SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:name=".common.AppContext"
android:allowBackup="true"
android:icon="@mipmap/icon"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".ui.activity.MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask"
android:screenOrientation="landscape"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".utils.DownloadService" />
</application>
</manifest>
\ No newline at end of file
package com.ifavine.pay.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ifavine.pay.utils.BaseUtil;
/**
* Created by Administrator on 2018/10/18.
*/
public class SpinnerAdapter extends ArrayAdapter<String> {
Context context;
String[] items = new String[]{};
public SpinnerAdapter(final Context context,
final int textViewResourceId, final String[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
this.context = context;
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(
android.R.layout.simple_spinner_item, parent, false);
}
TextView tv = (TextView) convertView
.findViewById(android.R.id.text1);
tv.setPadding(10, 10, 10, 10);
tv.setText(items[position]);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(Color.BLACK);
tv.setTextSize(BaseUtil.Dp2Px(context, 23));
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(
android.R.layout.simple_spinner_item, parent, false);
}
TextView tv = (TextView) convertView
.findViewById(android.R.id.text1);
tv.setPadding(10, 10, 10, 10);
tv.setText(items[position]);
tv.setGravity(Gravity.CENTER);
tv.setTextColor(Color.BLACK);
tv.setTextSize(BaseUtil.Dp2Px(context, 20));
return convertView;
}
}
\ No newline at end of file
package com.ifavine.pay.api;
import com.ifavine.pay.vo.CommonListResponse;
import com.ifavine.pay.vo.CommonResponse;
import com.ifavine.pay.vo.User;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public abstract interface APIService {
@FormUrlEncoded
@POST("getMsgDaliyList")
Call<CommonResponse<User>> getMsgDaliyList(@Field("data") String data);
@FormUrlEncoded
@POST("getMeetingTaskReplyList")
Call<CommonListResponse<User>> getMsgDaliyList2(@Field("data") String data);
}
package com.ifavine.pay.api;
import com.ifavine.pay.vo.CommonListResponse;
import com.ifavine.pay.vo.CommonResponse;
import com.ifavine.pay.vo.User;
import org.json.JSONObject;
import retrofit2.Call;
/**
* Created by tree on 7/13/2016.
*/
public class APIWrapper extends RetrofitUtil {
private static APIWrapper mAPIWrapper;
public static APIWrapper getInstance() {
if (mAPIWrapper == null) mAPIWrapper = new APIWrapper();
return mAPIWrapper;
}
/**
* 日事日毕列表
*
* @param Page
* @param PageSize
* @return
*/
public Call<CommonResponse<User>> getMsgDaliyList(int Page, int PageSize) {
JSONObject data = new JSONObject();
try {
data.put("Page", Page);
data.put("PageSize", PageSize);
} catch (Exception e) {
e.printStackTrace();
}
return getAPIService().getMsgDaliyList(data.toString());
}
/**
* * 日事日毕列表
* status :0待处理 1处理中 2待评价 3未关闭 4关闭
* DutyStatus : 1、已认领 2、可认领 3、需指定
* Satisfied =0或null未操作 =1满意 =2不满意(正式机)
*
* @param Page
* @param PageSize
* @param Status
* @param KeyWord
* @param Sno
* @param CreatorID
* @param Title
* @param StartTime
* @param EndTime
* @return
*/
public Call<CommonListResponse<User>> getMsgDaliyList2(int Page, int PageSize, int Status, String KeyWord, String Sno, String CreatorID, String Title, String StartTime, String EndTime) {
JSONObject data = new JSONObject();
try {
data.put("Page", Page);
data.put("PageSize", PageSize);
data.put("Status", Status);
data.put("KeyWord", KeyWord);
data.put("Sno", Sno);
data.put("CreatorID", CreatorID);
data.put("Title", Title);
data.put("StartTime", StartTime);
data.put("EndTime", EndTime);
} catch (Exception e) {
e.printStackTrace();
}
return getAPIService().getMsgDaliyList2(data.toString());
}
}
\ No newline at end of file
package com.ifavine.pay.api;
import com.ifavine.pay.common.AppContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
/**
* Created by Administrator on 2017/3/17.
*/
public class HttpsUtils {
// 证书数据
private static List<byte[]> CERTIFICATES_DATA = new ArrayList<>();
/**
* 添加https证书
*/
public synchronized static void initCertificate() {
InputStream inputStream = null;
// 添加https证书
try {
String[] certFiles = AppContext.getInstance().getAssets().list("certs");
if (certFiles != null) {
for (String cert : certFiles) {
inputStream = AppContext.getInstance().getAssets().open("certs/" + cert);
// 这里将证书读取出来,,放在配置中byte[]里
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (inputStream != null) {
try {
int ava = 0;// 数据当次可读长度
int len = 0;// 数据总长度
ArrayList<byte[]> data = new ArrayList<>();
while ((ava = inputStream.available()) > 0) {
byte[] buffer = new byte[ava];
inputStream.read(buffer);
data.add(buffer);
len += ava;
}
byte[] buff = new byte[len];
int dstPos = 0;
for (byte[] bytes : data) {
int length = bytes.length;
System.arraycopy(bytes, 0, buff, dstPos, length);
dstPos += length;
}
CERTIFICATES_DATA.add(buff);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static SSLSocketFactory createSSLSocketFactory() {
initCertificate();
// 添加证书
List<InputStream> certificates = new ArrayList<>();
List<byte[]> certs_data = CERTIFICATES_DATA;
// 将字节数组转为数组输入流
if (certs_data != null && !certs_data.isEmpty()) {
for (byte[] bytes : certs_data) {
certificates.add(new ByteArrayInputStream(bytes));
}
}
SSLSocketFactory sslSocketFactory = getSocketFactory(certificates);
return sslSocketFactory;
}
/**
* 添加证书
*
* @param certificates
*/
private static SSLSocketFactory getSocketFactory(List<InputStream> certificates) {
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
try {
for (int i = 0, size = certificates.size(); i < size; ) {
InputStream certificate = certificates.get(i);
String certificateAlias = Integer.toString(i++);
keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
if (certificate != null)
certificate.close();
}
} catch (IOException e) {
e.printStackTrace();
}
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.ifavine.pay.api;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* Created by tree on 1/4/2017.
* 自定义 json转换器
*/
public class JsonConverterFactory extends Converter.Factory {
public static JsonConverterFactory create() {
return create(new Gson());
}
public static JsonConverterFactory create(Gson gson) {
return new JsonConverterFactory(gson);
}
private final Gson gson;
private JsonConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new JsonResponseBodyConverter<>(gson, adapter); //响应
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new JsonRequestBodyConverter<>(gson, adapter); //请求
}
}
package com.ifavine.pay.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;
/**
* Created by tree on 1/4/2017.
* 自定义请求RequestBody
*/
public class JsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
/**
* 构造器
*/
public JsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert(T value) throws IOException {
//加密
//APIBodyData data = new APIBodyData();
Log.i("aaaaa", "request data:" + value.toString());
//data.setData(XXTEA.Encrypt(value.toString(), HttpConstant.KEY));
String postBody = gson.toJson(value); //对象转化成json
Log.i("aaaaa", "request data:" + postBody);
//Log.i("xiaozhang", "转化后的数据:" + postBody);
return RequestBody.create(MEDIA_TYPE, postBody);
}
}
package com.ifavine.pay.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import okhttp3.ResponseBody;
import retrofit2.Converter;
/**
* Created by tree on 1/4/2017.
* 自定义响应ResponseBody
*/
public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson mGson;//gson对象
private final TypeAdapter<T> adapter;
/**
* 构造器
*/
public JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.mGson = gson;
this.adapter = adapter;
}
/**
* 转换
*
* @param responseBody
* @return
* @throws IOException
*/
@Override
public T convert(ResponseBody responseBody) throws IOException {
String data = null;
try {
//数据解密
JSONObject obj = new JSONObject(responseBody.string());
data = obj.getString("data");
Log.i("aaaaa", "response data:" + data);
} catch (Exception e) {
e.printStackTrace();
}
JsonReader jsonReader = mGson.newJsonReader(new InputStreamReader(getStringStream(data)));
try {
return adapter.read(jsonReader);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将一个字符串转化为输入流
*/
public static InputStream getStringStream(String str) {
if (str != null && !str.trim().equals("")) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes());
return in;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
}
package com.ifavine.pay.api;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.ifavine.pay.common.AppContext;
import com.ifavine.pay.common.Constants;
import com.ifavine.pay.utils.SPUtil;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
/**
* Created by tree on 7/6/2016.
*/
public class RetrofitUtil {
/**
* 服务器地址
*/
private static final String API_HOST = Constants.BASE_URL;
private static APIService mAPIService;
private static Retrofit mRetrofit;
public static APIService getAPIService() {
if (mAPIService == null) mAPIService = (APIService) getRetrofit().create(APIService.class);
return mAPIService;
}
private static Retrofit getRetrofit() {
if (mRetrofit == null) {
ClearableCookieJar cookieJar =
new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(AppContext.getInstance()));
OkHttpClient.Builder localBuilder =
new OkHttpClient.Builder()
.connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
.readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
.writeTimeout(30 * 1000, TimeUnit.MILLISECONDS)
.addInterceptor(new RetryInterceptor(3))
.cookieJar(cookieJar)
// .sslSocketFactory(HttpsUtils.createSSLSocketFactory())
.retryOnConnectionFailure(true)
.addInterceptor(
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
String agent = SPUtil.getInstance().readString("UserAgent");
Request originRequest = chain.request();
HttpUrl httpUrl = originRequest.url();
String url = httpUrl.toString();
Request.Builder builder = originRequest.newBuilder();
builder.url(url)
.header("User-Agent", agent)
.header("Content-Type", "application/json;charset=utf-8")
.addHeader("Accept", "application/json")
.addHeader("Connection", "keep-alive");
Request newRequest = builder.build();
Response newResponse = chain.proceed(newRequest);
return newResponse;
}
});
HttpLoggingInterceptor localHttpLoggingInterceptor = new HttpLoggingInterceptor();
localHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
localBuilder.addInterceptor(localHttpLoggingInterceptor).build();
OkHttpClient client = localBuilder.build();
mRetrofit = new Retrofit.Builder().baseUrl(API_HOST)
.addConverterFactory(JsonConverterFactory.create()) // 添加自定义转换器
.client(client).build();
System.setProperty("java.net.preferIPv4Stack", "true");
}
return mRetrofit;
}
}
package com.ifavine.pay.api;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* 重试拦截器
*/
public class RetryInterceptor implements Interceptor {
public int maxRetry;//最大重试次数
private int retryNum = 0;//假如设置为3次重试的话,则最大可能请求4次(默认1次+3次重试)
public RetryInterceptor(int maxRetry) {
this.maxRetry = maxRetry;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
System.out.println("retryNum=" + retryNum);
Response response = chain.proceed(request);
while (!response.isSuccessful() && retryNum < maxRetry) {
retryNum++;
System.out.println("retryNum=" + retryNum);
response = chain.proceed(request);
}
return response;
}
}
\ No newline at end of file
package com.ifavine.pay.common;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class AppConfig {
private static final String APP_CONFIG = "app_config";
private static AppConfig appConfig;
private Context mContext;
public final static String CONF_COOKIE = "cookie";
public final static String CONF_APP_UNIQUEID = "APP_UNIQUEID";
public static final String KEY_LOAD_IMAGE = "KEY_LOAD_IMAGE";
public static final String KEY_NOTIFICATION_ACCEPT = "KEY_NOTIFICATION_ACCEPT";
public static final String KEY_NOTIFICATION_SOUND = "KEY_NOTIFICATION_SOUND";
public static final String KEY_NOTIFICATION_VIBRATION = "KEY_NOTIFICATION_VIBRATION";
public static final String KEY_NOTIFICATION_DISABLE_WHEN_EXIT =
"KEY_NOTIFICATION_DISABLE_WHEN_EXIT";
public static final String KEY_CHECK_UPDATE = "KEY_CHECK_UPDATE";
public static final String KEY_DOUBLE_CLICK_EXIT = "KEY_DOUBLE_CLICK_EXIT";
public static final String KEY_TWEET_DRAFT = "KEY_TWEET_DRAFT";
public static final String KEY_NOTE_DRAFT = "KEY_NOTE_DRAFT";
public static final String KEY_FRITST_START = "KEY_FRIST_START";
public static final String KEY_NIGHT_MODE_SWITCH = "night_mode_switch";
public static final String APP_QQ_KEY = "";
// 默认存放图片的路径
public final static String DEFAULT_SAVE_IMAGE_PATH = Environment.getExternalStorageDirectory()
+ File.separator
+ "monk"
+ File.separator
+ "top_img"
+ File.separator;
// 默认存放文件下载的路径
public final static String DEFAULT_SAVE_FILE_PATH = Environment.getExternalStorageDirectory()
+ File.separator
+ "monk"
+ File.separator
+ "top_download"
+ File.separator;
public static AppConfig getAppConfig(Context context) {
if (appConfig == null) {
appConfig = new AppConfig();
appConfig.mContext = context;
}
return appConfig;
}
public static SharedPreferences getSharedPrefereneces(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public String get(String key) {
Properties props = get();
return (props != null) ? props.getProperty(key) : null;
}
public Properties get() {
FileInputStream fis = null;
Properties props = new Properties();
try {
// 读取files目录下的config
// fis = activity.openFileInput(APP_CONFIG);
// 读取app_config目录下的config
File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
fis = new FileInputStream(dirConf.getPath() + File.separator + APP_CONFIG);
props.load(fis);
} catch (Exception e) {
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return props;
}
private void setProps(Properties p) {
FileOutputStream fos = null;
try {
// 把config建在files目录下
// fos = activity.openFileOutput(APP_CONFIG, Context.MODE_PRIVATE);
// 把config建在(自定义)app_config的目录下
// 把config建在(自定义)app_config的目录下
File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
File conf = new File(dirConf, APP_CONFIG);
fos = new FileOutputStream(conf);
p.store(fos, null);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
}
public void set(Properties ps) {
Properties props = get();
props.putAll(ps);
setProps(props);
}
public void set(String key, String value) {
Properties props = get();
props.setProperty(key, value);
setProps(props);
}
public void remove(String... key) {
Properties props = get();
for (String k : key)
props.remove(k);
setProps(props);
}
/**
* 比较时间是否在1小时内,是则为有效期
*
* @param time time
* @return isExpiryDate true or false
*/
public static boolean isExpiryDate(String time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date date = format.parse(time);
long delta = new Date().getTime() - date.getTime();
if (delta < 24L * 3600000L) {
return true;
}
;
return false;
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
}
package com.ifavine.pay.common;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ifavine.pay.ui.base.BaseApplication;
import com.ifavine.pay.utils.SPUtil;
import com.ifavine.pay.vo.User;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.List;
import java.util.Stack;
/**
* Created by tree on 7/4/2016.
*/
public class AppContext extends BaseApplication {
private static AppContext instance;
public static User mUser;
private HashSet<String> Msgs = new HashSet<>();
/**
* FONT_USE 发布时候要改为true
*/
public static final boolean FontUse = true;
/**
* 是否调试模式
*/
public static final boolean DebugModel = false;
/**
* 语言头部分
*/
public static String AcceptLanguage = "cn";
/**
* 系统版本
*/
public static String sAppVersionLocal = "1.0.0";
/**
* 服务端系统版本
*/
public static String sAppVersionServer = "1.0.0";
public static String sAppDownloadUrl;
public static String sAppVersionDesc;
/**
* 手机系统版本
*/
public static String sModileOsVersion = "android_4.2";
/**
* 手机型号
*/
public static String sMobileOsModel = "MOBILE";
/**
* 经度
*/
public static double sLongtitude;
/**
* 纬度
*/
public static double sLatitude;
@Override
public void onCreate() {
super.onCreate();
instance = this;
init();
}
private void init() {
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
//Bugly
Context context = getApplicationContext();
//// 获取当前包名
String packageName = context.getPackageName();
//// 获取当前进程名
String processName = getProcessName(android.os.Process.myPid());
getCurrentAppVer();
ZXingLibrary.initDisplayOpinion(this);
}
/**
* 获得当前app运行的AppContext
*/
public static AppContext getInstance() {
return instance;
}
/**
* 获取App安装包信息
*/
public PackageInfo getPackageInfo() {
PackageInfo info = null;
try {
info = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace(System.err);
}
if (info == null) info = new PackageInfo();
return info;
}
public boolean isMainProcess() {
ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
String mainProcessName = getPackageName();
int myPid = android.os.Process.myPid();
for (ActivityManager.RunningAppProcessInfo info : processInfos) {
if (info.pid == myPid && mainProcessName.equals(info.processName)) {
return true;
}
}
return false;
}
public void getCurrentAppVer() {
// 获取系统版本
try {
Log.i("aaaaa", "SDK_INT:" + Build.VERSION.SDK_INT);
PackageManager pm = getPackageManager();// context为当前Activity上下文
PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
sAppVersionLocal = pi.versionName;
sAppVersionServer = pi.versionName;
sModileOsVersion = Build.VERSION.RELEASE; // 获取版本号
sMobileOsModel = Build.MODEL; // 获取手机型号
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取进程号对应的进程名
*
* @param pid 进程号
* @return 进程名
*/
private static String getProcessName(int pid) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
String processName = reader.readLine();
if (!TextUtils.isEmpty(processName)) {
processName = processName.trim();
}
return processName;
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
return null;
}
public static String getExcptionName(Throwable e) {
String msg = e.toString();
if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
msg = "请求数据超时,请稍后重试";
} else if (e instanceof ConnectException) {
msg = "网络中断,请检查您的网络状态";
} else if (e instanceof JsonSyntaxException) {
msg = e.toString();
}
return msg;
}
// 记录打开的Activity
public static Stack<Activity> Acts = new Stack<Activity>();
public static void addActivity(Activity activity) {
Acts.add(activity);
}
public static void removeActivity(Activity activity) {
Acts.remove(activity);
}
public static void finishAllActivity() {
for (Activity activity : Acts) {
activity.finish();
}
}
public static void exitApp() {
finishAllActivity();
System.exit(0);
}
/**
* 获得登录用户的信息
*/
public User getUser() {
if (mUser == null) {
String data = SPUtil.getInstance().readString("UserData");
if (data != null) {
Gson gson = new Gson();
mUser = gson.fromJson(data, User.class);
}
}
return mUser;
}
public void saveUser(User user) {
mUser = user;
Gson gson = new Gson();
String data = gson.toJson(user);
Log.i("aaaaa", "saveUser:" + data);
SPUtil.getInstance().writeString("UserData", data);
}
public void setProperty(String key, String value) {
if (value == null) {
return;
}
AppConfig.getAppConfig(this).set(key, value);
}
/**
* 获取cookie时传AppConfig.CONF_COOKIE
*/
public String getProperty(String key) {
String res = AppConfig.getAppConfig(this).get(key);
return res;
}
public void removeProperty(String... key) {
AppConfig.getAppConfig(this).remove(key);
}
Handler handler = new Handler();
}
package com.ifavine.topmanage.common;
/**
* Created by Administrator on 2017/3/13.
*/
public enum AttendStatus {
Process(0),
Attend(1),
UnAttend(2),
None(3);//0未选择 1参加 2 不参加 3不是会议人员
private Integer text;
AttendStatus(Integer text) {
this.text = text;
}
public Integer value() {
return this.text;
}
}
package com.ifavine.pay.common;
/**
* Created by Administrator on 2017/5/10.
*/
public class Constants {
//public static final String BASE_URL = "http://si.ifavine.cn/OA/api/app/";
// public static final String IMAGE_URL = "http://sisource.ifavine.cn";
public static final String BASE_URL = "http://si.topcreating.com/OA/api/app/";
public static final String IMAGE_URL = "http://sisource.topcreating.com";
public static String LANG = "zn-cn";
public static String PREF_NAME = "pref_manage";
public static int PAGE_SIZE = 10;
public static String CONTACT_PAGE_SIZE = "20";
public static final String IMAGE_TEMP = "topoa/image_temp";
public static final String IMAGE_DOWNLOAD = "topoa/image_dowload";
public static final String SPKEY_LASTCHECKTIME = "SPKEY_LASTCHECKTIME";
public static final String MIN_DATE = "2017-01-01 00:00";
public static final String MAX_DATE = "2018-12-31 00:00";
public static int EMOTICON_CLICK_TEXT = 1;
public static int EMOTICON_CLICK_BIGIMAGE = 2;
}
package com.ifavine.pay.common;
/**
* Created by Administrator on 2017/3/13.
*/
public enum TaskStatus {
NotSolve(0),
Solved(1),
OutDateSolved(2),
OutDate(3);//0未解决 1解决 2过期解决 3过期
private Integer text;
TaskStatus(Integer text) {
this.text = text;
}
public Integer value() {
return this.text;
}
}
package com.ifavine.pay.interf;
/**
*
*/
public interface BaseViewInterface {
public void initView();
public void initData();
}
package com.ifavine.pay.listener;
import android.widget.TextView;
public interface OnMenuClickListener {
void onClick(TextView menuItem);
}
package com.ifavine.pay.ui.activity;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import com.ifavine.pay.R;
import com.ifavine.pay.adapter.SpinnerAdapter;
import com.ifavine.pay.ui.base.BaseActivity;
import com.ifavine.pay.utils.BaseUtil;
import com.ifavine.pay.utils.DialogMainSetUtils;
import com.ifavine.pay.utils.DialogUtil;
import com.ifavine.pay.view.PopWindowMainReport;
import com.ifavine.pay.view.PopWindowMainSet;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.BindView;
import butterknife.OnClick;
/**
* @author Administrator
*/
public class MainActivity extends BaseActivity {
@BindView(R.id.tv_date)
TextView tv_date;
@BindView(R.id.tv_set)
Button tv_set;
@BindView(R.id.tv_table)
Button tv_table;
private int startMin;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//无title
//requestWindowFeature(Window.FEATURE_NO_TITLE);
//全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
startMin = 0;
}
@Override
public void initData() {
super.initData();
date = System.currentTimeMillis();
startTimer();
//检查网络
pingNet("www.baidu.com");
}
private boolean pingNet(String address) {
try {
Process process = Runtime.getRuntime().exec("ping -c 3 -w 100 " + address);
InputStreamReader r = new InputStreamReader(process.getInputStream());
LineNumberReader returnData = new LineNumberReader(r);
String returnMsg = "";
String line = "";
while ((line = returnData.readLine()) != null) {
System.out.println(line);
returnMsg += line;
}
if (TextUtils.isEmpty(returnMsg)) {
System.out.println("与 " + address + " 连接不畅通.");
return false;
} else {
//0 received, 100% packet loss
if (returnMsg.indexOf("0 received") == 1 || returnMsg.indexOf("100% packet loss") == 1) {
System.out.println("与 " + address + " 连接不畅通.");
return false;
} else {
System.out.println("与 " + address + " 连接畅通.");
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@OnClick({R.id.tv_set, R.id.tv_table, R.id.tv_close, R.id.tv_reflesh})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_set:
new PopWindowMainSet(mContext, new PopWindowMainSet.CallBackPosition() {
@Override
public void selectIndex(int i) {
if (i == 0) {
DialogMainSetUtils.showRSTSetDialog(mContext, "饭堂窗口设置", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
}, null, true);
} else if (i == 1) {
DialogMainSetUtils.showSetAmtDialog(mContext, "消费金额设置", null, null, true);
} else if (i == 2) {
DialogMainSetUtils.showChangePwdDialog(mContext, "修改管理员密码", null, null, true);
}
}
}).showAtBottom(tv_set);
break;
case R.id.tv_table:
new PopWindowMainReport(mContext, new PopWindowMainReport.CallBackPosition() {
@Override
public void selectIndex(int index) {
if (index == 0) {
DialogMainSetUtils.showReportLocalDialog(mContext, "本机消费记录查询", null, true);
} else if (index == 1) {
DialogMainSetUtils.showReportRecordDialog(mContext, "消费记录查询", null, true);
} else if (index == 2) {
DialogMainSetUtils.showReportSumDialog(mContext, "每月消费汇总查询", null, true);
}
}
}).showAtBottom(tv_table);
break;
case R.id.tv_close:
DialogUtil.showConfirmDialog(mContext, null, "系统提示", "确认关闭应用?", "确定", "取消", new View.OnClickListener() {
@Override
public void onClick(View view) {
System.exit(0);
}
}, null, true);
break;
case R.id.tv_reflesh:
break;
}
}
// 初始化定时器
private long date;
private Timer timer;
private void startTimer() {
if (timer != null) {
return;
}
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
date += 1000;
handler.sendEmptyMessage(1);
}
}, 1000, 1000);
}
// 停止定时器
private void stopTimer() {
if (timer != null) {
timer.cancel();
// 一定设置为null,否则定时器不会被回收
timer = null;
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
tv_date.setText(BaseUtil.getDateFormat(date, "yyyy-MM-dd HH:mm:ss"));
break;
}
}
};
}
package com.ifavine.pay.ui.activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import com.ifavine.pay.R;
import com.ifavine.pay.ui.base.BaseActivity;
import com.ifavine.pay.utils.SPUtil;
import butterknife.BindView;
/**
* Powered by www.ifavine.com
*/
public class WelcomeActivity extends BaseActivity {
@BindView(R.id.iv_image)
ImageView ivImage;
@Override
protected int getLayoutId() {
return R.layout.activity_welcome;
}
@Override
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setToolbar(TOOL_BAR_TYPE_NONE, -1);
getWebAgent();
}
@Override
public void initView() {
super.initView();
}
@Override
public void initData() {
super.initData();
handler.sendEmptyMessageDelayed(0, 800);
// 全屏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
autoLogin();
finish();
}
};
@Override
protected void onPause() {
super.onPause();
handler.removeMessages(0);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeMessages(0);
}
private void autoLogin() {
boolean isShow = SPUtil.getInstance().readBoolean("ShowGuide");
if (isShow) {
boolean login = SPUtil.getInstance().readBoolean("user.autoLogin");
if (login) {
gotoActivity(MainActivity.class);
} else {
// gotoActivity(LoginActivity.class);
}
} else {
gotoActivity(MainActivity.class);
}
}
private String getWebAgent() {
WebView webview = new WebView(WelcomeActivity.this);
WebSettings settings = webview.getSettings();
// 获取到UserAgentString
String userAgent = settings.getUserAgentString();
Log.i("aaaaa", "userAgent:" + userAgent);
SPUtil.getInstance().writeString("UserAgent", userAgent);
return userAgent;
}
}
package com.ifavine.pay.ui.base;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ifavine.pay.R;
import com.ifavine.pay.utils.StringUtils;
public class BaseApplication extends Application {
private static String PREF_NAME = "creativelocker.pref";
private static String LAST_REFRESH_TIME = "last_refresh_time.pref";
static Context _context;
static Resources _resource;
private static String lastToast = "";
private static long lastToastTime;
private static boolean sIsAtLeastGB;
static {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
sIsAtLeastGB = true;
}
}
@Override
public void onCreate() {
super.onCreate();
_context = getApplicationContext();
_resource = _context.getResources();
}
public static synchronized BaseApplication context() {
return (BaseApplication) _context;
}
public static Resources resources() {
return _resource;
}
/**
* 放入已读文章列表中
*/
public static void putReadedPostList(String prefFileName, String key,
String value) {
SharedPreferences preferences = getPreferences(prefFileName);
int size = preferences.getAll().size();
Editor editor = preferences.edit();
if (size >= 100) {
editor.clear();
}
editor.putString(key, value);
apply(editor);
}
/**
* 读取是否是已读的文章列表
*
* @return
*/
public static boolean isOnReadedPostList(String prefFileName, String key) {
return getPreferences(prefFileName).contains(key);
}
/**
* 记录列表上次刷新时间
*
* @param key
* @param value
* @return void
* @author 火蚁
* 2015-2-9 下午2:21:37
*/
public static void putToLastRefreshTime(String key, String value) {
SharedPreferences preferences = getPreferences(LAST_REFRESH_TIME);
Editor editor = preferences.edit();
editor.putString(key, value);
apply(editor);
}
/**
* 获取列表的上次刷新时间
*
* @param key
* @return
* @author 火蚁
* 2015-2-9 下午2:22:04
*/
public static String getLastRefreshTime(String key) {
return getPreferences(LAST_REFRESH_TIME).getString(key, StringUtils.getCurTimeStr());
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void apply(Editor editor) {
if (sIsAtLeastGB) {
editor.apply();
} else {
editor.commit();
}
}
public static void set(String key, int value) {
Editor editor = getPreferences().edit();
editor.putInt(key, value);
apply(editor);
}
public static void set(String key, boolean value) {
Editor editor = getPreferences().edit();
editor.putBoolean(key, value);
apply(editor);
}
public static void set(String key, String value) {
Editor editor = getPreferences().edit();
editor.putString(key, value);
apply(editor);
}
public static boolean get(String key, boolean defValue) {
return getPreferences().getBoolean(key, defValue);
}
public static String get(String key, String defValue) {
return getPreferences().getString(key, defValue);
}
public static int get(String key, int defValue) {
return getPreferences().getInt(key, defValue);
}
public static long get(String key, long defValue) {
return getPreferences().getLong(key, defValue);
}
public static float get(String key, float defValue) {
return getPreferences().getFloat(key, defValue);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static SharedPreferences getPreferences() {
SharedPreferences pre = context().getSharedPreferences(PREF_NAME,
Context.MODE_MULTI_PROCESS);
return pre;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static SharedPreferences getPreferences(String prefName) {
return context().getSharedPreferences(prefName,
Context.MODE_MULTI_PROCESS);
}
public static int[] getDisplaySize() {
return new int[]{getPreferences().getInt("screen_width", 480),
getPreferences().getInt("screen_height", 854)};
}
public static void saveDisplaySize(Activity activity) {
DisplayMetrics displaymetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay()
.getMetrics(displaymetrics);
Editor editor = getPreferences().edit();
editor.putInt("screen_width", displaymetrics.widthPixels);
editor.putInt("screen_height", displaymetrics.heightPixels);
editor.putFloat("density", displaymetrics.density);
editor.commit();
}
public static String string(int id) {
return _resource.getString(id);
}
public static String string(int id, Object... args) {
return _resource.getString(id, args);
}
public static void showToast(int message) {
showToast(message, Toast.LENGTH_LONG, 0);
}
public static void showToast(String message) {
showToast(message, Toast.LENGTH_LONG, 0, Gravity.CENTER);
}
public static void showToast(int message, int icon) {
showToast(message, Toast.LENGTH_LONG, icon);
}
public static void showToast(String message, int icon) {
showToast(message, Toast.LENGTH_LONG, icon, Gravity.CENTER);
}
public static void showToastShort(int message) {
showToast(message, Toast.LENGTH_SHORT, 0);
}
public static void showToastShort(String message) {
showToast(message, Toast.LENGTH_SHORT, 0, Gravity.CENTER);
}
public static void showToastShort(int message, Object... args) {
showToast(message, Toast.LENGTH_SHORT, 0, Gravity.CENTER, args);
}
public static void showToast(int message, int duration, int icon) {
showToast(message, duration, icon, Gravity.CENTER);
}
public static void showToast(int message, int duration, int icon,
int gravity) {
showToast(context().getString(message), duration, icon, gravity);
}
public static void showToast(int message, int duration, int icon,
int gravity, Object... args) {
showToast(context().getString(message, args), duration, icon, gravity);
}
public static void showToast(String message, int duration, int icon,
int gravity) {
if (message != null && !message.equalsIgnoreCase("")) {
long time = System.currentTimeMillis();
if (!message.equalsIgnoreCase(lastToast)
|| Math.abs(time - lastToastTime) > 2000) {
View view = LayoutInflater.from(context()).inflate(
R.layout.view_toast, null);
((TextView) view.findViewById(R.id.title_tv)).setText(message);
if (icon != 0) {
((ImageView) view.findViewById(R.id.icon_iv))
.setImageResource(icon);
((ImageView) view.findViewById(R.id.icon_iv))
.setVisibility(View.VISIBLE);
}
Toast toast = new Toast(context());
toast.setView(view);
if (gravity == Gravity.CENTER) {
toast.setGravity(gravity, 0, 0);
} else {
toast.setGravity(gravity, 0, 60);
}
toast.setDuration(duration);
toast.show();
lastToast = message;
lastToastTime = System.currentTimeMillis();
}
}
}
}
package com.ifavine.pay.ui.base;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* Created by tree on 7/5/2016.
*/
public abstract class BaseFragment extends Fragment {
private boolean isVisibleToUser;
private boolean isViewInitialized;
private boolean isDataInitialized;
private boolean isLazyLoadEnabled;
public abstract void initView(View view);
public abstract void initData();
protected int getLayoutId() {
return 0;
}
public void enableLazyLoad() {
isLazyLoadEnabled = true;
}
protected LayoutInflater mInflater;
private Unbinder unbinder;
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
this.isVisibleToUser = isVisibleToUser;
checkIfLoadData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.mInflater = inflater;
View view = inflater.inflate(getLayoutId(), container, false);
if(view!=null){
unbinder= ButterKnife.bind(this,view);
}
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (!isLazyLoadEnabled) {
initView(view);
initData();
} else {
initView(view);
isViewInitialized = true;
if (savedInstanceState != null) {
onRestoreInstanceState(savedInstanceState);
}
if (isDataInitialized) {
initData();
} else {
checkIfLoadData();
}
}
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
isDataInitialized = true;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
@Override
public void onDestroyView() {
super.onDestroyView();
isViewInitialized = false;
}
private void checkIfLoadData() {
if (isVisibleToUser && isViewInitialized && !isDataInitialized) {
isDataInitialized = true;
initData();
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onInflate(Context context, AttributeSet attrs,
Bundle savedInstanceState) {
super.onInflate(context, attrs, savedInstanceState);
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
}
/**
* 打开一个Activity 默认 不关闭当前activity
*/
public void gotoActivity(Class<?> clz) {
gotoActivity(clz, false, null);
}
public void gotoActivity(Class<?> clz, boolean isCloseCurrentActivity) {
gotoActivity(clz, isCloseCurrentActivity, null);
}
public void gotoActivity(Class<?> clz, boolean isCloseCurrentActivity, Bundle ex) {
Intent intent = new Intent(getActivity(), clz);
if (ex != null) intent.putExtras(ex);
startActivity(intent);
if (isCloseCurrentActivity) {
getActivity().finish();
}
}
public void gotoActivity(Intent intent, boolean isCloseCurrentActivity) {
startActivity(intent);
if (isCloseCurrentActivity) {
getActivity().finish();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
}
package com.ifavine.pay.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.ifavine.pay.R;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
public class BaseTakePhotoActivity extends BaseActivity implements TakePhoto.TakeResultListener,InvokeListener {
private static final String TAG = BaseTakePhotoActivity.class.getName();
private TakePhoto takePhoto;
private InvokeParam invokeParam;
@Override
protected void onCreate(Bundle savedInstanceState) {
getTakePhoto().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
getTakePhoto().onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
getTakePhoto().onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionManager.TPermissionType type= PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
}
/**
* 获取TakePhoto实例
* @return
*/
public TakePhoto getTakePhoto(){
if (takePhoto==null){
takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
}
return takePhoto;
}
@Override
public void takeSuccess(TResult result) {
Log.i(TAG,"takeSuccess:" + result.getImage().getCompressPath());
}
@Override
public void takeFail(TResult result,String msg) {
Log.i(TAG, "takeFail:" + msg);
}
@Override
public void takeCancel() {
Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
}
@Override
public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
if(PermissionManager.TPermissionType.WAIT.equals(type)){
this.invokeParam=invokeParam;
}
return type;
}
}
\ No newline at end of file
package com.ifavine.pay.ui.base;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 封装adapter(注意:仅供参考,根据需要选择使用demo中提供的封装adapter)
*
* @param <T>
*/
public abstract class ListBaseAdapter<T> extends RecyclerView.Adapter<SuperViewHolder> {
protected Context mContext;
private LayoutInflater mInflater;
protected List<T> mDataList = new ArrayList<>();
public ListBaseAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public SuperViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(getLayoutId(), parent, false);
return new SuperViewHolder(itemView);
}
@Override
public void onBindViewHolder(SuperViewHolder holder, int position) {
onBindItemHolder(holder, position);
}
//局部刷新关键:带payload的这个onBindViewHolder方法必须实现
@Override
public void onBindViewHolder(SuperViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
onBindViewHolder(holder, position);
} else {
onBindItemHolder(holder, position, payloads);
}
}
public abstract int getLayoutId();
public abstract void onBindItemHolder(SuperViewHolder holder, int position);
public void onBindItemHolder(SuperViewHolder holder, int position, List<Object> payloads) {
}
@Override
public int getItemCount() {
return mDataList.size();
}
public List<T> getDataList() {
return mDataList;
}
public void setDataList(Collection<T> list) {
this.mDataList.clear();
this.mDataList.addAll(list);
notifyDataSetChanged();
}
public void addAll(Collection<T> list) {
int lastIndex = this.mDataList.size();
if (this.mDataList.addAll(list)) {
notifyItemRangeInserted(lastIndex, list.size());
}
}
public void remove(int position) {
this.mDataList.remove(position);
notifyItemRemoved(position);
if (position != (getDataList().size())) { // 如果移除的是最后一个,忽略
notifyItemRangeChanged(position, this.mDataList.size() - position);
}
}
public void clear() {
mDataList.clear();
notifyDataSetChanged();
}
}
package com.ifavine.pay.ui.base;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
/**
* ViewHolder基类
*/
public class SuperViewHolder extends RecyclerView.ViewHolder {
private SparseArray<View> views;
public SuperViewHolder(View itemView) {
super(itemView);
this.views = new SparseArray<>();
}
@SuppressWarnings("unchecked")
public <T extends View> T getView(int viewId) {
View view = views.get(viewId);
if (view == null) {
view = itemView.findViewById(viewId);
views.put(viewId, view);
}
return (T) view;
}
}
package com.ifavine.pay.utils;
/**
* Created by Administrator on 2017/7/5.
*/
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/***
* java抓取网络图片
* @author swinglife
*
*/
public class CatchImageUtils {
// 编码
private static final String ECODING = "UTF-8";
// 获取img标签正则
private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
// 获取src路径的正则
private static final String IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";
/***
* 获取HTML内容
*
* @param url
* @return
* @throws Exception
*/
private String getHTML(String url) throws Exception {
URL uri = new URL(url);
URLConnection connection = uri.openConnection();
InputStream in = connection.getInputStream();
byte[] buf = new byte[1024];
int length = 0;
StringBuffer sb = new StringBuffer();
while ((length = in.read(buf, 0, buf.length)) > 0) {
sb.append(new String(buf, ECODING));
}
in.close();
return sb.toString();
}
/***
* 获取ImageUrl标签
*
* @param HTML
* @return
*/
public static List<String> getImageTag(String HTML) {
Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);
List<String> listImgUrl = new ArrayList<String>();
while (matcher.find()) {
listImgUrl.add(matcher.group());
}
return listImgUrl;
}
/***
* 获取ImageSrc地址
*
* @return
*/
public static List<String> getImageSrc(String HTML) {
List<String> listImageUrl = getImageTag(HTML);
List<String> listImgSrc = new ArrayList<String>();
for (String image : listImageUrl) {
Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
while (matcher.find()) {
listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));
}
}
return listImgSrc;
}
}
package com.ifavine.pay.utils;
import com.ifavine.pay.vo.LocalContact;
import java.util.Comparator;
public class ContactSorting implements Comparator<LocalContact> {
@Override
public int compare(LocalContact l1, LocalContact l2) {
//给我两个对象,我只比较他的字母
if (l2.getIndex().equals("#")) {
return -1;
} else if (l1.getIndex().equals("#")) {
return 1;
} else {
return l1.getIndex().compareTo(l2.getIndex());
}
}
}
\ No newline at end of file
package com.ifavine.pay.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Telephony;
import android.widget.Toast;
/**
* Created by lin on 2017/5/19.
*/
public class ContactUtil {
public static final int FILE_SELECT_CODE = 0;
/**发送邮件*/
public static void sendEmail(Context context,String emailAddress) {
Intent email = new Intent(android.content.Intent.ACTION_SEND);
//邮件发送类型:无附件,纯文本
email.setType("plain/text");
//邮件接收者(数组,可以是多位接收者)
String[] emailReciver = new String[]{emailAddress};
// String emailTitle = "标题";
// String emailContent = "内容";
//设置邮件地址
email.putExtra(android.content.Intent.EXTRA_EMAIL, emailReciver);
////设置邮件标题
// email.putExtra(android.content.Intent.EXTRA_SUBJECT, emailTitle);
////设置发送的内容
// email.putExtra(android.content.Intent.EXTRA_TEXT, emailContent);
//调用系统的邮件系统
context.startActivity(Intent.createChooser(email, "请选择邮箱app发送邮件"));
// context.startActivity(email);
}
/**
* 发送短信
*/
@SuppressLint("NewApi")
public static void sendSMS(Context context,String phoneNum) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) //At least KitKat
{
String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context); //Need to change the build to API 19
// Intent sendIntent = new Intent(Intent.ACTION_SEND);
// sendIntent.setType("text/plain");
// sendIntent.putExtra(Intent.EXTRA_TEXT, shareContent);
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
sendIntent.putExtra("address", phoneNum);
// sendIntent.putExtra("sms_body", shareContent);
if (defaultSmsPackageName != null)//Can be null in case that there is no default, then the user would be able to choose any app that support this intent.
{
sendIntent.setPackage(defaultSmsPackageName);
}
context.startActivity(sendIntent);
}else{
Uri smsToUri = Uri.parse("smsto:");
Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
sendIntent.putExtra("address", phoneNum); // 电话号码,这行去掉的话,默认就没有电话
// sendIntent.putExtra("sms_body", shareContent);
sendIntent.setType("vnd.android-dir/mms-sms");
context.startActivity(sendIntent);
}
}
public static void telCall(Context context,String phoneNum){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phoneNum));
//开启系统拨号器
context.startActivity(intent);
}
/** 调用文件选择软件来选择文件 **/
public static void showFileChooser(Activity context) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
context.startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(context, "请安装文件管理器", Toast.LENGTH_SHORT)
.show();
}
}
}
package com.ifavine.pay.utils;
import android.net.Uri;
import android.os.Environment;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TakePhotoOptions;
import java.io.File;
public class CustomTakePhotoHelper {
public static CustomTakePhotoHelper of() {
return new CustomTakePhotoHelper();
}
private CustomTakePhotoHelper() {
}
private void init(TakePhoto takePhoto) {
configCompress(takePhoto);
configTakePhotoOption(takePhoto);
}
public void pickBySelect(TakePhoto takePhoto){
init(takePhoto);
takePhoto.onPickFromGallery();
// takePhoto.onPickMultiple(8);
}
public void pickByTake(TakePhoto takePhoto){
File file = new File(Environment.getExternalStorageDirectory(),
"/temp/" + System.currentTimeMillis() + ".jpg");
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
Uri imageUri = Uri.fromFile(file);
init(takePhoto);
takePhoto.onPickFromCapture(imageUri);
}
private void configTakePhotoOption(TakePhoto takePhoto) {
TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
if (true) {
builder.setWithOwnGallery(true);
}else{
builder.setCorrectImage(true);
}
takePhoto.setTakePhotoOptions(builder.create());
}
private void configCompress(TakePhoto takePhoto) {
//if (rgCompress.getCheckedRadioButtonId() != R.id.rbCompressYes) {
// takePhoto.onEnableCompress(null, false);
// return;
//}
int maxSize = Integer.parseInt("102400");
int width = Integer.parseInt("800");
int height = Integer.parseInt("800");
CompressConfig config;
if (true) {
config = new CompressConfig.Builder().setMaxSize(maxSize)
.setMaxPixel(width >= height ? width : height)
.enableReserveRaw(true)
.create();
} else {
LubanOptions option = new LubanOptions.Builder().setMaxHeight(height)
.setMaxWidth(width)
.setMaxSize(maxSize)
.create();
config = CompressConfig.ofLuban(option);
config.enableReserveRaw(true);
}
takePhoto.onEnableCompress(config, true);
}
private CropOptions getCropOptions() {
int height = Integer.parseInt("800");
int width = Integer.parseInt("800");
CropOptions.Builder builder = new CropOptions.Builder();
builder.setAspectX(width).setAspectY(height);
builder.setOutputX(width).setOutputY(height);
builder.setWithOwnCrop(true);
return builder.create();
}
}
package com.ifavine.pay.utils;
/**
* Created by Administrator on 2017/6/20.
*/
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by xyz on 2017/1/9.
*/
public class DateTimeUtils {
private int hour;
private int day;
private Date date;
private DateFormat df;
private String pointText;
private Long time;
private Long now;
public DateTimeUtils() {
hour = 60 * 60 * 1000;
day = (60 * 60 * 24) * 1000;
time = 28800L;
now = new Date().getTime();
pointText = "";
}
//获得当天0点时间
public static Long getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (Long) cal.getTimeInMillis();
}
//获取星期几
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
//获取时间点
public String getTimePoint(String timeStr) {
if (timeStr == null || "".equals(timeStr)) {
timeStr = String.valueOf(new Date().getTime());
}
long time = Long.parseLong(timeStr) * 1000;
//现在时间
now = new Date().getTime();
//时间点比当天零点早
if (time <= now) {
date = new Date(time);
if (time < getTimesmorning()) {
if (time >= getTimesmorning() - day) {//比昨天零点晚
pointText = "昨天";
return pointText;
} else {
//显示具体日期
return date.getMonth() + 1 + "月" + date.getDate() + "日";
}
} else {//无日期时间,当天内具体时间
Date d = new Date();
int h = d.getHours() - date.getHours();
int m = d.getMinutes() - date.getMinutes();
if (h >= 1) {
return h + "小时前";
} else {
if (m <= 5) {
return "刚刚";
}
return m + "分钟前";
}
}
} else {
pointText = "刚刚";
}
return pointText;
}
public static String getMeetingDate(String start, String end) {
long time = Long.parseLong(start) * 1000;
Calendar cal = Calendar.getInstance();//使用日历类
cal.setTimeInMillis(time);
int year = cal.get(Calendar.YEAR);//得到年
int month = cal.get(Calendar.MONTH) + 1;//得到月,因为从0开始的,所以要加1
int day = cal.get(Calendar.DAY_OF_MONTH);//得到天
int hour = cal.get(Calendar.HOUR);//得到小时
int minute = cal.get(Calendar.MINUTE);//得到分钟
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String sTime = df.format(cal.getTime());
String week = getWeekOfDate(cal.getTime());
time = Long.parseLong(end) * 1000;
cal.setTimeInMillis(time);
String eTime = df.format(cal.getTime());
return month + "月" + day + "日 " + week + " " + sTime + "~" + eTime;
}
public static String getMeetingDate(String start) {
long time = Long.parseLong(start) * 1000;
Calendar cal = Calendar.getInstance();//使用日历类
cal.setTimeInMillis(time);
int year = cal.get(Calendar.YEAR);//得到年
int month = cal.get(Calendar.MONTH) + 1;//得到月,因为从0开始的,所以要加1
int day = cal.get(Calendar.DAY_OF_MONTH);//得到天
int hour = cal.get(Calendar.HOUR);//得到小时
int minute = cal.get(Calendar.MINUTE);//得到分钟
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String sTime = df.format(cal.getTime());
String week = getWeekOfDate(cal.getTime());
return month + "月" + day + "日 " + week + " " + sTime;
}
}
\ No newline at end of file
package com.ifavine.pay.utils;
/**
* Created by Administrator on 2017/6/16.
*/
import android.os.Looper;
import com.bumptech.glide.Glide;
import com.ifavine.pay.common.AppContext;
import java.io.File;
import java.math.BigDecimal;
/**
* Created by YaphetZhao
* on 2016/12/19.
* <p>
* QQ:11613371
* GitHub:https://github.com/YaphetZhao
* Email:yaphetzhao@foxmail.com
* Email_EN:yaphetzhao@gmail.com
* <p>
* Glide缓存工具类
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class GlideCacheUtil {
private static GlideCacheUtil instance;
public static GlideCacheUtil getInstance() {
if (null == instance) {
instance = new GlideCacheUtil();
}
return instance;
}
// 获取Glide磁盘缓存大小
public String getCacheSize() {
try {
return getFormatSize(getFolderSize(Glide.getPhotoCacheDir(AppContext.getInstance())));
} catch (Exception e) {
e.printStackTrace();
return "获取失败";
}
}
// 清除Glide磁盘缓存,自己获取缓存文件夹并删除方法
public boolean cleanCatchDisk() {
return deleteFolderFile(Glide.getPhotoCacheDir(AppContext.getInstance()).getPath(), true);
}
// 清除图片磁盘缓存,调用Glide自带方法
public boolean clearCacheDiskSelf() {
try {
if (Looper.myLooper() == Looper.getMainLooper()) {
new Thread(new Runnable() {
@Override
public void run() {
Glide.get(AppContext.getInstance()).clearDiskCache();
}
}).start();
} else {
Glide.get(AppContext.getInstance()).clearDiskCache();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 清除Glide内存缓存
public boolean clearCacheMemory() {
try {
if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
Glide.get(AppContext.getInstance()).clearMemory();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// 获取指定文件夹内所有文件大小的和
private long getFolderSize(File file) throws Exception {
long size = 0;
try {
File[] fileList = file.listFiles();
for (File aFileList : fileList) {
if (aFileList.isDirectory()) {
size = size + getFolderSize(aFileList);
} else {
size = size + aFileList.length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
// 格式化单位
private static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}
// 按目录删除文件夹文件方法
private boolean deleteFolderFile(String filePath, boolean deleteThisPath) {
try {
File file = new File(filePath);
if (file.isDirectory()) {
File files[] = file.listFiles();
for (File file1 : files) {
deleteFolderFile(file1.getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {
file.delete();
} else {
if (file.listFiles().length == 0) {
file.delete();
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
package com.ifavine.pay.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
public class GlideCircleTransform extends BitmapTransformation {
public GlideCircleTransform(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(
new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override public String getId() {
return getClass().getName();
}
}
package com.ifavine.pay.utils;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by cundong on 2015/10/9.
* <p/>
* 网络使用工具类
*/
public class NetworkUtils {
/**
* 判断是不是wifi网络状态
*
* @param paramContext
* @return
*/
public static boolean isWifi(Context paramContext) {
return "2".equals(getNetType(paramContext)[0]);
}
/**
* 判断是不是2/3G网络状态
*
* @param paramContext
* @return
*/
public static boolean isMobile(Context paramContext) {
return "1".equals(getNetType(paramContext)[0]);
}
/**
* 网络是否可用
*
* @param paramContext
* @return
*/
public static boolean isNetAvailable(Context paramContext) {
if ("1".equals(getNetType(paramContext)[0]) || "2".equals(getNetType(paramContext)[0])) {
return true;
}
return false;
}
/**
* 获取当前网络状态 返回2代表wifi,1代表2G/3G
*
* @param paramContext
* @return
*/
public static String[] getNetType(Context paramContext) {
String[] arrayOfString = {"Unknown", "Unknown"};
PackageManager localPackageManager = paramContext.getPackageManager();
if (localPackageManager.checkPermission("android.permission.ACCESS_NETWORK_STATE", paramContext.getPackageName()) != 0) {
arrayOfString[0] = "Unknown";
return arrayOfString;
}
ConnectivityManager localConnectivityManager = (ConnectivityManager) paramContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (localConnectivityManager == null) {
arrayOfString[0] = "Unknown";
return arrayOfString;
}
NetworkInfo localNetworkInfo1 = localConnectivityManager.getNetworkInfo(1);
if (localNetworkInfo1 != null && localNetworkInfo1.getState() == NetworkInfo.State.CONNECTED) {
arrayOfString[0] = "2";
return arrayOfString;
}
NetworkInfo localNetworkInfo2 = localConnectivityManager.getNetworkInfo(0);
if (localNetworkInfo2 != null && localNetworkInfo2.getState() == NetworkInfo.State.CONNECTED) {
arrayOfString[0] = "1";
arrayOfString[1] = localNetworkInfo2.getSubtypeName();
return arrayOfString;
}
return arrayOfString;
}
}
package com.ifavine.pay.utils;
import android.content.Context;
import android.content.SharedPreferences;
import com.ifavine.pay.common.AppContext;
import com.ifavine.pay.common.Constants;
/**
* Created by tree on 11/28/2016.
*/
public class SPUtil {
private static SPUtil myPrefs;//私有化
private static SharedPreferences sp;
//提供私有的构造方法
private SPUtil() {
}
/**
* 对外提供的初始化方法
*
* @return
*/
public static SPUtil getInstance() {
//初始化自身对象
if (myPrefs == null) {
myPrefs = new SPUtil();
}
if (sp == null) {
sp = AppContext.getInstance().getSharedPreferences(Constants.PREF_NAME,
Context.MODE_PRIVATE);
}
return myPrefs;
}
/**
* 向SharedPreferences中写入String类型的数据
*/
public void writeString(String key, String value) {
//获取编辑器对象
SharedPreferences.Editor editor = sp.edit();
//写入数据
editor.putString(key, value);
editor.commit();//提交写入的数据
}
/**
* 根据key读取SharedPreferences中的String类型的数据
*
* @param key
* @return
*/
public String readString(String key) {
return sp.getString(key, "");
}
/**
* 向SharedPreferences中写入Boolean类型的数据
*
* @param key
*/
public void writeBoolean(String key, boolean value) {
//获取编辑器对象
SharedPreferences.Editor editor = sp.edit();
//写入数据
editor.putBoolean(key, value);
editor.commit();//提交写入的数据
}
/**
* 根据key读取SharedPreferences中的Boolean类型的数据
*
* @param key
* @return
*/
public Boolean readBoolean(String key) {
return sp.getBoolean(key, false);
}
/**
* 向SharedPreferences中写入long类型的数据
*/
public void writeLong(String key, long value) {
//获取编辑器对象
SharedPreferences.Editor editor = sp.edit();
//写入数据
editor.putLong(key, value);
editor.commit();//提交写入的数据
}
/**
* 根据key读取SharedPreferences中的long类型的数据
*
* @param key
* @return
*/
public Long readLong(String key) {
return sp.getLong(key, 0);
}
/**
* 根据key读取
*
* @param key
* @return
*/
public Integer readInt(String key, int mDefault) {
return sp.getInt(key, mDefault);
}
/**
* @param key
* @param value
*/
public void writeInt(String key, int value) {
//获取编辑器对象
SharedPreferences.Editor editor = sp.edit();
//写入数据
editor.putInt(key, value);
editor.commit();//提交写入的数据
}
}
package com.ifavine.pay.utils;
/**
* Created by tree on 7/4/2016.
*/
import android.util.Log;
import com.ifavine.pay.common.AppContext;
public class TLog {
public static boolean DEBUG = AppContext.DebugModel;
public static final String LOG_TAG = "iKettle_App";
public static final void analytics(String paramString) {
if (DEBUG) Log.d(LOG_TAG, paramString);
}
public static final void error(String paramString) {
if (DEBUG) {
Log.e(LOG_TAG, "" + paramString);
}
}
public static final void log(String paramString) {
if (DEBUG) Log.i(LOG_TAG, "" + paramString);
}
public static final void log(String paramString1, String paramString2) {
if (DEBUG) Log.i(paramString1, "" + paramString2);
}
public static final void logv(String paramString) {
if (DEBUG) Log.v(LOG_TAG, paramString);
}
public static final void warn(String paramString) {
if (DEBUG) Log.w(LOG_TAG, paramString);
}
}
package com.ifavine.pay.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.ifavine.pay.R;
/**
* 自定义组件:购买数量,带减少增加按钮
* Created by hiwhitley on 2016/7/4.
*/
public class AmountView extends LinearLayout implements View.OnClickListener, TextWatcher {
private static final String TAG = "AmountView";
private double amount = 1; //购买数量
private int goods_storage = 100; //商品库存
private OnAmountChangeListener mListener;
private EditText etAmount;
private Button btnDecrease;
private Button btnIncrease;
public AmountView(Context context) {
this(context, null);
}
public AmountView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.view_amount, this);
etAmount = (EditText) findViewById(R.id.etAmount);
btnDecrease = (Button) findViewById(R.id.btnDecrease);
btnIncrease = (Button) findViewById(R.id.btnIncrease);
btnDecrease.setOnClickListener(this);
btnIncrease.setOnClickListener(this);
etAmount.addTextChangedListener(this);
TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attrs, R.styleable.AmountView);
int btnWidth = obtainStyledAttributes.getDimensionPixelSize(R.styleable.AmountView_btnWidth, LayoutParams.WRAP_CONTENT);
int tvWidth = obtainStyledAttributes.getDimensionPixelSize(R.styleable.AmountView_tvWidth, 80);
int tvTextSize = obtainStyledAttributes.getDimensionPixelSize(R.styleable.AmountView_tvTextSize, 0);
int btnTextSize = obtainStyledAttributes.getDimensionPixelSize(R.styleable.AmountView_btnTextSize, 0);
obtainStyledAttributes.recycle();
LayoutParams btnParams = new LayoutParams(btnWidth, LayoutParams.MATCH_PARENT);
btnDecrease.setLayoutParams(btnParams);
btnIncrease.setLayoutParams(btnParams);
if (btnTextSize != 0) {
btnDecrease.setTextSize(TypedValue.COMPLEX_UNIT_PX, btnTextSize);
btnIncrease.setTextSize(TypedValue.COMPLEX_UNIT_PX, btnTextSize);
}
LayoutParams textParams = new LayoutParams(tvWidth, LayoutParams.MATCH_PARENT);
etAmount.setLayoutParams(textParams);
if (tvTextSize != 0) {
etAmount.setTextSize(tvTextSize);
}
}
public void setOnAmountChangeListener(OnAmountChangeListener onAmountChangeListener) {
this.mListener = onAmountChangeListener;
}
public void setGoods_storage(int goods_storage) {
this.goods_storage = goods_storage;
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btnDecrease) {
if (amount > 0) {
amount--;
etAmount.setText(amount + "");
}
} else if (i == R.id.btnIncrease) {
if (amount < goods_storage) {
amount++;
etAmount.setText(amount + "");
}
}
etAmount.clearFocus();
if (mListener != null) {
mListener.onAmountChange(this, amount);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().isEmpty())
return;
try {
amount = Double.valueOf(s.toString());
} catch (Exception e) {
return;
}
if (amount > goods_storage) {
etAmount.setText(goods_storage + "");
return;
}
if (mListener != null) {
mListener.onAmountChange(this, amount);
}
}
public interface OnAmountChangeListener {
void onAmountChange(View view, double amount);
}
}
package com.ifavine.pay.view;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
public class AsteriskPasswordTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return new PasswordCharSequence(source);
}
private class PasswordCharSequence implements CharSequence {
private CharSequence mSource;
public PasswordCharSequence(CharSequence source) {
mSource = source; // Store char sequence
}
public char charAt(int index) {
return '*'; // This is the important part
}
public int length() {
return mSource.length(); // Return default
}
public CharSequence subSequence(int start, int end) {
return mSource.subSequence(start, end); // Return default
}
}
}
\ No newline at end of file
package com.ifavine.pay.view;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.ifavine.pay.R;
public class BConfirmDialog extends android.app.Dialog implements View.OnClickListener {
private Context mContext;
private View view;
private BConfirmDialog(Context context, int defStyle) {
super(context, defStyle);
view = getLayoutInflater().inflate(R.layout.dialog_logout, null);
super.setContentView(view);
}
public BConfirmDialog(Context context, String title, View.OnClickListener okListener, String okName, View.OnClickListener cancelListener, String cancelName) {
this(context, R.style.logout_dialog_bottom);
this.mContext = context;
TextView tv_ok = (TextView) view.findViewById(R.id.tv_confirm);
TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
TextView tv_title = (TextView) view.findViewById(R.id.tv_take_photo);
tv_title.setText(title);
tv_cancel.setText(cancelName);
tv_ok.setText(okName);
if (okListener != null) {
tv_ok.setOnClickListener(okListener);
} else {
tv_ok.setOnClickListener(this);
}
if (cancelListener != null) {
tv_cancel.setOnClickListener(cancelListener);
} else {
tv_cancel.setOnClickListener(this);
}
}
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
getWindow().setGravity(Gravity.BOTTOM);
WindowManager m = getWindow().getWindowManager();
Display d = m.getDefaultDisplay();
WindowManager.LayoutParams p = getWindow().getAttributes();
p.width = (int) (d.getWidth() * 0.95);
getWindow().setAttributes(p);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_cancel:
dismiss();
break;
case R.id.tv_confirm:
dismiss();
break;
}
}
}
\ No newline at end of file
package com.ifavine.pay.view;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.ifavine.pay.R;
import java.util.ArrayList;
import java.util.List;
public class BMutilDialog extends android.app.Dialog implements View.OnClickListener {
private Context mContext;
private View view;
private OnClickCallBack callBack;
private List<TextView> textViews;
private BMutilDialog(Context context, int defStyle) {
super(context, defStyle);
view = getLayoutInflater().inflate(R.layout.dialog_mutil, null);
super.setContentView(view);
}
public BMutilDialog(Context context, OnClickCallBack callBack, int[] images, String[] name) {
this(context, R.style.logout_dialog_bottom);
this.mContext = context;
View v1 = (View) view.findViewById(R.id.v1);
View v2 = (View) view.findViewById(R.id.v2);
View v3 = (View) view.findViewById(R.id.v3);
TextView tv1 = (TextView) view.findViewById(R.id.tv1);
TextView tv2 = (TextView) view.findViewById(R.id.tv2);
TextView tv3 = (TextView) view.findViewById(R.id.tv3);
TextView tv4 = (TextView) view.findViewById(R.id.tv4);
TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
tv_cancel.setOnClickListener(this);
tv1.setOnClickListener(this);
tv2.setOnClickListener(this);
tv3.setOnClickListener(this);
tv4.setOnClickListener(this);
tv2.setVisibility(View.GONE);
tv3.setVisibility(View.GONE);
tv4.setVisibility(View.GONE);
textViews = new ArrayList<>();
textViews.add(tv1);
textViews.add(tv2);
textViews.add(tv3);
textViews.add(tv4);
for (int i = 0; i < name.length; i++) {
textViews.get(i).setText(name[i]);
textViews.get(i).setVisibility(View.VISIBLE);
Drawable dra = context.getResources().getDrawable(images[i]);
dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
textViews.get(i).setCompoundDrawables(dra, null, null, null);
if (i == 1) {
v1.setVisibility(View.VISIBLE);
}
if (i == 2) {
v2.setVisibility(View.VISIBLE);
}
if (i == 3) {
v3.setVisibility(View.VISIBLE);
}
}
this.callBack = callBack;
}
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
getWindow().setGravity(Gravity.BOTTOM);
WindowManager m = getWindow().getWindowManager();
Display d = m.getDefaultDisplay();
WindowManager.LayoutParams p = getWindow().getAttributes();
p.width = (int) (d.getWidth() * 0.95);
getWindow().setAttributes(p);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv1:
dismiss();
callBack.call(0);
break;
case R.id.tv2:
dismiss();
callBack.call(1);
break;
case R.id.tv3:
dismiss();
callBack.call(2);
break;
case R.id.tv4:
dismiss();
callBack.call(3);
break;
case R.id.tv_cancel:
dismiss();
break;
}
}
public interface OnClickCallBack {
void call(int index);
}
}
\ No newline at end of file
package com.ifavine.pay.view;
import android.content.Context;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ifavine.pay.R;
import com.ifavine.pay.utils.NetworkUtils;
/**
* Created by tree on 7/5/2016.
*/
public class ErrorLayout extends LinearLayoutCompat
implements View.OnClickListener {// , ISkinUIObserver {
public static final int HIDE_LAYOUT = 4;
public static final int NETWORK_ERROR = 1;
public static final int NETWORK_LOADING = 2;
public static final int NODATA_ENABLE_CLICK = 5;
public static final int NO_LOGIN = 6;
public static final int NODATA_CLOUD = 7;
public static final int NODATA_FAVOURITE = 8;
public static final int NODATA_HISTORY = 9;
public static final int NO_PERMISSION = 10;
public static final int NO_MSG = 11;
private ProgressBar animProgress;
private boolean clickEnable = true;
private final Context context;
public ImageView img;
private OnClickListener listener;
private int mErrorState;
private RelativeLayout mLayout;
private String strNoDataContent = "";
private TextView tv;
private Button btn;
public ErrorLayout(Context context) {
super(context);
this.context = context;
init();
}
public ErrorLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
private void init() {
View view = View.inflate(context, R.layout.view_error_layout, null);
img = (ImageView) view.findViewById(R.id.img_error_layout);
tv = (TextView) view.findViewById(R.id.tv_error_layout);
btn = (Button) view.findViewById(R.id.btn_error_layout);
mLayout = (RelativeLayout) view.findViewById(R.id.pageerrLayout);
animProgress = (ProgressBar) view.findViewById(R.id.animProgress);
setBackgroundColor(-1);
setOnClickListener(this);
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (clickEnable) {
// setErrorType(NETWORK_LOADING);
if (listener != null) listener.onClick(v);
}
}
});
addView(view);
changeErrorLayoutBgMode(context);
}
public void changeErrorLayoutBgMode(Context context1) {
// mLayout.setBackgroundColor(SkinsUtil.getColor(context1,
// "bgcolor01"));
// tv.setTextColor(SkinsUtil.getColor(context1, "textcolor05"));
}
public void dismiss() {
mErrorState = HIDE_LAYOUT;
setVisibility(View.GONE);
}
public int getErrorState() {
return mErrorState;
}
public boolean isLoadError() {
return mErrorState == NETWORK_ERROR;
}
public boolean isLoading() {
return mErrorState == NETWORK_LOADING;
}
@Override
public void onClick(View v) {
if (clickEnable) {
// setErrorType(NETWORK_LOADING);
if (listener != null) listener.onClick(v);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// MyApplication.getInstance().getAtSkinObserable().registered(this);
onSkinChanged();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// MyApplication.getInstance().getAtSkinObserable().unregistered(this);
}
public void onSkinChanged() {
// mLayout.setBackgroundColor(SkinsUtil
// .getColor(getContext(), "bgcolor01"));
// tv.setTextColor(SkinsUtil.getColor(getContext(), "textcolor05"));
}
public void setDayNight(boolean flag) {
}
public void setErrorMessage(String msg) {
tv.setText(msg);
}
/**
* 新添设置背景
*
* @author 火蚁 2015-1-27 下午2:14:00
*/
public void setErrorImag(int imgResource) {
try {
img.setImageResource(imgResource);
} catch (Exception e) {
}
}
public void setErrorType(int state) {
setVisibility(View.VISIBLE);
switch (state) {
case NETWORK_ERROR:
mErrorState = NETWORK_ERROR;
// img.setBackgroundDrawable(SkinsUtil.getDrawable(context,"ic_page_failed"));
if (NetworkUtils.isNetAvailable(getContext())) {
tv.setText(R.string.error_view_load_error_click_to_refresh);
img.setBackgroundResource(R.mipmap.icon_data_error);
} else {
tv.setText(R.string.error_view_network_error_click_to_refresh);
img.setBackgroundResource(R.mipmap.icon_network_error);
btn.setText(R.string.error_view_start);
btn.setVisibility(VISIBLE);
btn.setOnClickListener(listener);
}
img.setVisibility(View.VISIBLE);
animProgress.setVisibility(View.GONE);
clickEnable = true;
break;
case NETWORK_LOADING:
mErrorState = NETWORK_LOADING;
// animProgress.setBackgroundDrawable(SkinsUtil.getDrawable(context,"loadingpage_bg"));
animProgress.setVisibility(View.VISIBLE);
img.setVisibility(View.GONE);
tv.setText(R.string.error_view_loading);
clickEnable = false;
break;
case NODATA_ENABLE_CLICK:
mErrorState = NODATA_ENABLE_CLICK;
// animProgress.setBackgroundDrawable(SkinsUtil.getDrawable(context,"loadingpage_bg"));
animProgress.setVisibility(View.GONE);
img.setVisibility(View.VISIBLE);
img.setBackgroundResource(R.mipmap.icon_data_error);
tv.setText(R.string.error_view_empty_layout_label);
break;
case NO_PERMISSION:
mErrorState = NODATA_ENABLE_CLICK;
animProgress.setVisibility(View.GONE);
img.setVisibility(View.VISIBLE);
img.setBackgroundResource(R.mipmap.icon_data_error);
tv.setText(R.string.error_view_no_permission);
break;
case HIDE_LAYOUT:
setVisibility(View.GONE);
break;
case NODATA_CLOUD:
animProgress.setVisibility(View.GONE);
img.setBackgroundResource(R.mipmap.icon_data_error);
img.setVisibility(View.VISIBLE);
tv.setText(R.string.error_view_empty_layout_label);
tv.setVisibility(View.VISIBLE);
clickEnable = true;
break;
case NO_MSG:
animProgress.setVisibility(View.GONE);
img.setBackgroundResource(R.mipmap.icon_data_error);
img.setVisibility(View.VISIBLE);
tv.setText(R.string.error_view_empty_msg);
tv.setVisibility(View.VISIBLE);
clickEnable = true;
break;
default:
break;
}
}
public void setNoDataContent(String noDataContent) {
strNoDataContent = noDataContent;
}
public void setOnLayoutClickListener(OnClickListener listener) {
this.listener = listener;
}
@Override
public void setVisibility(int visibility) {
if (visibility == View.GONE) mErrorState = HIDE_LAYOUT;
super.setVisibility(visibility);
}
}
package com.ifavine.pay.view;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.ifavine.pay.R;
import com.ifavine.pay.listener.OnMenuClickListener;
import java.io.File;
public class PickPhotoMenuDialog extends Dialog implements View.OnClickListener {
public final static int CAMERA = 1;
public final static int ALBUMS = 2;
private Context mContext;
private OnMenuClickListener mListener;
private PickPhotoMenuDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
}
private PickPhotoMenuDialog(Context context, int defStyle) {
super(context, defStyle);
View view = getLayoutInflater().inflate(R.layout.dialog_photo_picker, null);
view.findViewById(R.id.tv_take_photo).setOnClickListener(this);
view.findViewById(R.id.tv_take_album).setOnClickListener(this);
view.findViewById(R.id.tv_cancel).setOnClickListener(this);
super.setContentView(view);
}
public PickPhotoMenuDialog(Context context) {
this(context, R.style.dialog_bottom);
this.mContext = context;
}
@Override protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
getWindow().setGravity(Gravity.BOTTOM);
WindowManager m = getWindow().getWindowManager();
Display d = m.getDefaultDisplay();
WindowManager.LayoutParams p = getWindow().getAttributes();
p.width = d.getWidth();
getWindow().setAttributes(p);
}
public void setOnMenuClickListener(OnMenuClickListener listener) {
mListener = listener;
}
@Override public void onClick(View v) {
if (mListener != null) {
mListener.onClick((TextView) v);
}
}
// 照像添加图片
public void getImageFromCamera(Activity activity, String filePath) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath)));
activity.startActivityForResult(intent, CAMERA);
}
// 从相册添加图片
public void getImageFormAlbum(Activity activity) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
activity.startActivityForResult(intent, ALBUMS);
}
}
\ No newline at end of file
package com.ifavine.pay.view;
/**
* Created by Administrator on 2018/10/18.
*/
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.ifavine.pay.R;
/**
* 弹窗视图
*/
public class PopWindowMainReport extends PopupWindow implements View.OnClickListener {
private Context context;
private View ll_1, ll_2, ll_3;
private CallBackPosition call;
public PopWindowMainReport(Context context, CallBackPosition call) {
super(context);
this.context = context;
this.call = call;
initalize();
}
private void initalize() {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.pop_main_report, null);
ll_1 = view.findViewById(R.id.ll_1);//发起群聊
ll_2 = view.findViewById(R.id.ll_2);//添加好友
ll_3 = view.findViewById(R.id.ll_3);//添加好友
ll_1.setOnClickListener(this);
ll_2.setOnClickListener(this);
ll_3.setOnClickListener(this);
setContentView(view);
initWindow();
}
private void initWindow() {
DisplayMetrics d = context.getResources().getDisplayMetrics();
this.setWidth((int) (d.widthPixels * 0.2));
this.setHeight(LayoutParams.WRAP_CONTENT);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.update();
//实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0x00000000);
//设置SelectPicPopupWindow弹出窗体的背景
this.setBackgroundDrawable(dw);
backgroundAlpha((Activity) context, 0.6f);//0.0-1.0
this.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
backgroundAlpha((Activity) context, 1f);
}
});
}
//设置添加屏幕的背景透明度
public void backgroundAlpha(Activity context, float bgAlpha) {
WindowManager.LayoutParams lp = context.getWindow().getAttributes();
lp.alpha = bgAlpha;
context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
context.getWindow().setAttributes(lp);
}
public void showAtBottom(View view) {
//弹窗位置设置
// showAsDropDown(view, Math.abs((view.getWidth() - getWidth()) / 2), 10);
showAsDropDown(view);
//showAtLocation(view, Gravity.TOP | Gravity.RIGHT, 10, 110);//有偏差
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.ll_1:
dismiss();
if (call != null) {
call.selectIndex(0);
}
break;
case R.id.ll_2:
dismiss();
if (call != null) {
call.selectIndex(1);
}
break;
case R.id.ll_3:
dismiss();
if (call != null) {
call.selectIndex(2);
}
break;
default:
break;
}
}
public interface CallBackPosition {
void selectIndex(int index);
}
}
package com.ifavine.pay.view;
/**
* Created by Administrator on 2018/10/18.
*/
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.PopupWindow;
import com.ifavine.pay.R;
/**
* 弹窗视图
*/
public class PopWindowMainSet extends PopupWindow implements View.OnClickListener {
private Context context;
private View ll_1, ll_2, ll_3;
private CallBackPosition call;
public PopWindowMainSet(Context context, CallBackPosition call) {
super(context);
this.context = context;
this.call = call;
initalize();
}
private void initalize() {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.pop_main_set, null);
ll_1 = view.findViewById(R.id.ll_1);//发起群聊
ll_2 = view.findViewById(R.id.ll_2);//添加好友
ll_3 = view.findViewById(R.id.ll_3);//添加好友
ll_1.setOnClickListener(this);
ll_2.setOnClickListener(this);
ll_3.setOnClickListener(this);
setContentView(view);
initWindow();
}
private void initWindow() {
DisplayMetrics d = context.getResources().getDisplayMetrics();
this.setWidth((int) (d.widthPixels * 0.2));
this.setHeight(LayoutParams.WRAP_CONTENT);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.update();
//实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0x00000000);
//设置SelectPicPopupWindow弹出窗体的背景
this.setBackgroundDrawable(dw);
backgroundAlpha((Activity) context, 0.6f);//0.0-1.0
this.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
backgroundAlpha((Activity) context, 1f);
}
});
}
//设置添加屏幕的背景透明度
public void backgroundAlpha(Activity context, float bgAlpha) {
WindowManager.LayoutParams lp = context.getWindow().getAttributes();
lp.alpha = bgAlpha;
context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
context.getWindow().setAttributes(lp);
}
public void showAtBottom(View view) {
//弹窗位置设置
// showAsDropDown(view, Math.abs((view.getWidth() - getWidth()) / 2), 10);
showAsDropDown(view);
//showAtLocation(view, Gravity.TOP | Gravity.RIGHT, 10, 110);//有偏差
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.ll_1:
dismiss();
if (call != null) {
call.selectIndex(0);
}
break;
case R.id.ll_2:
dismiss();
if (call != null) {
call.selectIndex(1);
}
break;
case R.id.ll_3:
dismiss();
if (call != null) {
call.selectIndex(2);
}
break;
default:
break;
}
}
public interface CallBackPosition {
void selectIndex(int index);
}
}
package com.ifavine.pay.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
/**
* Copyright (C) 2017 Wasabeef
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public final class Utils {
private Utils() throws InstantiationException {
throw new InstantiationException("This class is not for instantiation");
}
public static String toBase64(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
public static Bitmap toBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public static Bitmap decodeResource(Context context, int resId) {
return BitmapFactory.decodeResource(context.getResources(), resId);
}
public static long getCurrentTime() {
return System.currentTimeMillis();
}
}
package com.ifavine.pay.view.datepicker;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Created by lmt on 16/7/6.
*/
public class DateUtil {
public static final String ymdhms = "yyyy-MM-dd HH:mm:ss";
public static final String ymd = "yyyy-MM-dd";
public static String monthNumToMonthName(String month) {
String m = month;
if ("1".equals(month)) {
m = "一月份";
} else if ("2".equals(month)) {
m = "二月份";
} else if ("3".equals(month)) {
m = "三月份";
} else if ("4".equals(month)) {
m = "四月份";
} else if ("5".equals(month)) {
m = "五月份";
} else if ("6".equals(month)) {
m = "六月份";
} else if ("7".equals(month)) {
m = "七月份";
} else if ("8".equals(month)) {
m = "八月份";
} else if ("9".equals(month)) {
m = "九月份";
} else if ("10".equals(month)) {
m = "十月份";
} else if ("11".equals(month)) {
m = "十一月份";
} else if ("12".equals(month)) {
m = "十二月份";
}
return m;
}
public static String getTomorrow() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 1);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
return year + "-" + (month > 9 ? month : ("0" + month)) + "-" + day;
}
public static int getYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
public static String getToday() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
return year + "-" + (month > 9 ? month : ("0" + month)) + "-" + day;
}
public static List<Integer> getDateForString(String date) {
String[] dates = date.split("-");
List<Integer> list = new ArrayList<>();
list.add(Integer.parseInt(dates[0]));
list.add(Integer.parseInt(dates[1]));
list.add(Integer.parseInt(dates[2]));
return list;
}
public static Calendar getCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static String formatDate(String date, String format) {
String resultD = date;
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date d = sdf.parse(date);
resultD = sdf.format(d);
} catch (Exception e) {
e.printStackTrace();
}
return resultD;
}
public static String formatDate(long milliseconds, String format) {
String resultD = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date d = new Date(milliseconds);
resultD = sdf.format(d);
} catch (Exception e) {
e.printStackTrace();
}
return resultD;
}
public static Date formatDateStr(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date1 = null;
try {
date1 = sdf.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
return date1;
}
/**
* 通过年份和月份 得到当月的日子
*
* @param year
* @param month
* @return
*/
public static int getMonthDays(int year, int month) {
month++;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return 29;
} else {
return 28;
}
default:
return -1;
}
}
/**
* 返回当前月份1号位于周几
*
* @param year 年份
* @param month 月份,传入系统获取的,不需要正常的
* @return 日:1 一:2 二:3 三:4 四:5 五:6 六:7
*/
public static int getFirstDayWeek(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 1);
Log.d("DateView", "DateView:First:" + calendar.getFirstDayOfWeek());
return calendar.get(Calendar.DAY_OF_WEEK);
}
public static String getDayWeek(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
Log.d("DateView", "DateView:First:" + calendar.getFirstDayOfWeek());
switch (calendar.get(Calendar.DAY_OF_WEEK)) {
case 1:
return "周日";
case 2:
return "周一";
case 3:
return "周二";
case 4:
return "周三";
case 5:
return "周四";
case 6:
return "周五";
case 7:
return "周六";
default:
return "";
}
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
public interface LoopListener
{
void onItemSelect(int item);
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
// Referenced classes of package com.qingchifan.view:
// LoopView, LoopListener
final class LoopRunnable implements Runnable {
final LoopView loopView;
LoopRunnable(LoopView loopview) {
super();
loopView = loopview;
}
public final void run() {
LoopListener listener = loopView.loopListener;
int i = LoopView.getSelectItem(loopView);
listener.onItemSelect(i);
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
import java.util.Timer;
import java.util.TimerTask;
// Referenced classes of package com.qingchifan.view:
// LoopView
final class LoopTimerTask extends TimerTask {
float a;
final float b;
final Timer timer;
final LoopView loopView;
LoopTimerTask(LoopView loopview, float f, Timer timer) {
super();
loopView = loopview;
b = f;
this.timer = timer;
a = 2.147484E+09F;
}
public final void run() {
if (a == 2.147484E+09F) {
if (Math.abs(b) > 2000F) {
if (b > 0.0F) {
a = 2000F;
} else {
a = -2000F;
}
} else {
a = b;
}
}
if (Math.abs(a) >= 0.0F && Math.abs(a) <= 20F) {
timer.cancel();
loopView.handler.sendEmptyMessage(2000);
return;
}
int i = (int) ((a * 10F) / 1000F);
LoopView loopview = loopView;
loopview.totalScrollY = loopview.totalScrollY - i;
if (!loopView.isLoop) {
if (loopView.totalScrollY <= (int) ((float) (-loopView.positon) * (loopView.l * (float) loopView.h))) {
a = 40F;
loopView.totalScrollY = (int) ((float) (-loopView.positon) * (loopView.l * (float) loopView.h));
} else if (loopView.totalScrollY >= (int) ((float) (loopView.arrayList.size() - 1 - loopView.positon) * (loopView.l * (float) loopView.h))) {
loopView.totalScrollY = (int) ((float) (loopView.arrayList.size() - 1 - loopView.positon) * (loopView.l * (float) loopView.h));
a = -40F;
}
}
if (a < 0.0F) {
a = a + 20F;
} else {
a = a - 20F;
}
loopView.handler.sendEmptyMessage(1000);
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
import android.view.MotionEvent;
// Referenced classes of package com.qingchifan.view:
// LoopView
final class LoopViewGestureListener extends android.view.GestureDetector.SimpleOnGestureListener {
final LoopView loopView;
LoopViewGestureListener(LoopView loopview) {
super();
loopView = loopview;
}
public final boolean onDown(MotionEvent motionevent) {
if (loopView.mTimer != null) {
loopView.mTimer.cancel();
}
return true;
}
public final boolean onFling(MotionEvent motionevent, MotionEvent motionevent1, float f, float f1) {
loopView.b(f1);
return true;
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
import java.util.Timer;
import java.util.TimerTask;
final class MTimer extends TimerTask {
int a;
int b;
final int c;
final Timer timer;
final LoopView loopView;
MTimer(LoopView loopview, int i, Timer timer) {
super();
loopView = loopview;
c = i;
this.timer = timer;
a = 0x7fffffff;
b = 0;
}
public final void run() {
if (a == 0x7fffffff) {
if (c < 0) {
if ((float) (-c) > (loopView.l * (float) loopView.h) / 2.0F) {
a = (int) (-loopView.l * (float) loopView.h - (float) c);
} else {
a = -c;
}
} else if ((float) c > (loopView.l * (float) loopView.h) / 2.0F) {
a = (int) (loopView.l * (float) loopView.h - (float) c);
} else {
a = -c;
}
}
b = (int) ((float) a * 0.1F);
if (b == 0) {
if (a < 0) {
b = -1;
} else {
b = 1;
}
}
if (Math.abs(a) <= 0) {
timer.cancel();
loopView.handler.sendEmptyMessage(3000);
return;
} else {
LoopView loopview = loopView;
loopview.totalScrollY = loopview.totalScrollY + b;
loopView.handler.sendEmptyMessage(1000);
a = a - b;
return;
}
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
import android.os.Handler;
import android.os.Message;
// Referenced classes of package com.qingchifan.view:
// LoopView
final class MessageHandler extends Handler {
final LoopView a;
MessageHandler(LoopView loopview) {
super();
a = loopview;
}
public final void handleMessage(Message paramMessage) {
if (paramMessage.what == 1000)
this.a.invalidate();
while (true) {
if (paramMessage.what == 2000)
LoopView.b(a);
else if (paramMessage.what == 3000)
this.a.c();
super.handleMessage(paramMessage);
return;
}
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.ifavine.pay.view.datepicker;
import java.util.Timer;
import java.util.TimerTask;
// Referenced classes of package com.qingchifan.view:
// LoopView
final class MyTimerTask extends TimerTask {
float a;
float b;
final int c;
final Timer timer;
final LoopView loopView;
MyTimerTask(LoopView loopview, int i, Timer timer) {
super();
this.loopView = loopview;
c = i;
this.timer = timer;
a = 2.147484E+09F;
b = 0.0F;
}
public final void run() {
if (a == 2.147484E+09F) {
a = (float) (c - LoopView.getSelectItem(loopView)) * loopView.l * (float) loopView.h;
if (c > LoopView.getSelectItem(loopView)) {
b = -1000F;
} else {
b = 1000F;
}
}
if (Math.abs(a) < 1.0F) {
timer.cancel();
loopView.handler.sendEmptyMessage(2000);
return;
}
int j = (int) ((b * 10F) / 1000F);
int i = j;
if (Math.abs(a) < (float) Math.abs(j)) {
i = (int) (-a);
}
LoopView loopview = loopView;
loopview.totalScrollY = loopview.totalScrollY - i;
float f = a;
a = (float) i + f;
loopView.handler.sendEmptyMessage(1000);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment