Commit 333f1a69 by chengfengpiaopiao

微信登录

parents
Showing with 5368 additions and 0 deletions
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
<component name="CopyrightManager">
<settings default="" />
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AndroidLintStringFormatMatches" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="LoggerInitializedWithForeignClass" enabled="false" level="WARNING" enabled_by_default="false">
<option name="loggerClassName" value="org.apache.log4j.Logger,org.slf4j.LoggerFactory,org.apache.commons.logging.LogFactory,java.util.logging.Logger" />
<option name="loggerFactoryMethodName" value="getLogger,getLogger,getLog,getLogger" />
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="Project Default" />
<option name="USE_PROJECT_PROFILE" value="true" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="4">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
</list>
</value>
</option>
</component>
<component name="ProjectInspectionProfilesVisibleTreeState">
<entry key="Project Default">
<profile-state>
<expanded-state>
<State>
<id />
</State>
<State>
<id>Android</id>
</State>
<State>
<id>Android &gt; Lint &gt; Correctness</id>
</State>
<State>
<id>Java</id>
</State>
<State>
<id>Java language level migration aidsJava</id>
</State>
</expanded-state>
<selected-state>
<State>
<id>Android</id>
</State>
</selected-state>
</profile-state>
</entry>
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/DuoBaoJingCai2.iml" filepath="$PROJECT_DIR$/DuoBaoJingCai2.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.maile.jingcai"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
//配置keystore签名
signingConfigs {
release {
storeFile file("duobaojingcai.jks")
storePassword "yy10241905"
keyAlias "duobaojingcai"
keyPassword "yy10241905"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
signingConfig signingConfigs.release
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.0'
testCompile 'junit:junit:4.12'
compile "com.jakewharton:butterknife:$rootProject.ButterKnife"
compile "com.squareup.retrofit2:retrofit:$Retrofit"
compile "com.squareup.retrofit2:converter-gson:$Retrofit"
compile "com.squareup.retrofit2:adapter-rxjava:$Retrofit"
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.9'
compile 'com.google.code.gson:gson:2.6.2'
compile "com.squareup.okhttp3:logging-interceptor:$loggingInterceptor"
compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.0.2'
compile 'cz.msebera.android:httpclient:4.4.1.1'
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\2_android\as_client\sdk/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 *;
#}
package com.maile.jingcai;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.maile.jingcai", appContext.getPackageName());
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.maile.jingcai">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<!-- 访问网络权限,用于与服务器交互数据 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:name=".DuoBaoApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:name=".view.activity.LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".view.activity.MainActivity"
android:exported="true"
android:launchMode="singleTask"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="invitation"
android:scheme="duobaojingcai" />
</intent-filter>
</activity>
<!-- 微信 -->
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true"
android:label="@string/app_name"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoDisplay" />
</application>
</manifest>
\ No newline at end of file
package com.maile.jingcai;
import com.maile.jingcai.base.BaseApplication;
/**
* Created by chengfeng-piaopiao on 2017/11/7.
*/
public class DuoBaoApplication extends BaseApplication {
@Override
public void onCreate() {
super.onCreate();
}
}
package com.maile.jingcai.base;
import android.app.Application;
import android.content.Context;
import com.maile.jingcai.util.DrawUtil;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
/**
* Created by chengfeng-piaopiao on 2017/11/7.
*/
public class BaseApplication extends Application{
public static IWXAPI sApi;
protected static BaseApplication sInstance;
@Override
public void onCreate() {
super.onCreate();
DrawUtil.resetDensity(this);
regToWx();
}
//初始化微信SDK
//初始化QQSDK
//初始化推送SDK
public BaseApplication() {
sInstance = this;
}
public static Context getAppContext() {
return sInstance;
}
/**
* 向微信终端注册你的id
*/
public void regToWx() {
sApi = WXAPIFactory.createWXAPI(this, Constant.WEIXIN_APP_ID, true);
sApi.registerApp(Constant.WEIXIN_APP_ID);
}
}
package com.maile.jingcai.base;
/**
* Created by chengfeng-piaopiao on 2017/11/9.
*/
public class Constant {
public static final boolean DEBUG = true;
public static final String BASE_URL = "http://192.168.1.250:81";
public static final String WEIXIN_APP_ID = "wxac811a3942bd3638";
public static final String WEIXIN_APP_SECRET = "182ad59bb146ed391f7d6c8ce5664903";
public static final String WEIXIN_AUTH_LOGIN_INFO_SCOPE = "snsapi_userinfo";
public static final String WEIXIN_AUTH_LOGIN_INFO_STATE = "wtf";
}
package com.maile.jingcai.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
/**
* Created by zoubo on 15/12/31.
* 系统时间变化监听广播,当发生天数改变时,插入一条新数据到数据库
*/
public class SmsReceiver extends BroadcastReceiver {
private static final String ACTION_SMS_RECEIVER = "android.provider.Telephony.SMS_RECEIVED";
private Context mContext;
private SmsReceiverCallback mCallback;
public SmsReceiver(SmsReceiverCallback callback, Context context) {
super();
mCallback = callback;
mContext = context;
IntentFilter filter = new IntentFilter(ACTION_SMS_RECEIVER);
filter.setPriority(999);
context.registerReceiver(this, filter);
}
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage msg;
if (null != bundle) {
Object[] smsObj = (Object[]) bundle.get("pdus");
for (Object object : smsObj) {
msg = SmsMessage.createFromPdu((byte[]) object);
getCode(msg.getDisplayMessageBody());
}
}
}
private void getCode(String msg) {
String code;
String[] strings = msg.split(":");
if (strings[0].contains("香蕉打卡")) {
code = strings[1].substring(0, 4);
} else {
code = "";
}
Log.i("tangwen", "getCode code: " + code);
mCallback.onCallback(code);
}
public interface SmsReceiverCallback {
void onCallback(String code);
}
public void destory() {
if (mContext != null) {
try {
mContext.unregisterReceiver(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mContext = null;
mCallback = null;
}
}
\ No newline at end of file
package com.maile.jingcai.commponent;
/**
* Created by chengfeng-piaopiao on 2017/11/7.
*/
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import com.maile.jingcai.R;
/**
* Created by chenjingmian on 16/7/4.
*/
public class LoginClickBtn extends LinearLayout {
private boolean mIsFocus;
private Drawable mCoverDrawable;
public LoginClickBtn(Context context) {
super(context);
init(context);
}
public LoginClickBtn(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LoginClickBtn(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mIsFocus = false;
mCoverDrawable = context.getResources().getDrawable(R.drawable.login_btn_click_cover);
initListener();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w > 0 && h > 0) {
mCoverDrawable.setBounds(0, 0, w, h);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mIsFocus) {
mCoverDrawable.draw(canvas);
}
}
private void initListener() {
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mIsFocus = true;
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mIsFocus = false;
invalidate();
break;
}
return false;
}
});
}
}
package com.maile.jingcai.commponent;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.maile.jingcai.R;
/**
* Created by chenjingmian on 16/7/5.
*/
public class LoginClickTextView extends TextView {
private boolean mIsFocus;
private Drawable mCoverDrawable;
private boolean mClickable;
public LoginClickTextView(Context context) {
super(context);
init(context);
}
public LoginClickTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LoginClickTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mIsFocus = false;
mClickable = true;
mCoverDrawable = context.getResources().getDrawable(R.drawable.login_btn_click_cover);
initListener();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w > 0 && h > 0) {
mCoverDrawable.setBounds(0, 0, w, h);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mIsFocus) {
mCoverDrawable.draw(canvas);
}
}
private void initListener() {
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (!mClickable) {
return false;
}
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mIsFocus = true;
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mIsFocus = false;
invalidate();
break;
}
return false;
}
});
}
/**
* 设置是否屏蔽touch
* @param isDisallow true是屏蔽
*/
public void disallowTouch(boolean isDisallow) {
this.mClickable = !isDisallow;
}
}
package com.maile.jingcai.module;
/**
* @version v1.0.0
* @authon zjh
* @date 2016-06-28
* @desc
*/
public class User {
}
package com.maile.jingcai.module;
/**
* @author zjh
* @date 2016/8/19
*/
public class WrapperRspEntity<T> {
private int status;
private T data;
private String msg; //errorMSG;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "WrapperRspEntity{" +
"status=" + status +
", data=" + data +
", msg='" + msg + '\'' +
'}';
}
}
package com.maile.jingcai.module.api;
import com.maile.jingcai.module.User;
import com.maile.jingcai.module.WrapperRspEntity;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public interface LoginApiService {
@GET("code")
Observable<WrapperRspEntity<String>> getMessageFormALi (@Query("phone") String phone);
@GET("login")
Observable<WrapperRspEntity<String>> loginPhone (@Query("phone") String phone , @Query("code") String code);
@GET("thirdLogin")
Observable<WrapperRspEntity<String>> thirdLogin (@Query("channel") String channel ,
@Query("openid") String openid,
@Query("accountType") String accountType ,
@Query("avatar") String avatar , @Query("nickname") String nickname);
}
package com.maile.jingcai.module.net;
import com.maile.jingcai.base.Constant;
import com.maile.jingcai.module.net.interceptor.RspCheckInterceptor;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @author zjh
* @date 2016/6/29
*/
public class RetrofitManager {
private static RetrofitManager mRetrofitManager;
private Retrofit mRetrofit;
private RetrofitManager(){
initRetrofit();
}
public static synchronized RetrofitManager getInstance(){
if (mRetrofitManager == null){
mRetrofitManager = new RetrofitManager();
}
return mRetrofitManager;
}
private void initRetrofit() {
HttpLoggingInterceptor LoginInterceptor = new HttpLoggingInterceptor();
LoginInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new RspCheckInterceptor());
if (Constant.DEBUG){
builder.addInterceptor(LoginInterceptor);
}
builder.connectTimeout(15, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
builder.retryOnConnectionFailure(true);
OkHttpClient client = builder.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
}
public <T> T createReq(Class<T> reqServer){
return mRetrofit.create(reqServer);
}
}
package com.maile.jingcai.module.net.interceptor;
import com.maile.jingcai.util.InterceptorUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* @author zjh
* @date 2016/8/31
*/
public class RspCheckInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
try {
ResponseBody rspBody = response.body();
JSONObject jsonObject = new JSONObject(InterceptorUtils.getRspData(rspBody));
int status = jsonObject.getInt("code");//status
if (status != 0 && status != 200){
throw new IOException(jsonObject.getString("msg"));
}
} catch (JSONException e) {
e.printStackTrace();
throw new IOException("parase data error");
}catch (Exception e){
if (e instanceof IOException){
throw (IOException)e;
}
}
return response;
}
}
package com.maile.jingcai.util;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 绘制工具类
*
* @author luopeihuan
*/
public class DrawUtil {
public static float sDensity = 1.0f;
public static int sDensityDpi;
public static int sWidthPixels;
public static int sHeightPixels;
public static float sFontDensity;
public static int sTouchSlop = 15; // 点击的最大识别距离,超过即认为是移动
public static int sStatusHeight; // 平板中底边的状态栏高度
private static Class sClass = null;
private static Method sMethodForWidth = null;
private static Method sMethodForHeight = null;
public static int sTopStatusHeight;
public static int sNavBarLocation;
private static int sRealWidthPixels;
private static int sRealHeightPixels;
private static int sNavBarWidth; // 虚拟键宽度
private static int sNavBarHeight; // 虚拟键高度
public static final int NAVBAR_LOCATION_RIGHT = 1;
public static final int NAVBAR_LOCATION_BOTTOM = 2;
// 在某些机子上存在不同的density值,所以增加两个虚拟值
public static float sVirtualDensity = -1;
public static float sVirtualDensityDpi = -1;
public static int sStatusBar;
/**
* @param viewData
* 根据电池状态设置view是否可见
*/
/*public static void setViewCategory(ViewData viewData)
{
String category = viewData.getAttr("category");
if (category != null)
{
int batteryState = MobileState.sBatteryState;
int batteryLevel = MobileState.sBatteryLevel;
// 电池状态: 充电
if (category.equalsIgnoreCase("Charging")
&& batteryState == BatteryManager.BATTERY_STATUS_CHARGING)
{
viewData.setBatteryVisible(true);
}
// 电池状态: 电量低:2
else if (category.equalsIgnoreCase("BatteryLow") && batteryLevel < 15
&& batteryState != BatteryManager.BATTERY_STATUS_CHARGING)
{
viewData.setBatteryVisible(true);
}
// 电池状态: 已充满:3
else if (category.equalsIgnoreCase("BatteryFull")
&& batteryState == BatteryManager.BATTERY_STATUS_FULL)
{
viewData.setBatteryVisible(true);
}
// 电池状态: 正常:0
else if (category.equalsIgnoreCase("Normal")
&& batteryState != BatteryManager.BATTERY_STATUS_CHARGING)
{
viewData.setBatteryVisible(true);
}
else
{
viewData.setBatteryVisible(false);
}
}
}*/
/**
* dip/dp转像素
* <p/>
* dip或 dp大小
*
* @return 像素值
*/
public static int dip2px(float dipVlue) {
return (int) (dipVlue * sDensity + 0.5f);
}
/**
* 像素转dip/dp
*
* @param pxValue 像素大小
* @return dip值
*/
public static int px2dip(float pxValue) {
final float scale = sDensity;
return (int) (pxValue / scale + 0.5f);
}
/**
* sp 转 px
*
* @param spValue sp大小
* @return 像素值
*/
public static int sp2px(float spValue) {
final float scale = sDensity;
return (int) (scale * spValue);
}
/**
* px转sp
*
* @param pxValue 像素大小
* @return sp值
*/
public static int px2sp(float pxValue) {
final float scale = sDensity;
return (int) (pxValue / scale);
}
public static void resetDensity(Context context) {
if (context != null && null != context.getResources()) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
sDensity = metrics.density;
sFontDensity = metrics.scaledDensity;
sWidthPixels = metrics.widthPixels;
sHeightPixels = metrics.heightPixels;
sDensityDpi = metrics.densityDpi;
if (Machine.isTablet(context)) {
sStatusHeight = getTabletScreenHeight(context) - sHeightPixels;
}
try {
final ViewConfiguration configuration = ViewConfiguration.get(context);
if (null != configuration) {
sTouchSlop = configuration.getScaledTouchSlop();
}
getStatusBarHeight(context);
} catch (Error e) {
Log.i("DrawUtil", "resetDensity has error" + e.getMessage());
}
sStatusBar = getStatusBarHeight(context);
}
resetNavBarHeight(context);
}
private static void resetNavBarHeight(Context context) {
if (context != null) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
try {
if (sClass == null) {
sClass = Class.forName("android.view.Display");
}
Point realSize = new Point();
Method method = sClass.getMethod("getRealSize", Point.class);
method.invoke(display, realSize);
sRealWidthPixels = realSize.x;
sRealHeightPixels = realSize.y;
sNavBarWidth = realSize.x - sWidthPixels;
sNavBarHeight = realSize.y - sHeightPixels;
} catch (Exception e) {
sRealWidthPixels = sWidthPixels;
sRealHeightPixels = sHeightPixels;
sNavBarHeight = 0;
}
}
sNavBarLocation = getNavBarLocation();
}
public static int getTabletScreenWidth(Context context) {
int width = 0;
if (context != null) {
try {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if (sClass == null) {
sClass = Class.forName("android.view.Display");
}
if (sMethodForWidth == null) {
sMethodForWidth = sClass.getMethod("getRealWidth");
}
width = (Integer) sMethodForWidth.invoke(display);
} catch (Exception e) {
}
}
// Rect rect= new Rect();
// ((Activity)
// context).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
// int statusbarHeight = height - rect.bottom;
if (width == 0) {
width = sWidthPixels;
}
return width;
}
public static int getTabletScreenHeight(Context context) {
int height = 0;
if (context != null) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
try {
if (sClass == null) {
sClass = Class.forName("android.view.Display");
}
if (sMethodForHeight == null) {
sMethodForHeight = sClass.getMethod("getRealHeight");
}
height = (Integer) sMethodForHeight.invoke(display);
} catch (Exception e) {
}
}
// Rect rect= new Rect();
// ((Activity)
// context).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
// int statusbarHeight = height - rect.bottom;
if (height == 0) {
height = sHeightPixels;
}
return height;
}
public static boolean isPad() {
if (sDensity >= 1.5 || sDensity <= 0) {
return false;
}
if (sWidthPixels < sHeightPixels) {
if (sWidthPixels > 480 && sHeightPixels > 800) {
return true;
}
} else {
if (sWidthPixels > 800 && sHeightPixels > 480) {
return true;
}
}
return false;
}
public static int getStatusBarHeight(Context context) {
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0;
int top = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
top = context.getResources().getDimensionPixelSize(x);
sTopStatusHeight = top;
} catch (Exception e1) {
e1.printStackTrace();
}
return top;
}
public static int getRealWidth() {
if (Machine.s_IS_SDK_ABOVE_KITKAT) {
return sRealWidthPixels;
}
return sWidthPixels;
}
public static int getRealHeight() {
if (Machine.s_IS_SDK_ABOVE_KITKAT) {
return sRealHeightPixels;
}
return sHeightPixels;
}
/**
* 虚拟键在下面时
*
* @return
*/
public static int getNavBarHeight() {
if (Machine.s_IS_SDK_ABOVE_KITKAT) {
return sNavBarHeight;
}
return 0;
}
/**
* 横屏,虚拟键在右边时
*
* @return
*/
public static int getNavBarWidth() {
if (Machine.s_IS_SDK_ABOVE_KITKAT) {
return sNavBarWidth;
}
return 0;
}
public static int getNavBarLocation() {
if (sRealWidthPixels > sWidthPixels) {
return NAVBAR_LOCATION_RIGHT;
}
return NAVBAR_LOCATION_BOTTOM;
}
/**
* 底部状态栏高度
*/
public static int getNavigationBarHeight(Context context) {
if (Build.VERSION.SDK_INT >= 19) {
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
int height = resources.getDimensionPixelSize(resourceId);
return height;
} else {
return 0;
}
}
/**
* 判断是否显示了状态栏
*
* @param activity
* @return
*/
public static boolean isNavigationBarExist2(Activity activity) {
WindowManager windowManager = activity.getWindowManager();
Display d = windowManager.getDefaultDisplay();
DisplayMetrics realDisplayMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
d.getRealMetrics(realDisplayMetrics);
}
int realHeight = realDisplayMetrics.heightPixels;
int realWidth = realDisplayMetrics.widthPixels;
DisplayMetrics displayMetrics = new DisplayMetrics();
d.getMetrics(displayMetrics);
int displayHeight = displayMetrics.heightPixels;
int displayWidth = displayMetrics.widthPixels;
return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
}
/**
* 裁剪成圆形图片
*
* @param bitmap 原图
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
if (bitmap != null) {
Bitmap moutBitmap = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas mcanvas = new Canvas(moutBitmap);
final int mcolor = 0xff424242;
final Paint mpaint = new Paint();
final Rect mrect = new Rect(0, 0, bitmap.getWidth(),
bitmap.getHeight());
final RectF mrectF = new RectF(mrect);
final float mroundPX = bitmap.getWidth() / 2;
mpaint.setAntiAlias(true);
mcanvas.drawARGB(0, 0, 0, 0);
mpaint.setColor(mcolor);
mcanvas.drawRoundRect(mrectF, mroundPX, mroundPX, mpaint);
mpaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
mcanvas.drawBitmap(bitmap, mrect, mrect, mpaint);
return moutBitmap;
} else {
return null;
}
}
public static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
//使用Bitmap加Matrix来缩放
public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
Bitmap BitmapOrg = bitmap;
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}
public static void setTranslucentStatusBar(Window window) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
// | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
// window.setNavigationBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
public static void setNoTranslucentStatusBar(Window window) {
Log.i("zou", "DrawUtil setNoTranslucentStatusBar");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.i("zou", "DrawUtil setNoTranslucentStatusBar1111");
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLACK);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Log.i("zou", "DrawUtil setNoTranslucentStatusBar2222");
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
}
/**
* 跑步中使用截图
*
* @param view
* @return
*/
public static Bitmap convertViewToBitmap(View view) {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheEnabled(false);
return bitmap;
}
}
package com.maile.jingcai.util;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
/**
* @author zjh
* @date 2016/9/2
*/
public class InterceptorUtils {
private static final Charset UTF8 = Charset.forName("UTF-8");
public static String getRspData(ResponseBody responseBody) throws Exception {
long contentLength = responseBody.contentLength();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
return null;
}
}
if (contentLength != 0) {
return new JSONObject(buffer.clone().readString(charset)).toString(); //because response content contain quotation mark
}
return null;
}
public static String getReqData(RequestBody requestBody) throws IOException {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return buffer.readString(UTF8);
}
public static Response changeRspData(Response response, String rspData) {
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType,rspData);
return response.newBuilder().body(body).build();
}
}
package com.maile.jingcai.util;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;
/**
* @author jiangxuwen
*/
// CHECKSTYLE:OFF
public class Machine {
public static int LEPHONE_ICON_SIZE = 72;
private static boolean sCheckTablet = false;
private static boolean sIsTablet = false;
// 硬件加速
public static int LAYER_TYPE_NONE = 0x00000000;
public static int LAYER_TYPE_SOFTWARE = 0x00000001;
public static int LAYER_TYPE_HARDWARE = 0x00000002;
public static boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= 11;
public static boolean IS_HONEYCOMB_MR1 = Build.VERSION.SDK_INT >= 12;
public static boolean IS_ICS = Build.VERSION.SDK_INT >= 14;
public static boolean IS_ICS_MR1 = Build.VERSION.SDK_INT >= 15 && Build.VERSION.RELEASE.equals("4.0.4");// HTC oneX 4.0.4系统
public static boolean sLevelUnder3 = Build.VERSION.SDK_INT < 11;// 版本小于3.0
private static Method sAcceleratedMethod = null;
public static boolean s_IS_SDK_ABOVE_KITKAT = Build.VERSION.SDK_INT >= 19;
public static boolean s_IS_SDK_ABOVE_18 = Build.VERSION.SDK_INT >= 18;
public static boolean s_IS_SDK_ABOVE_LOLLIPOP = Build.VERSION.SDK_INT >= 21;
private final static String LEPHONEMODEL[] = {"3GW100", "3GW101", "3GC100", "3GC101"};
private final static String MEIZUBOARD[] = {"m9", "M9", "mx", "MX"};
private final static String M9BOARD[] = {"m9", "M9"};
private final static String ONE_X_MODEL[] = {"HTC One X", "HTC One S"};
public final static String XIAOMI = "xiaomi";
public final static String XIAOMI4 = "xiaomi4";
public final static String BRAND_OPPO = "oppo";
public static final boolean IS_JELLY_BEAN = Build.VERSION.SDK_INT >= 16;
public static final String XIAOMI_VERSION_CODE6 = "v6";
public static final String XIAOMI_VERSION_CODE5 = "v5";
public static boolean isLephone() {
final String model = Build.MODEL;
if (model == null) {
return false;
}
final int size = LEPHONEMODEL.length;
for (int i = 0; i < size; i++) {
if (model.equals(LEPHONEMODEL[i])) {
return true;
}
}
return false;
}
/**
* <br>功能简述:获取Android ID的方法
* <br>功能详细描述:
* <br>注意:
*
* @return
*/
public static String getAndroidId(Context context) {
String androidId = null;
if (context != null) {
androidId = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
}
return androidId;
}
public static String getVersionCode(Context context) {
String versionCode = null;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
versionCode = pInfo.versionCode + "";
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return versionCode;
}
/**
* <br>功能简述:获取versionCode
* <br>功能详细描述:
* <br>注意:
*
* @param context
* @return
*/
public static String getVersionName(Context context) {
String versionCode = null;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
versionCode = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
// public static String getChannel(Context context) {
// return BuildConfig.FLAVOR;
// }
private static String getApplicationMetaValue(Context context, String name) {
String value = "";
try {
ApplicationInfo appInfo = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
value = appInfo.metaData.getString(name);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return value;
}
public static String getIMSI(Context context) {
String imsi = null;
try {
if (context != null) {
// 从系统服务上获取了当前网络的MCC(移动国家号),进而确定所处的国家和地区
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
imsi = manager.getSubscriberId();
imsi = (imsi == null) ? "000" : imsi;
}
} catch (Throwable e) {
}
return imsi;
}
public static String getIMEI(Context context) {
try {
return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
.getDeviceId();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String getPhoneNumber(Context context) {
String phone = null;
try {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
phone = tm.getLine1Number();//手机号码
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return phone;
}
public static boolean isM9() {
return isPhone(M9BOARD);
}
public static boolean isMeizu() {
boolean isMeizu = isPhone(MEIZUBOARD);
final String board = Build.BOARD;
if (board == null) {
return false;
}
if (board.contains("mx") || board.contains("MX")) {
isMeizu = true;
}
return isMeizu;
}
public static boolean isONE_X() {
return checkModel(ONE_X_MODEL);
}
private static boolean isPhone(String[] boards) {
final String board = Build.BOARD;
if (board == null) {
return false;
}
final int size = boards.length;
for (int i = 0; i < size; i++) {
if (board.equals(boards[i])) {
return true;
}
}
return false;
}
private static boolean checkModel(String[] models) {
final String board = Build.MODEL;
if (board == null) {
return false;
}
final int size = models.length;
for (int i = 0; i < size; i++) {
if (board.equals(models[i])) {
return true;
}
}
return false;
}
/**
* 因为主题2.0新起进程,无法获取GoLauncher.getContext(), 所以重载此方法,以便主题2.0调用
*
* @param context
* @return
*/
public static boolean isCnUser(Context context) {
boolean result = false;
if (context != null) {
// 从系统服务上获取了当前网络的MCC(移动国家号),进而确定所处的国家和地区
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
// SIM卡状态
boolean simCardUnable = manager.getSimState() != TelephonyManager.SIM_STATE_READY;
String simOperator = manager.getSimOperator();
if (simCardUnable || TextUtils.isEmpty(simOperator)) {
// 如果没有SIM卡的话simOperator为null,然后获取本地信息进行判断处理
// 获取当前国家或地区,如果当前手机设置为简体中文-中国,则使用此方法返回CN
String curCountry = Locale.getDefault().getCountry();
if (curCountry != null && curCountry.contains("CN")) {
// 如果获取的国家信息是CN,则返回TRUE
result = true;
} else {
// 如果获取不到国家信息,或者国家信息不是CN
result = false;
}
} else if (simOperator.startsWith("460")) {
// 如果有SIM卡,并且获取到simOperator信息。
/**
* 中国大陆的前5位是(46000) 中国移动:46000、46002 中国联通:46001 中国电信:46003
*/
result = true;
}
}
return result;
}
// 根据系统版本号判断时候为华为2.2 or 2.2.1, Y 则catch
public static boolean isHuaweiAndOS2_2_1() {
boolean resault = false;
String androidVersion = Build.VERSION.RELEASE;// os版本号
String brand = Build.BRAND;// 商标
if (androidVersion == null || brand == null) {
return resault;
}
if (brand.equalsIgnoreCase("Huawei")
&& (androidVersion.equals("2.2") || androidVersion.equals("2.2.2")
|| androidVersion.equals("2.2.1") || androidVersion.equals("2.2.0"))) {
resault = true;
}
return resault;
}
public static boolean isHuawei() {
boolean resault = false;
String androidVersion = Build.VERSION.RELEASE;// os版本号
String brand = Build.BRAND;// 商标
if (androidVersion == null || brand == null) {
return resault;
}
if (brand.equalsIgnoreCase("Huawei")) {
resault = true;
}
return resault;
}
// 判断当前设备是否为平板
private static boolean isPad() {
if (DrawUtil.sDensity >= 1.5 || DrawUtil.sDensity <= 0) {
return false;
}
if (DrawUtil.sWidthPixels < DrawUtil.sHeightPixels) {
if (DrawUtil.sWidthPixels > 480 && DrawUtil.sHeightPixels > 800) {
return true;
}
} else {
if (DrawUtil.sWidthPixels > 800 && DrawUtil.sHeightPixels > 480) {
return true;
}
}
return false;
}
public static boolean isTablet(Context context) {
if (sCheckTablet == true) {
return sIsTablet;
}
sCheckTablet = true;
sIsTablet = isPad();
// if(null == context || DrawUtil.sDensity >= 1.5)
// {
// sIsTablet = isPad();
// }
// else
// {
// sIsTablet = (context.getResources().getConfiguration().screenLayout &
// Configuration.SCREENLAYOUT_SIZE_MASK) >=
// Configuration.SCREENLAYOUT_SIZE_LARGE;
// }
//
return sIsTablet;
}
/**
* 判断当前网络是否可以使用
*
* @param context
* @return
* @author huyong
*/
public static boolean isNetworkOK(Context context) {
boolean result = false;
if (context != null) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
result = true;
}
}
}
return result;
}
/**
* 设置硬件加速
*
* @param view
*/
public static void setHardwareAccelerated(View view, int mode) {
if (sLevelUnder3) {
return;
}
try {
if (null == sAcceleratedMethod) {
sAcceleratedMethod = View.class.getMethod("setLayerType", new Class[]{
Integer.TYPE, Paint.class});
}
sAcceleratedMethod.invoke(view, new Object[]{Integer.valueOf(mode), null});
} catch (Throwable e) {
sLevelUnder3 = true;
}
}
public static boolean isIceCreamSandwichOrHigherSdk() {
return Build.VERSION.SDK_INT >= 14;
}
/**
* 获取Android中的Linux内核版本号
*/
public static String getLinuxKernel() {
Process process = null;
try {
process = Runtime.getRuntime().exec("cat /proc/version");
} catch (IOException e) {
e.printStackTrace();
}
if (null == process) {
return null;
}
// get the output line
InputStream outs = process.getInputStream();
InputStreamReader isrout = new InputStreamReader(outs);
BufferedReader brout = new BufferedReader(isrout, 8 * 1024);
String result = "";
String line;
// get the whole standard output string
try {
while ((line = brout.readLine()) != null) {
result += line;
}
} catch (IOException e) {
e.printStackTrace();
}
if (!result.equals("")) {
String keyword = "version ";
int index = result.indexOf(keyword);
line = result.substring(index + keyword.length());
if (null != line) {
index = line.indexOf(" ");
return line.substring(0, index);
}
}
return null;
}
/**
* 获得手机内存的可用空间大小
*
* @author kingyang
*/
public static long getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
/**
* 获得手机内存的总空间大小
*
* @author kingyang
*/
public static long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
/**
* 获得手机sdcard的可用空间大小
*
* @author kingyang
*/
public static long getAvailableExternalMemorySize() {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
/**
* 获得手机sdcard的总空间大小
*
* @author kingyang
*/
public static long getTotalExternalMemorySize() {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
/**
* 是否存在SDCard
*
* @return
* @author chenguanyu
*/
public static boolean isSDCardExist() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/**
* 获取当前的语言
*
* @param context
* @return
* @author zhoujun
*/
public static String getLanguage(Context context) {
String language = context.getResources().getConfiguration().locale.getLanguage();
return language;
}
/**
* 判断应用软件是否运行在前台
*
* @param context
* @param packageName 应用软件的包名
* @return
*/
public static boolean isTopActivity(Context context, String packageName) {
try {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
if (tasksInfo.size() > 0) {
// 应用程序位于堆栈的顶层
if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())) {
return true;
}
}
} catch (Exception e) {
}
return false;
}
public static String getAndroidId() {
// TODO Auto-generated method stub
return null;
}
public static boolean isMiuiV5() {
boolean resault = false;
String brand = Build.BRAND; // 商标
if (brand == null) {
return resault;
}
if (IS_JELLY_BEAN) {
Log.e("zou", "brand== " + brand);
if (brand.toLowerCase().contains(XIAOMI)) {
return true;
}
}
return resault;
}
/**
* 判断是否是OPPO
*/
public static boolean isOPPO() {
boolean result = false;
if (Build.VERSION.SDK_INT < 14) {
return false; //过滤4.0以下机型
}
String brand = Build.BRAND; // 商标
if (brand == null) {
return result;
}
Log.e("MM", "brand== " + brand);
if (brand.toLowerCase().contains(BRAND_OPPO)) {
result = true;
}
return result;
}
/**
* 获取SD卡剩余空间
*
* @return
*/
public static long getSDFreeSize() {
// 取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
long blockSize = sf.getBlockSize();
// 空闲的数据块的数量
long freeBlocks = sf.getAvailableBlocks();
// 返回SD卡空闲大小
return freeBlocks * blockSize; // 单位K
}
public static String checkNetWordState(Context context) {
NetworkInfo mobNetInfo = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (mobNetInfo != null) {
if (mobNetInfo.isAvailable()) {
int netType = mobNetInfo.getType();
if (netType == ConnectivityManager.TYPE_WIFI) {
return "wifi";
} else if (netType == ConnectivityManager.TYPE_MOBILE) {
if (mobNetInfo.getExtraInfo() != null) {
String netMode = mobNetInfo.getExtraInfo().toLowerCase();
if (netMode.equals("cmwap")) {
return "cmwap";
} else {
return "cmnet";
}
}
}
}
}
return "other";
}
public static String getMiuiVersionName() {
String propName = "ro.miui.ui.version.name";
String line;
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("getprop " + propName);
input = new BufferedReader(
new InputStreamReader(p.getInputStream()), 1024);
line = input.readLine();
input.close();
} catch (IOException ex) {
Log.e("printTask", "Unable to read sysprop " + propName, ex);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e("printTask", "Exception while closing InputStream", e);
}
}
}
return line;
}
public static boolean isMiuiVSixOrAbove() {
boolean result = false;
String version = getMiuiVersionName();
if (version != null && version.trim().toLowerCase().contains(XIAOMI_VERSION_CODE6)) {
result = true;
}
return result;
}
public static boolean isMiuiVFive() {
boolean result = false;
String version = getMiuiVersionName();
if (version != null && version.trim().toLowerCase().contains(XIAOMI_VERSION_CODE5)) {
result = true;
}
return result;
}
/**
* 判断是否是魅族flyme4.2以上才显示
*/
public static boolean isMeizuAndFlyme4() {
return isMeizu() && Build.VERSION.SDK_INT >= 19;
}
public static void gotoMeizuSetting(Context context) {
try {
//魅族省电管理
Intent intent = new Intent("com.meizu.power.POWER_UI_MAIN");
ComponentName cName = new ComponentName("com.meizu.safe", "com.meizu.safe.powerui.AppPowerManagerActivity");
intent.setComponent(cName);
context.startActivity(intent);
} catch (Exception e) {
}
}
}
package com.maile.jingcai.util;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
/**
* Created by Administrator on 2015/8/11.
*/
public class NetUtils {
/**
* 是否连接网络
**/
public static boolean isNetworkOK(Context context) {
boolean result = false;
if (context != null) {
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
result = true;
}
}
} catch (NoSuchFieldError e) {
e.printStackTrace();
}
}
return result;
}
/**
* 判断是wifi还是3g网络
*/
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkINfo = cm.getActiveNetworkInfo();
if (networkINfo != null
&& networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}
/**
* 判断WIFI是否打开
*/
public static boolean isWifiEnabled(Context context) {
ConnectivityManager mgrConn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}
/**
* 获取当前网络状态,wifi,GPRS,3G,4G
*
* @param context
* @return
*/
public static String buildNetworkState(Context context) {
// build Network conditions
String ret = "";
try {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
if (networkinfo == null) {
return ret;
}
if (networkinfo.getType() == ConnectivityManager.TYPE_WIFI) {
ret = "WIFI";
} else if (networkinfo.getType() == ConnectivityManager.TYPE_MOBILE) {
int subtype = networkinfo.getSubtype();
switch (subtype) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_IDEN:
// 2G
ret = "2G";
break;
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_UMTS:
// 3G,4G
ret = "3G/4G";
break;
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
// unknow
ret = "UNKNOW";
break;
}
} else {
ret = "UNKNOW";
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* 获取IP地址
**/
public static String getIpAddress(Context context) {
try {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int i = wifiInfo.getIpAddress();
return int2ip(i);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* 将ip的整数形式转换成ip形式
**/
public static String int2ip(int ipInt) {
StringBuilder sb = new StringBuilder();
sb.append(ipInt & 0xFF).append(".");
sb.append((ipInt >> 8) & 0xFF).append(".");
sb.append((ipInt >> 16) & 0xFF).append(".");
sb.append((ipInt >> 24) & 0xFF);
return sb.toString();
}
/*
* 打开设置网络界面
* */
public static void setNetworkMethod(final Context context) {
//提示对话框
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("网络不可用").setMessage("跑步精准定位地图需要很少网络支持,是否开启网络尽情跑步?").setPositiveButton("开启", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
//判断手机系统的版本 即API大于10 就是3.0或以上版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(Settings.ACTION_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
package com.maile.jingcai.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* @author zjh
* @date 2016/9/1
*/
public class NetworkUtils {
/**
* 判断是否有网络连接
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
}
package com.maile.jingcai.util;
import android.view.Gravity;
import android.widget.Toast;
import com.maile.jingcai.base.BaseApplication;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public class PublicUtils {
/**
* 去除空格
*/
public static String removeAllSpace(String str) {
String tmpStr = str.replace(" ", "");
return tmpStr;
}
public static void showToast(String showString) {
Toast toast = Toast.makeText(BaseApplication.getAppContext(), showString + "", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
package com.maile.jingcai.util;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* <br>类描述:
* <br>功能详细描述:
*/
public class UtilTool {
public static final String NET_WIFI = "wifi";
public static final String GOOGLE_PALY_PACKAGE = "com.android.vending";
public static final int SUCCESS = 100; // 本地检测通过
public static final int ERROR_PASSWORD_LENGTH = 101; // 密码长度要求6~20位
public static final int ERROR_NICKNAME_LENGTH = 106; // 密码长度要求6~20位
public static final int NETTYPE_MOBILE = 0; // 中国移动
public static final int NETTYPE_UNICOM = 1; // 中国联通
public static final int NETTYPE_TELECOM = 2; // 中国电信
private static final String SMS_URI_SEND = "content://sms/sent";
/**
* 启动浏览器时需要过滤的包,如淘宝客户端
*/
public static final String[] FILTER_BROWSER_PKGS = {"com.xiaomi.market", "com.taobao.taobao", "com.sohu.newsclient"};
public static PackageInfo getVersionInfo(Context context, String pkg) {
PackageManager pm = context.getPackageManager();
PackageInfo info = null;
try {
info = pm.getPackageInfo(pkg, 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return info;
}
/**
* 检查是安装某包
*
* @param context
* @param packageName 包名
* @return
*/
public static boolean isAppExist(final Context context, final String packageName) {
boolean result = false;
if (context == null || packageName == null) {
return result;
}
try {
// context.createPackageContext(packageName,
// Context.CONTEXT_IGNORE_SECURITY);
context.getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SHARED_LIBRARY_FILES);
result = true;
} catch (NameNotFoundException e) {
// TODO: handle exception
result = false;
} catch (Exception e) {
result = false;
}
return result;
}
public static boolean isGooglePalyExist(final Context context) {
return isAppExist(context, GOOGLE_PALY_PACKAGE);
}
public static int boolean2Int(boolean bool) {
return bool ? 1 : 0;
}
public static boolean int2Boolean(int value) {
return value == 1 ? true : false;
}
public static String getNetworkType(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
// 获取网络连接管理的对象
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED && info.getTypeName() != null) {
if (info.getTypeName().equals("WIFI")) {
return NET_WIFI;
} else {
return info.getTypeName().toLowerCase();
}
}
}
}
return null;
}
public static String unzip(String zipStr, String charsetName) throws IOException {
return unzip(zipStr.getBytes(charsetName));
}
public static String unzip(byte[] byteArray) throws IOException {
int buffer_size = 1024;
ByteArrayInputStream is = new ByteArrayInputStream(byteArray);
GZIPInputStream gis = new GZIPInputStream(is, buffer_size);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[buffer_size];
int bytesRead;
while ((bytesRead = gis.read(data, 0, buffer_size)) != -1) {
baos.write(data, 0, bytesRead);
}
gis.close();
is.close();
return new String(baos.toByteArray(), "UTF-8");
}
public static String gzip(byte[] bs) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
GZIPOutputStream gzout = null;
try {
gzout = new GZIPOutputStream(bout);
gzout.write(bs);
gzout.flush();
} catch (Exception e) {
throw e;
} finally {
if (gzout != null) {
try {
gzout.close();
} catch (Exception ex) {
}
}
}
String result = null;
if (bout != null) {
result = bout.toString("ISO-8859-1");
}
return result;
}
public static byte[] gzipByte(byte[] bs) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream(1000);
GZIPOutputStream gzout = null;
try {
gzout = new GZIPOutputStream(bout);
gzout.write(bs);
gzout.flush();
} catch (Exception e) {
throw e;
} finally {
if (gzout != null) {
try {
gzout.close();
} catch (Exception ex) {
}
}
}
byte result[] = null;
if (bout != null) {
result = bout.toByteArray();
}
return result;
}
/**
* 是否cmwap连接
*/
public static boolean isCWWAPConnect(Context context) {
boolean result = false;
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) {
if (Proxy.getDefaultHost() != null || Proxy.getHost(context) != null) {
result = true;
}
}
return result;
}
/**
* 获取网络类型
*
* @param context
* @return 1 for 移动,2 for 联通,3 for 电信,-1 for 不能识别
*/
public static int getNetWorkType(Context context) {
int netType = -1;
// 从系统服务上获取了当前网络的MCC(移动国家号),进而确定所处的国家和地区
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String simOperator = manager.getSimOperator();
if (simOperator != null) {
if (simOperator.startsWith("46000") || simOperator.startsWith("46002")) {
// 因为移动网络编号46000下的IMSI已经用完,
// 所以虚拟了一个46002编号,134/159号段使用了此编号
// 中国移动
netType = NETTYPE_MOBILE;
} else if (simOperator.startsWith("46001")) {
// 中国联通
netType = NETTYPE_UNICOM;
} else if (simOperator.startsWith("46003")) {
// 中国电信
netType = NETTYPE_TELECOM;
}
}
return netType;
}
/**
* <br>功能简述: 获取sim卡状态
* <br>功能详细描述:
* <br>注意:
*
* @param context
* @return
*/
public static int getSimStatus(Context context) {
TelephonyManager telManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telManager.getSimState();
}
/**
* <br>功能简述:判断sim卡是否能用
* <br>功能详细描述:
* <br>注意:
*
* @param context
* @return
*/
public static boolean isSimReady(Context context) {
boolean res = false;
int status = getSimStatus(context);
if (status == TelephonyManager.SIM_STATE_READY) {
res = true;
}
return res;
}
public static String getProxyHost(Context context) {
return Proxy.getHost(context);
}
public static int getProxyPort(Context context) {
return Proxy.getPort(context);
}
public static boolean isLegalEmailAddress(String email) {
Pattern pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean isLegalPhoneNumber(String number) {
number = number.replace(" ", "");
if (number.startsWith("+86")) {
number = number.substring(number.indexOf("+86") + 3).trim();
}
Pattern pattern = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
Matcher matcher = pattern.matcher(number);
return matcher.matches();
}
public static int isLegalPassword(String password) {
int ret = SUCCESS;
if (password.length() < 6 || password.length() > 20) {
ret = ERROR_PASSWORD_LENGTH;
}
return ret;
}
public static int isLegalNickName(String nickName) {
int ret = SUCCESS;
if (nickName.length() > 8) {
ret = ERROR_PASSWORD_LENGTH;
}
return ret;
}
public static void putJsonValue(JSONObject obj, String key, int value) {
try {
obj.put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void putJsonValue(JSONObject obj, String key, double value) {
try {
obj.put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void putJsonValue(JSONObject obj, String key, long value) {
try {
obj.put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void putJsonValue(JSONObject obj, String key, boolean value) {
try {
obj.put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void putJsonValue(JSONObject obj, String key, Object value) {
try {
obj.put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String unzipData(InputStream inStream) {
try {
byte[] old_bytes = toByteArray(inStream);
String old = new String(old_bytes, "UTF-8");
// Loger.e(null, old);
byte[] new_bytes = ungzip(old_bytes);
return new String(new_bytes, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static byte[] ungzip(byte[] bs) throws Exception {
GZIPInputStream gzin = null;
ByteArrayInputStream bin = null;
try {
bin = new ByteArrayInputStream(bs);
gzin = new GZIPInputStream(bin);
return toByteArray(gzin);
} catch (Exception e) {
throw e;
} finally {
if (bin != null) {
bin.close();
}
}
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static int copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024 * 4];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
/**
* <br>功能简述:解析actValue;
* <br>actValue的格式如下:
* <br>a) intent:classname=*****?arg1=I3#arg2=Stest#arg3=Ztrue#arg4=J8888#arg5=F1.0#arg5=D1.00
* <br>b) intent:action=*****?arg1=I3#arg2=Stest
* <br>功能详细描述:
* <br>注意:
*
* @return
* @throws Exception
*/
public static Intent praseIntent(Context context, String url) throws Exception {
// TODO Auto-generated method stub
String[] actValues = url.split("\\?", 4);
String intentStr = actValues[0];
intentStr = intentStr.replace("intent:", "");
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String[] actionOrClass = intentStr.split("=", 2);
if (actionOrClass.length > 1) {
if (intentStr.startsWith("classname=")) {
intent.setClassName(context, actionOrClass[1]);
} else if (intentStr.startsWith("action=")) {
intent.setAction(actionOrClass[1]);
}
} else {
// throw new Exception("messageManager->parseActValue:actionOrClass 不能为空");
return null;
}
if (actValues.length > 1) {
// 如果有参数
String[] attributes = actValues[1].split("#");
for (int i = 0; i < attributes.length; i++) {
String[] atts = attributes[i].split("=", 2);
if (atts.length != 2) {
break;
}
String attName = atts[0];
String attType = "";
String attValue = "";
attType = atts[1].substring(0, 1);
if (atts[1].length() < 2) {
// 等号后面只有1个字符,可能参数为空字符串
// 当attType=S的时候attValue保持空字符串
if (!attType.equals("S")) {
// 因为参数格式错误,舍弃这次的参数
continue;
}
} else {
attValue = atts[1].substring(1, atts[1].length());
}
if (attName.equals("Uri")) {
intent.setData(Uri.parse(attValue));
}
buildInent(intent, attName, attType, attValue);
}
}
return intent;
}
/**
* <br>功能简述:构建intent的参数
* <br>功能详细描述:
* <br>注意:attType的含义:
* I表示int,
* S表示String,
* Z表示bool,
* J表示long
* F表示float
* D表示double
* B表示Byte
*
* @param intent
* @param attName 属性名
* @param attType 属性类型
* @param attValue 属性值
*/
public static void buildInent(Intent intent, String attName, String attType, String attValue) {
// TODO Auto-generated method stub
if (attType.equals("I")) {
intent.putExtra(attName, Integer.parseInt(attValue));
} else if (attType.equals("S")) {
if (attName.equals("Uri")) {
intent.setData(Uri.parse(formatUri(attValue)));
} else {
intent.putExtra(attName, attValue);
}
} else if (attType.equals("Z")) {
intent.putExtra(attName, Boolean.parseBoolean(attValue));
} else if (attType.equals("J")) {
intent.putExtra(attName, Long.parseLong(attValue));
} else if (attType.equals("F")) {
intent.putExtra(attName, Float.parseFloat(attValue));
} else if (attType.equals("D")) {
intent.putExtra(attName, Double.parseDouble(attValue));
} else if (attType.equals("B")) {
intent.putExtra(attName, Byte.parseByte(attValue));
}
}
public static void gotoBrowser(Context context, String uriString) {
// 跳转intent
Uri uri = Uri.parse(uriString);
Intent myIntent = new Intent(Intent.ACTION_VIEW, uri);
// 1:已安装的浏览器列表
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveList = pm.queryIntentActivities(myIntent, 0);
// 无正在运行的浏览器,直接取浏览器列表的第1个打开
ResolveInfo resolveInfo = resolveList.get(0);
String pkgString = resolveInfo.activityInfo.packageName;
String activityName = resolveInfo.activityInfo.name;
myIntent.setClassName(pkgString, activityName);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
/**
* <br>功能简述:不弹浏览器选择框,直接开网页。
* <br>功能详细描述:优先打开默认浏览器,其次使用正在运行的浏览器,再次打开获取到的第一个浏览器
* <br>注意:会过滤掉
*
* @param mContext
* @param uriString
* @param doFilter 是否过滤特殊应用,如淘宝等
*/
public static void gotoDefaultBrowser(Context mContext, String uriString, boolean doFilter) {
// 跳转intent
Uri uri = Uri.parse(uriString);
Intent myIntent = new Intent(Intent.ACTION_VIEW, uri);
// 1:已安装的浏览器列表
PackageManager pm = mContext.getPackageManager();
List<ResolveInfo> resolveList = pm.queryIntentActivities(myIntent, 0);
// 过滤删除扫描出来的指定包名的应用
if (doFilter) {
resolveList = filterPkgs(resolveList, FILTER_BROWSER_PKGS);
}
// 获取系统默认设置列表
List<ComponentName> componentNames = new ArrayList<ComponentName>();
List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
pm.getPreferredActivities(intentFilters, componentNames, null);
if (resolveList != null && !resolveList.isEmpty()) {
// 查看是否有设置默认浏览器,若是有,用默认打开
int preferredSz = componentNames.size();
for (ResolveInfo resolveInfo : resolveList) {
if (resolveInfo != null) {
String packageStr = resolveInfo.activityInfo.packageName;
for (int j = 0; j < preferredSz; j++) {
ComponentName componentName = componentNames.get(j);
if (null == componentName) {
continue;
}
if (packageStr.equals(componentName.getPackageName())) {
String activityName = resolveInfo.activityInfo.name;
myIntent.setClassName(packageStr, activityName);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(myIntent);
return;
}
}
}
}
mContext.startActivity(myIntent);
} else {
}
}
/**
* <br>功能简述:在列表里过滤删除指定包名的应用
* <br>功能详细描述:
* <br>注意:
*
* @param resolveList
* @param pkgs
* @return
*/
public static List<ResolveInfo> filterPkgs(List<ResolveInfo> resolveList, String[] pkgs) {
if (resolveList == null || resolveList.size() == 0 || pkgs == null || pkgs.length == 0) {
return resolveList;
}
ArrayList<ResolveInfo> list = new ArrayList<ResolveInfo>(resolveList);
for (ResolveInfo resolveInfo : resolveList) {
if (resolveInfo != null && resolveInfo.activityInfo != null && resolveInfo.activityInfo.packageName != null) {
for (String pkg : pkgs) {
if (resolveInfo.activityInfo.packageName.equals(pkg)) {
list.remove(resolveInfo);
break;
}
}
}
}
return list;
}
public static String filterContent(String content, String beginTag, String endTag) {
String result = null;
do {
if (content != null && beginTag != null && endTag != null) {
int start = -1;
int end = -1;
if (TextUtils.isEmpty(beginTag)) {
start = 0;
} else {
start = content.indexOf(beginTag.trim()) + beginTag.length();
}
if (TextUtils.isEmpty(endTag)) {
end = 0;
} else {
end = content.indexOf(endTag);
}
if (start == -1 || end == -1 || end <= start) {
break;
}
result = content.substring(start, end);
}
} while (false);
return result;
}
public static boolean isSDMounted() {
boolean sdCardExist = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED); //判断sd卡是否存在
return sdCardExist;
}
public static long getSDFreeSize() {
// 取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
long blockSize = sf.getBlockSize();
// 空闲的数据块的数量
long freeBlocks = sf.getAvailableBlocks();
// 返回SD卡空闲大小
return freeBlocks * blockSize / 1024; // 单位K
}
public static boolean hasEnoughSDFreeSize() {
return getSDFreeSize() > 2;
}
public static void hideSoftInput(Context context) {
if (context != null) {
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager.isActive()) {
inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
/**
* 用于把被转义下发的URL还原的工具
*
* @param url
* @return
*/
public static String formatUri(String url) {
if (url == null) {
return null;
}
String newUri = url.replaceAll("%3A", ":");
newUri = newUri.replaceAll("%2F", "/");
newUri = newUri.replaceAll("%2B", "+");
newUri = newUri.replaceAll("%20", " ");
newUri = newUri.replaceAll("%3F", "?");
newUri = newUri.replaceAll("%25 ", "%");
newUri = newUri.replaceAll("%23 ", "#");
newUri = newUri.replaceAll("%26", "&");
newUri = newUri.replaceAll("%3D", "=");
return newUri;
}
// 设置过滤字符函数(过滤掉我们不需要的字符)
public static String stringFilter(String str) {
String result = str;
try {
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
result = m.replaceAll("");
} catch (PatternSyntaxException e) {
e.printStackTrace();
}
return result;
}
/**
* 用来判断服务是否运行.
*
* @param context
* @param className 判断的服务名字
* @return true 在运行 false 不在运行
*/
public static boolean isServiceRunning(Context context, String className) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(300);
if (!(serviceList.size() > 0)) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
//Log.i("UtilTool---->", "服务名:-->"+serviceList.get(i).service.getClassName());
if (serviceList.get(i).service.getClassName().equals(className) == true) {
isRunning = true;
break;
}
}
return isRunning;
}
/*
* 根据电话号码取得联系人姓名
*/
public static String getContactNameByPhoneNumber(Context context,
String PhoneNum) {
String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = null;
String name = null;
// 将自己添加到 msPeers 中
try {
cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
+ PhoneNum + "'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if (cursor != null) {
if (cursor.moveToFirst()) {
// 取得联系人名字
int nameFieldColumnIndex = cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
name = cursor.getString(nameFieldColumnIndex);
}
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return name;
}
}
package com.maile.jingcai.util.preferences;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public class DefaultConfigPreference {
}
package com.maile.jingcai.util.preferences;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public class IPreferencesIds {
// 文件名
public static final String DEFAULT_SHAREPREFERENCES_FILE = "default_cfg";
// KEY
public static final String IS_LOGIN = "is_login";
}
package com.maile.jingcai.util.preferences;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import java.util.Map;
import java.util.Set;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public final class PreferencesManager {
private SharedPreferences mPreferences;
private SharedPreferences.Editor mEditor;
private PreferencesManager() {
}
/**
* 获取默认的sp文件default_cfg.xml,默认模式为${@link Context#MODE_PRIVATE}
*
* @param context
* @return
*/
public static PreferencesManager getDefaultSharedPreference(Context context) {
return getSharedPreference(context,
IPreferencesIds.DEFAULT_SHAREPREFERENCES_FILE,
Context.MODE_PRIVATE);
}
/**
* 获取sp
*
* @param context
* @param name
* 文件名称
* @param mode
* 模式
* @return
*/
public static PreferencesManager getSharedPreference(Context context,
String name, int mode) {
if (context != null) {
try {
PreferencesManager preferencesManager = new PreferencesManager();
preferencesManager.mPreferences = context.getSharedPreferences(
name, mode);
preferencesManager.mEditor = preferencesManager.mPreferences
.edit();
return preferencesManager;
} catch (Exception e) {
// CSH-TODO send error report
}
}
return null;
}
/**
* 清除数据
*/
public void clear() {
if (mEditor != null) {
mEditor.clear().commit();
} else if (mPreferences != null) {
mEditor = mPreferences.edit();
mEditor.clear().commit();
}
}
public void remove(String key) {
mPreferences.edit().remove(key).commit();
}
public Map<String, ?> getAll() {
return mPreferences.getAll();
}
public boolean contains(String key) {
if (mPreferences == null || key == null) {
return false;
}
return mPreferences.contains(key);
}
public boolean getBoolean(String key, boolean defValue) {
if (mPreferences != null) {
return mPreferences.getBoolean(key, defValue);
}
return defValue;
}
public float getFloat(String key, float defValue) {
if (mPreferences != null) {
return mPreferences.getFloat(key, defValue);
}
return defValue;
}
public int getInt(String key, int defValue) {
if (mPreferences != null) {
return mPreferences.getInt(key, defValue);
}
return defValue;
}
public long getLong(String key, long defValue) {
if (mPreferences != null) {
return mPreferences.getLong(key, defValue);
}
return defValue;
}
public String getString(String key, String defValue) {
if (mPreferences != null) {
return mPreferences.getString(key, defValue);
}
return defValue;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public Set<String> getStringSet(String key, Set<String> defValues) {
if (mPreferences != null) {
return mPreferences.getStringSet(key, defValues);
}
return defValues;
}
public void registerOnSharedPreferenceChangeListener(
SharedPreferences.OnSharedPreferenceChangeListener listener) {
mPreferences.registerOnSharedPreferenceChangeListener(listener);
}
public void unregisterOnSharedPreferenceChangeListener(
SharedPreferences.OnSharedPreferenceChangeListener listener) {
mPreferences.unregisterOnSharedPreferenceChangeListener(listener);
}
public void putBoolean(String key, boolean b) {
if (mEditor != null) {
mEditor.putBoolean(key, b);
}
}
public void putInt(String key, int i) {
if (mEditor != null) {
mEditor.putInt(key, i);
}
}
public void putFloat(String key, float f) {
if (mEditor != null) {
mEditor.putFloat(key, f);
}
}
public void putLong(String key, long l) {
if (mEditor != null) {
mEditor.putLong(key, l);
}
}
public void putString(String key, String s) {
if (mEditor != null) {
mEditor.putString(key, s);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void putStringSet(String key, Set<String> values) {
if (mEditor != null) {
mEditor.putStringSet(key, values);
}
}
@SuppressLint("CommitPrefEdits")
public void edit() {
if (mEditor == null && mPreferences != null) {
mEditor = mPreferences.edit();
}
}
}
package com.maile.jingcai.view.activity;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.maile.jingcai.R;
import com.maile.jingcai.util.DrawUtil;
import com.maile.jingcai.util.preferences.IPreferencesIds;
import com.maile.jingcai.util.preferences.PreferencesManager;
import com.maile.jingcai.view.iview.ILoginView;
import com.maile.jingcai.view.layer.LoginMainLayer;
import com.maile.jingcai.view.layer.PhoneLayer;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class LoginActivity extends Activity implements ILoginView {
private final int DURATION_ANIM_OUT_START = 400;
private final int DURATION_ANIM_IN_LOGIN = 400;
private final int HANDLER_MAG_HIDE_ERRORBAR = 1;
private final int DURATION_ANIM_ERROR = 300;
@InjectView(R.id.main_layer)
LoginMainLayer mainLayer;
@InjectView(R.id.phoneLayer)
PhoneLayer phoneLayer;
@InjectView(R.id.error_tv)
TextView mErrorTextView;
@InjectView(R.id.error_bar)
LinearLayout mErrorBar;
@InjectView(R.id.iv_loading)
ProgressBar ivLoading;
@InjectView(R.id.rl_loading_layout)
RelativeLayout mLoading;
@InjectView(R.id.activity_home)
RelativeLayout activityHome;
private boolean mErrorVisible;
private int mErrorCurrentTop;
private int mErrorHideTop;
private ValueAnimator mErrorAnim;
private boolean mHasDestory;
private static Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设置全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
ButterKnife.inject(this);
init();
startAnimToLogin();
}
private void init() {
ButterKnife.inject(this);
mContext = this;
phoneLayer.setLoginView(this);
mainLayer.setIoginView(this, this);
mErrorHideTop = -DrawUtil.dip2px(60);
mErrorCurrentTop = mErrorHideTop;
mHasDestory = false;
}
/**
* 启动页
*/
private void startAnimToLogin() {
AlphaAnimation alphaAnimIn = new AlphaAnimation(0, 1);
alphaAnimIn.setDuration(DURATION_ANIM_IN_LOGIN);
alphaAnimIn.setFillAfter(true);
mainLayer.startAnimation(alphaAnimIn);
alphaAnimIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
checkUserIsLogin();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
@Override
protected void onResume() {
super.onResume();
if (mainLayer != null) {
mainLayer.onResume();
}
}
//检测用户是否登录
private void checkUserIsLogin() {
PreferencesManager preferencesManager = PreferencesManager.getSharedPreference(getApplication(),
IPreferencesIds.DEFAULT_SHAREPREFERENCES_FILE,
Context.MODE_PRIVATE);
boolean isLogin = preferencesManager.getBoolean(IPreferencesIds.IS_LOGIN, false);
if (isLogin) {
onStartMainActivity();
} else {
//开启动画:显示登录入口
mainLayer.startAnimToLogin();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mHasDestory = true;
mContext = null;
ButterKnife.reset(this);
}
@Override
public void onEnterPhoneLayer() {
phoneLayer.onEnterPhoneLayer();
}
@Override
public void onStartMainActivity() {
startEntranceActivity(this);
}
public static void startEntranceActivity(Context context) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
if (mContext != null) {
((Activity) mContext).finish();
}
}
@Override
public void onUpdateErrorBar(boolean visiable, int errorResId) {
if (visiable) {
showErrorBar(errorResId);
} else {
hideErrorBar();
}
}
@Override
public void onShowLoadingView(boolean visiable) {
mLoading.setVisibility(visiable ? View.VISIBLE : View.INVISIBLE);
}
@Override
public void onUpdateErrorBar(boolean visiable, String error) {
if (visiable) {
showErrorBar(error);
} else {
hideErrorBar();
}
}
private void showErrorBar(int errorResId) {
mErrorTextView.setText(errorResId);
startErrorAnim(true);
}
private void showErrorBar(String error) {
mErrorTextView.setText(error);
startErrorAnim(true);
}
private void hideErrorBar() {
startErrorAnim(false);
}
@Override
public void onBackPressed() {
if (phoneLayer.onBackPressed()) {
return;
}
super.onBackPressed();
myHandler.removeMessages(HANDLER_MAG_HIDE_ERRORBAR);
myHandler = null;
}
private void startErrorAnim(boolean isVisible) {
if (myHandler == null) {
return;
}
mErrorVisible = isVisible; //false
int start = mErrorCurrentTop;
int end = isVisible ? 0 : mErrorHideTop;
myHandler.removeMessages(HANDLER_MAG_HIDE_ERRORBAR);
if (start == end) {
if (isVisible) {
Message message = myHandler.obtainMessage(HANDLER_MAG_HIDE_ERRORBAR);
myHandler.sendMessageDelayed(message, 1000);
}
return;
}
if (mErrorAnim == null) {
mErrorAnim = ValueAnimator.ofInt(start, end);
mErrorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mErrorCurrentTop = (int) animation.getAnimatedValue();
((RelativeLayout.LayoutParams) mErrorBar.getLayoutParams()).topMargin = mErrorCurrentTop;
mErrorBar.requestLayout();
}
});
mErrorAnim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
mErrorCurrentTop = mErrorVisible ? 0 : mErrorHideTop;//-60
((RelativeLayout.LayoutParams) mErrorBar.getLayoutParams()).topMargin = mErrorCurrentTop;
mErrorBar.requestLayout();
if (mErrorVisible && myHandler != null) {
Message message = myHandler.obtainMessage(HANDLER_MAG_HIDE_ERRORBAR);
myHandler.sendMessageDelayed(message, 1000);
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
} else {
mErrorAnim.setIntValues(start, end);
}
mErrorAnim.setDuration((long) (Math.abs((end - start) * 1.0f / mErrorHideTop) * DURATION_ANIM_ERROR));
mErrorAnim.start();
}
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MAG_HIDE_ERRORBAR:
if (!mHasDestory) {
hideErrorBar();
}
break;
}
super.handleMessage(msg);
}
};
}
package com.maile.jingcai.view.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.maile.jingcai.R;
import butterknife.ButterKnife;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设置全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
}
package com.maile.jingcai.view.iview;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public interface ILoginView {
void onEnterPhoneLayer();
void onStartMainActivity();
void onUpdateErrorBar(boolean visiable, String error);
void onUpdateErrorBar(boolean visiable, int errorResId);
void onShowLoadingView(boolean visiable);
}
package com.maile.jingcai.view.layer;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.maile.jingcai.R;
import com.maile.jingcai.base.BaseApplication;
import com.maile.jingcai.base.Constant;
import com.maile.jingcai.commponent.LoginClickBtn;
import com.maile.jingcai.util.NetUtils;
import com.maile.jingcai.view.iview.ILoginView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public class LoginMainLayer extends RelativeLayout {
private final int DURATION_ANIM_OUT_START = 400;
private final int DURATION_ANIM_IN_LOGIN = 2800;
private Context mContext;
private boolean mWeixinLogining; // 是否微信登录中
@InjectView(R.id.iv_phone)
ImageView ivPhone;
@InjectView(R.id.tv_phone)
TextView tvPhone;
@InjectView(R.id.btn_login_phone)
LoginClickBtn btnLoginPhone;
@InjectView(R.id.iv_weixin)
ImageView ivWeixin;
@InjectView(R.id.tv_weixin)
TextView tvWeixin;
@InjectView(R.id.btn_login_weixin)
LoginClickBtn btnLoginWeixin;
@InjectView(R.id.ll_login_container)
LinearLayout llLoginContainer;
@InjectView(R.id.activity_home)
RelativeLayout activityHome;
private ILoginView iLoginView ;
private Activity parentActivity;
public LoginMainLayer(Context context) {
super(context);
init(context);
}
public LoginMainLayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LoginMainLayer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mContext = context;
mWeixinLogining = false;
View view = LayoutInflater.from(context).inflate(R.layout.layour_login_main, this);
ButterKnife.inject(view,this);
startAnimToLogin();
}
public void setIoginView (ILoginView view ,Activity activity){
this.iLoginView = view;
this.parentActivity = activity;
}
@OnClick(R.id.btn_login_phone)
public void onPhoneClick(){
clearAnimation();
Log.d("tangwen", "onPhoneClick: onPhoneClick");
iLoginView.onEnterPhoneLayer();
}
@OnClick(R.id.btn_login_weixin)
public void onWeixinClick(){
loginWeixin_();
}
void loginWeixin_(){
iLoginView.onShowLoadingView(true);
if (!checkNetworkOK()) {
return;
}
if (!BaseApplication.sApi.isWXAppInstalled()) {
iLoginView.onUpdateErrorBar(true, R.string.login_install_weixin);
iLoginView.onShowLoadingView(false);
return;
}
mWeixinLogining = true;
final SendAuth.Req req = new SendAuth.Req();
req.scope = Constant.WEIXIN_AUTH_LOGIN_INFO_SCOPE;
req.state = Constant.WEIXIN_AUTH_LOGIN_INFO_STATE;
BaseApplication.sApi.sendReq(req);
}
private boolean checkNetworkOK() {
if (!NetUtils.isNetworkOK(mContext)) { //网络未连接
iLoginView.onUpdateErrorBar(true, R.string.network_not_ok);
iLoginView.onShowLoadingView(false);
return false;
}
return true;
}
/**
* 启动页切换到登录页
*/
public void startAnimToLogin() {
llLoginContainer.setVisibility(VISIBLE);
AlphaAnimation alphaAnimIn = new AlphaAnimation(0, 1);
alphaAnimIn.setDuration(DURATION_ANIM_IN_LOGIN);
alphaAnimIn.setFillAfter(true);
llLoginContainer.startAnimation(alphaAnimIn);
alphaAnimIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void onResume() {
if (mWeixinLogining) {
mWeixinLogining = false;
if (iLoginView != null) {
iLoginView.onShowLoadingView(false);
}
}
}
}
package com.maile.jingcai.view.layer;
import android.content.Context;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.maile.jingcai.R;
import com.maile.jingcai.base.BaseApplication;
import com.maile.jingcai.broadcast.SmsReceiver;
import com.maile.jingcai.commponent.LoginClickTextView;
import com.maile.jingcai.module.User;
import com.maile.jingcai.module.WrapperRspEntity;
import com.maile.jingcai.module.api.LoginApiService;
import com.maile.jingcai.module.net.RetrofitManager;
import com.maile.jingcai.util.NetUtils;
import com.maile.jingcai.util.PublicUtils;
import com.maile.jingcai.util.UtilTool;
import com.maile.jingcai.view.iview.ILoginView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by chengfeng-piaopiao on 2017/11/8.
*/
public class PhoneLayer extends RelativeLayout implements View.OnFocusChangeListener , SmsReceiver.SmsReceiverCallback{
private final int VIEW_TYPE_MAIN_LOGIN = 0;
private static final int VIEW_TYPE_PHONE_LOGIN = 1;
@InjectView(R.id.etv_login_phone)
EditText mInputPhone;
@InjectView(R.id.input_phone_layout)
LinearLayout inputPhoneLayout;
@InjectView(R.id.etv_login_checkcode)
EditText mInputCheckcode;
@InjectView(R.id.tv_checkcode_send)
LoginClickTextView mSendCheckCodeView;
@InjectView(R.id.input_checkcode_layout)
LinearLayout inputCheckcodeLayout;
@InjectView(R.id.btn_login_phone)
LoginClickTextView btnLoginPhone;
@InjectView(R.id.ll_phone_container)
LinearLayout ll_phone_container;
private boolean mAniming;
private final int DURATION_ANIM_IN = 500;
private final int DURATION_ANIM_OUT = 300;
private final int DURATION_ANIM_TRAN = 300;
private TranslateAnimation mTranIn;
private TranslateAnimation mTranOut;
private AnimationSet mAnimIn;
private AnimationSet mAnimOut;
private int mCurrentViewType;//
private ILoginView mLoginView;
private boolean mIsSendingCheckCode;
private SmsReceiver mSmsReceiver;
private MyCountDownTimer mCountDownTimer;
public PhoneLayer(Context context) {
super(context);
init(context);
}
public PhoneLayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public PhoneLayer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.layer_login_phone, this);
ButterKnife.inject(view, this);
initAnimation();
initListener();
mIsSendingCheckCode = false;
}
@OnClick(R.id.ll_phone_container)
public void clearFocus(){
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); //强制隐藏键盘
imm.hideSoftInputFromWindow(ll_phone_container.getWindowToken(), 0);
}
@OnClick(R.id.btn_login_phone)
public void login(){
String phoneNumber = PublicUtils.removeAllSpace(mInputPhone.getText().toString().trim());
String code = PublicUtils.removeAllSpace( mInputCheckcode.getText().toString().trim());
if(checkIsValid(phoneNumber,code)){
mLoginView.onShowLoadingView(true);
hideError();
RetrofitManager.getInstance().createReq(LoginApiService.class).loginPhone(phoneNumber,code).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<WrapperRspEntity<String>>() {
@Override
public void onCompleted() {
mLoginView.onShowLoadingView(false);
hideError();
}
@Override
public void onError(Throwable e) {
showError(e.getMessage());
mLoginView.onShowLoadingView(false);
}
@Override
public void onNext(WrapperRspEntity<String> userWrapperRspEntity) {
mLoginView.onStartMainActivity();
}
});
}
}
public boolean checkIsValid(String phoneNumber,String code) {
//判断号码是否合格,密码是否合格
if (phoneNumber == null || phoneNumber.equals("")) {
showError(R.string.user_error_please_input_right_phone);
return false;
} else if (!UtilTool.isLegalPhoneNumber(phoneNumber)) {
showError(R.string.user_error_please_input_right_phone);
return false;
} else if (phoneNumber.length() < 11) {
showError(R.string.user_error_please_input_right_phone);
return false;
} else {
if (code == null || code.equals("")) {
showError(R.string.user_error_input_code);
return false;
} else if (!NetUtils.isNetworkOK(getContext())) { //网络未连接
showError(R.string.network_not_ok);
return false;
}
}
return true;
}
private void initListener() {
mInputPhone.addTextChangedListener(new TextWatcher() {
int beforeLen = 0;
int afterLen = 0;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
beforeLen = s.length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String txt = mInputPhone.getText().toString();
afterLen = txt.length();
if (afterLen > beforeLen) {
if (txt.length() == 4 || txt.length() == 9) {
mInputPhone.setText(new StringBuffer(txt).insert(txt.length() - 1, " ").toString());
mInputPhone.setSelection(mInputPhone.getText().length());
}
} else {
if (txt.startsWith(" ")) {
mInputPhone.setText(new StringBuffer(txt).delete(afterLen - 1, afterLen).toString());
mInputPhone.setSelection(mInputPhone.getText().length());
}
}
if (afterLen >= 13) {
mInputPhone.clearFocus();
mInputCheckcode.setFocusable(true);
mInputCheckcode.setFocusableInTouchMode(true);
mInputCheckcode.requestFocus();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
ButterKnife.reset(this);
mLoginView = null;
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
if (mSmsReceiver != null) {
mSmsReceiver.destory();
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
String hint;
if (v.getId() == R.id.etv_login_phone) {
if (hasFocus) {
hint = mInputPhone.getHint().toString();
mInputPhone.setTag(hint);
mInputPhone.setHint("");
} else {
hint = mInputPhone.getTag().toString();
mInputPhone.setHint(hint);
}
} else if (v.getId() == R.id.etv_login_checkcode) {
if (hasFocus) {
hint = mInputCheckcode.getHint().toString();
mInputCheckcode.setTag(hint);
mInputCheckcode.setHint("");
} else {
hint = mInputCheckcode.getTag().toString();
mInputCheckcode.setHint(hint);
}
} else if (v.getId() == R.id.etv_login_phone) {
if (hasFocus) {
hint = mInputPhone.getHint().toString();
mInputPhone.setTag(hint);
mInputPhone.setHint("");
} else {
hint = mInputPhone.getTag().toString();
mInputPhone.setHint(hint);
}
}
}
public void setLoginView(ILoginView view) {
this.mLoginView = view;
}
@OnClick(R.id.tv_checkcode_send)
void OnGetCode() {
//判断号码是否合格,密码是否合格
String phoneNumber = PublicUtils.removeAllSpace(mInputPhone.getText().toString().trim());
hideError();
if (phoneNumber == null || phoneNumber.equals("")) {
showError(R.string.user_error_please_input_right_phone);
return;
} else if (!UtilTool.isLegalPhoneNumber(phoneNumber)) {
showError(R.string.user_error_please_input_right_phone);
return;
} else if (phoneNumber.length() < 11) {
showError(R.string.user_error_please_input_right_phone);
return;
} else if (!NetUtils.isNetworkOK(getContext())) { //网络未连接
showError(R.string.network_not_ok);
return;
} else if (!mIsSendingCheckCode) {
if (mSmsReceiver == null) {
mSmsReceiver = new SmsReceiver(this, getContext());
}
if (mCountDownTimer == null) {
mCountDownTimer = new MyCountDownTimer(60000, 1000);
}
mCountDownTimer.start();
mSendCheckCodeView.setBackgroundResource(R.drawable.input_send_checkcode_bg_lock);
mSendCheckCodeView.disallowTouch(true);
mIsSendingCheckCode = true;
RetrofitManager.getInstance().createReq(LoginApiService.class).getMessageFormALi(phoneNumber).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<WrapperRspEntity<String>>() {
@Override
public void onCompleted() {
hideError();
}
@Override
public void onError(Throwable e) {
Log.i("tangwen", "onError: "+ e.getMessage());
showError(e.getMessage());
//com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was 服务端定义的数据格式和客户端不一致
//class java.net.ConnectException
}
@Override
public void onNext(WrapperRspEntity<String> userWrapperRspEntity) {
Log.i("tangwen", "onNext: " + userWrapperRspEntity.toString());
}
});
}
}
private void hideError() {
if ( mLoginView != null) {
mLoginView.onUpdateErrorBar(false, "");
}
}
private void showError(int errorResId) {
if (mLoginView != null) {
mLoginView.onUpdateErrorBar(true, errorResId);
}
}
private void showError(String error) {
if (mLoginView != null) {
mLoginView.onUpdateErrorBar(true, error);
}
}
class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
mSendCheckCodeView.setText(String.format(BaseApplication.getAppContext().getResources().getString(R.string.login_input_checkcode_clock),
millisUntilFinished / 1000));
}
@Override
public void onFinish() {
mSendCheckCodeView.setBackgroundResource(R.drawable.input_send_checkcode_bg);
mSendCheckCodeView.disallowTouch(false);
mSendCheckCodeView.setText(BaseApplication.getAppContext().getResources().getString(R.string.login_input_checkcode_send));
mIsSendingCheckCode = false;
}
}
private void initAnimation() {
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
mAnimIn = new AnimationSet(true);
ScaleAnimation scaleAnim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnim.setDuration(DURATION_ANIM_IN);
mAnimIn.addAnimation(scaleAnim);
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(DURATION_ANIM_IN);
mAnimIn.addAnimation(alphaAnimation);
mAnimIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAniming = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAniming = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mAnimOut = new AnimationSet(true);
scaleAnim = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnim.setDuration(DURATION_ANIM_OUT);
mAnimOut.addAnimation(scaleAnim);
alphaAnimation = new AlphaAnimation(1, 0);
alphaAnimation.setDuration(DURATION_ANIM_OUT);
mAnimOut.addAnimation(alphaAnimation);
mAnimOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mTranIn = new TranslateAnimation(metrics.widthPixels, 0, 0, 0);
mTranIn.setDuration(DURATION_ANIM_TRAN);
mTranIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
setVisibility(VISIBLE);
mAniming = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAniming = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mTranOut = new TranslateAnimation(0, metrics.widthPixels, 0, 0);
mTranOut.setDuration(DURATION_ANIM_TRAN);
mTranOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAniming = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAniming = false;
setVisibility(INVISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void onEnterPhoneLayer() {
if (mAniming) {
return;
}
startAnimation(mTranIn);
mCurrentViewType = VIEW_TYPE_PHONE_LOGIN;
}
public boolean onBackPressed() {
switch (mCurrentViewType) {
case VIEW_TYPE_PHONE_LOGIN:
onPhoneLoginBack();
return true;
}
return false;
}
private void onPhoneLoginBack() {
if (mAniming) {
return;
}
mCurrentViewType = VIEW_TYPE_MAIN_LOGIN;
startAnimation(mTranOut);
}
//信息监听回调
@Override
public void onCallback(String code) {
mInputCheckcode.setText(code);
}
}
package com.maile.jingcai.wxapi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.maile.jingcai.R;
import com.maile.jingcai.base.Constant;
import com.maile.jingcai.module.WrapperRspEntity;
import com.maile.jingcai.module.api.LoginApiService;
import com.maile.jingcai.module.net.RetrofitManager;
import com.maile.jingcai.util.PublicUtils;
import com.maile.jingcai.view.activity.LoginActivity;
import com.maile.jingcai.view.activity.MainActivity;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.HttpStatus;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* zz
* 一定是包名目录下新建,不要在其他目录新建,否则WXEntryActivity.java里的public void onResp(BaseResp resp)方法不会被调用
* 请求成功后,可拉起微信的授权登录页面,如下。用户点击“确认登录”后,SDK通过SendAuth的Resp返回数据给调用方(即app),
* 此时WXEntryActivity中的public void onResp(BaseResp resp)方法被调用(微信、朋友圈分享成功后,此方法同样会被调用),
*/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI sApi;
// 获取第一步的code后,请求以下链接获取access_token
public static String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
//获取用户个人信息
public static String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
private static String get_access_token = "";
private String mCode;
private String mAccessToken;
private String mOpenId;
private Context mContext;
RelativeLayout mLoading;
boolean mIsDestroy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wxentry);
mContext = this;
mIsDestroy = false;
mLoading = (RelativeLayout) findViewById(R.id.rl_loading_layout);
Log.i("tangwen", "WXEntryActivity onCreate");
sApi = WXAPIFactory.createWXAPI(this, Constant.WEIXIN_APP_ID, false);
sApi.handleIntent(getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
sApi.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
Log.i("tangwen", "<WXEntryActivity> access_token onReq= ");
}
@Override
public void onResp(BaseResp baseResp) {
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK: //用户同意
if (baseResp.getType() == ConstantsAPI.COMMAND_SENDAUTH) { //登录授权
mCode = ((SendAuth.Resp) baseResp).code;
get_access_token = getCodeRequest(((SendAuth.Resp) baseResp).code);
// Log.i("zou", "WXEntryActivity mCode= " + mCode + " get_access_token= " + get_access_token);
Thread thread = new Thread(downloadRun);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else { //TODO:分享成功
PublicUtils.showToast("分享成功");
// this.finish();
}
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
Log.i("zou", "<ERR_USER_CANCEL> ");
// this.finish();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
break;
default:
break;
}
}
/**
* 获取access_token的URL(微信)
*
* @param code 授权时,微信回调给的
* @return URL
*/
public static String getCodeRequest(String code) {
String result;
GetCodeRequest = GetCodeRequest.replace("APPID",
urlEnodeUTF8(Constant.WEIXIN_APP_ID));
GetCodeRequest = GetCodeRequest.replace("SECRET",
urlEnodeUTF8(Constant.WEIXIN_APP_SECRET));
GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
result = GetCodeRequest;
return result;
}
/**
* 获取用户个人信息的URL(微信)
*
* @param access_token 获取access_token时给的
* @param openid 获取access_token时给的
* @return URL
*/
public static String getUserInfo(String access_token, String openid) {
String result;
GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN",
urlEnodeUTF8(access_token));
GetUserInfo = GetUserInfo.replace("OPENID",
urlEnodeUTF8(openid));
result = GetUserInfo;
return result;
}
public static String urlEnodeUTF8(String str) {
String result = str;
try {
result = URLEncoder.encode(str, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Runnable downloadRun = new Runnable() {
@Override
public void run() {
String str = WXGetAccessToken();
if (str != null) {
Message message = mHandler.obtainMessage();
message.what = 1;
message.obj = str;
mHandler.sendMessage(message);
}
}
};
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO 接收消息并且去更新UI线程上的控件内容
if (msg.what == 1) {
PublicUtils.showToast(String.valueOf(msg.obj));
}
super.handleMessage(msg);
}
};
/**
* 获取access_token等等的信息(微信)
*/
private String WXGetAccessToken() {
HttpClient get_access_token_httpClient = new DefaultHttpClient();
try {
HttpPost postMethod = new HttpPost(get_access_token);
HttpResponse response = get_access_token_httpClient.execute(postMethod); // 执行POST方法
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String str = "";
StringBuffer sb = new StringBuffer();
while ((str = br.readLine()) != null) {
sb.append(str);
}
is.close();
String josn = sb.toString();
JSONObject json1 = new JSONObject(josn);
mAccessToken = (String) json1.opt("access_token");
mOpenId = (String) json1.opt("openid");
Log.i("tangwen", "<WXEntryActivity> openid= " + mOpenId + " mAccessToken = " + mAccessToken);
if (mAccessToken == null || mAccessToken.equals("")) {
this.finish();
return "微信登录失败";
}
String get_user_info_url = getUserInfo(mAccessToken, mOpenId);
WXGetUserInfo(get_user_info_url);
} else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// String get_user_info_url = getUserInfo(mAccessToken, openid);
// WXGetUserInfo(get_user_info_url);
return null;
}
/**
* 获取微信用户个人信息
*
* @param get_user_info_url 调用URL
*/
private void WXGetUserInfo(String get_user_info_url) {
HttpClient get_access_token_httpClient = new DefaultHttpClient();
String openid = "";
String nickname = "";
String headimgurl = "";
String channel = "android";;
String accounType = "weixin";
try {
HttpGet getMethod = new HttpGet(get_user_info_url);
HttpResponse response = get_access_token_httpClient.execute(getMethod); // 执行GET方法
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String str = "";
StringBuffer sb = new StringBuffer();
while ((str = br.readLine()) != null) {
sb.append(str);
}
is.close();
String josn = sb.toString();
JSONObject json1 = new JSONObject(josn);
//{"openid":"o52lCv6Bt9fS7lvQteww1CcRUmHU","nickname":"Melles","sex":1,"language":"zh_CN","city":"Liverpool","province":"England","country":"GB","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/vi_32\/Q0j4TwGTfTLW2kf2ddpsD62zicIQVteQviaxNuVTW6wWr5zNyz6IM7Ch1ror9hibPYyqdj3zht6hEqMt8d3x3f9GA\/0","privilege":[],"unionid":"oUBfOwGVmmqaO8wCG89xtRh6prnU"}
openid = (String) json1.opt("openid");
nickname = (String) json1.opt("nickname");
headimgurl = (String) json1.opt("headimgurl");
//请求服务器传第三方的数据
Log.i("tangwen", "<WXEntryActivity> openid= " + openid +
" nickname= " + nickname + " headimgurl= " + headimgurl + " mCode =" + mCode + " mAccessToken = " + mAccessToken);
LoginActivity.startEntranceActivity(mContext);
RetrofitManager.getInstance().createReq(LoginApiService.class).thirdLogin(channel,openid,accounType,headimgurl,nickname).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<WrapperRspEntity<String>>() {
@Override
public void onCompleted() {
Log.d("tangwen", "onCompleted: ");
}
@Override
public void onError(Throwable errorException) {
Log.d("tangwen", "onError: " + errorException.getMessage());
if (errorException == null) {
PublicUtils.showToast(getString(R.string.error_server_not_ok));
} else if (errorException instanceof java.net.ConnectException) {
PublicUtils.showToast(errorException.getMessage());
} else if (errorException.equals("com.android.volley.TimeoutError")) {
PublicUtils.showToast(getString(R.string.error_server_timeout_error));
} else {
PublicUtils.showToast(getString(R.string.error_server_not_ok));
}
}
@Override
public void onNext(WrapperRspEntity<String> userWrapperRspEntity) {
Log.d("tangwen", "onCompleted: " + userWrapperRspEntity.toString());
if (mIsDestroy) {
return;
}
mLoading.setVisibility(View.GONE);
runOnUiThread(new Runnable() {
@Override
public void run() {
// LoginActivity.startEntranceActivity(mContext);
}
});
}
});
} else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("zou", "<onDestroy> ");
mIsDestroy = true;
// PublicUtils.showToast("注意:这里是测试 WXEntryActivity onDestroy");
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp" />
<solid android:color="#b1db49" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp" />
<solid android:color="#e1e1e1" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/loading"
android:pivotX="50%"
android:pivotY="50%" />
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="8dp" />
<solid android:color="#ffffff" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp" />
<solid android:color="#f3d800" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp" />
<solid android:color="#26000000" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp" />
<stroke
android:width="1dp"
android:color="#e8e8e9" />
<solid android:color="#00FFFFFF" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="25dp" />
<solid android:color="#FFA54F" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_home"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.maile.jingcai.view.layer.LoginMainLayer
android:id="@+id/main_layer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.maile.jingcai.view.layer.PhoneLayer
android:id="@+id/phoneLayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"/>
<LinearLayout
android:id="@+id/error_bar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal"
android:background="#99000000"
android:gravity="center"
android:layout_marginTop="-60dp"
>
<ImageView
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_marginLeft="21dp"
android:layout_marginRight="8dp"
android:src="@drawable/login_error_img"
/>
<TextView
android:id="@+id/error_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#ffffff"
android:textSize="20sp"
/>
</LinearLayout>
<include
layout="@layout/layout_loading"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".view.activity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.chaodong.hongyan.android.wxapi.WXEntryActivity">
<include
layout="@layout/layout_loading"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_phone_container"
android:orientation="vertical"
android:gravity="center"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:background="#ffffff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/input_phone_layout"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_marginTop="66dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="@drawable/login_input_bg"
>
<ImageView
android:layout_width="18dp"
android:layout_height="26dp"
android:src="@drawable/input_phone"
android:layout_marginLeft="17dp"
/>
<EditText
android:id="@+id/etv_login_phone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:digits="0123456789"
android:gravity="center_vertical"
android:hint="@string/login_input_phone_hint"
android:inputType="phone"
android:maxLength="13"
android:singleLine="true"
android:textColor="#cc222222"
android:textColorHint="#cacaca"
android:textCursorDrawable="@null"
android:layout_marginLeft="16dp"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/input_checkcode_layout"
android:layout_width="match_parent"
android:layout_height="46dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_below="@+id/input_password_layout"
android:layout_marginTop="13dp"
android:background="@drawable/login_input_bg"
>
<ImageView
android:layout_width="28dp"
android:layout_height="23dp"
android:src="@drawable/input_checkcode"
android:layout_marginLeft="17dp"
/>
<EditText
android:id="@+id/etv_login_checkcode"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:gravity="center_vertical"
android:hint="@string/login_input_checkcode_hint"
android:maxLength="20"
android:singleLine="true"
android:textColor="#cc222222"
android:textColorHint="#cacaca"
android:digits="0123456789"
android:textCursorDrawable="@null"
android:layout_marginLeft="7dp"
android:textSize="17sp" />
<com.maile.jingcai.commponent.LoginClickTextView
android:id="@+id/tv_checkcode_send"
android:layout_width="122dp"
android:layout_height="match_parent"
android:text="@string/login_input_checkcode_send"
android:background="@drawable/input_send_checkcode_bg"
android:gravity="center"
android:textSize="17sp"
android:textColor="#ffffff"
/>
</LinearLayout>
<com.maile.jingcai.commponent.LoginClickTextView
android:id="@+id/btn_login_phone"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/login_btn"
android:layout_below="@+id/login_input_view"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:text="@string/login"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="18sp"
android:layout_marginTop="64dp"
/>
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/start_logo">
<LinearLayout
android:id="@+id/ll_login_container"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="35dp"
android:layout_marginTop="19dp"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:visibility="invisible"
android:layout_marginBottom="60dp">
<com.maile.jingcai.commponent.LoginClickBtn
android:id="@+id/btn_login_phone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/login_qq_btn"
android:gravity="center">
<ImageView
android:id="@+id/iv_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/start_phone"
android:layout_marginRight="7dp"
/>
<TextView
android:id="@+id/tv_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#000000"
android:text="@string/login_phone"
android:gravity="center"
/>
</com.maile.jingcai.commponent.LoginClickBtn>
<com.maile.jingcai.commponent.LoginClickBtn
android:id="@+id/btn_login_weixin"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginLeft="25dp"
android:background="@drawable/login_qq_btn"
android:gravity="center">
<ImageView
android:id="@+id/iv_weixin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/start_weixin"
android:layout_marginRight="7dp"/>
<TextView
android:id="@+id/tv_weixin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#000000"
android:text="@string/login_weixin"
android:gravity="center" />
</com.maile.jingcai.commponent.LoginClickBtn>
</LinearLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_loading_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80000000"
android:clickable="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<RelativeLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="@drawable/loading_bg"
>
<ProgressBar
android:id="@+id/iv_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminateBehavior="repeat"
android:indeterminateDrawable="@drawable/loading_animated"
android:indeterminateOnly="true" />
</RelativeLayout>
</RelativeLayout>
\ No newline at end of file
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
<resources>
<string name="app_name">DuoBaoJingCai</string>
<string name="login_phone">手机登录</string>
<string name="login_weixin">微信登录</string>
<string name="login_input_password_hint">密码</string>
<string name="login_input_phone_hint">手机号</string>
<string name="login_input_checkcode_hint">验证码</string>
<string name="login_input_checkcode_send">发送验证码</string>
<string name="login">登录</string>
<string name="user_error_please_input_right_phone">请输入正确的手机号码</string>
<string name="network_not_ok">网络未连接</string>
<string name="login_input_checkcode_clock">重发(%1$ss)</string>
<string name="login_install_weixin">请先安装微信</string>
<string name="error_server_not_ok">服务器开小差了</string>
<string name="error_server_timeout_error">请求超时</string>
<string name="user_error_input_code">请输入验证码</string>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
package com.maile.jingcai;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
//dependencies 项目以来
ButterKnife = "6.1.0"
Retrofit = "2.0.2"
loggingInterceptor = "3.2.0"
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
include ':app'
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 sign in to comment