基于Bmob云的同城健身
第一阶段:(1)
写在准备前:
(一)、开始想写博客时我的项目已经写了一部分,也是对以前写的部分代码的总结。
(二)、本系列博客将会将代码的各个模块、View、基类以及一般的第三方框架的使用,使用Android Studio的开发环境。
(三)、写这个项目也是对以往项目的一次回顾以及养成自己写代码的习惯。
(四)、项目中有大量参照网上的代码,在本项目中保证绝对可用,在项目后期将会采用谷歌官方最新提供的Material Design的设计风格,也会在后面用到的时候讲解。
(五)、对使用别人代码的同行说声感谢,和使用第三方软件的接口,如果发现侵权,请联系我删除,谢谢(longshihan@163.com)
前言:
项目比较丑,希望大家可以谅解。在编写代码前先行准备的软件:Android studio,github,美图秀秀(PhotoShop),夜神虚拟机(genymotion最好),安卓版Packet Capture(无需Root)。
前言最后说一句:在《STL源码刨析》中有这样一句:源码之前 了无秘密。
与诸君共勉。
———————–可爱的分割线————————————
下面开始正文:
首先先着手搭软件的框架,像继承Application的类、Activity的基类、Utils的工具类都在先前做软件的UML和准备时做好。(PS:刚开始我也没想这么多,就做了,前期 都是各自为营)
(1)、首先是App继承Apptlication,这个类将会在软件的启动时就开始首先运行,所以我们将每次都需要实例化的东西放在这里,比如第三方平台的初始化Key和Activity的集合,Application的单例模式和本项目使用Volley的初始化。
```public class App extends Application {
private static App _instance;
public static Context applicationContext;
private static App application;
/*
* 初始化TAG
* */
private static String TAG = App.class.getName();
/*Activity堆*/
private Stack<AppCompatActivity> activityStack = new Stack<AppCompatActivity>();
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
initConfig(getApplicationContext());
_instance = this;
applicationContext=this;
queues= Volley.newRequestQueue(getApplicationContext());
// 初始化 Bmob SDK
Bmob.initialize(getApplicationContext(), Constans.Bmob_APPID);
//初始化sharedSDK的短信SDK
SMSSDK.initSDK(this, Constans.Mob_SMS_ID, Constans.MOb_SMS_SCRECT);
SharePreferenceUtils.init(this);
printAppParameter();
}
//。。。。下面是Activity的集合,参考我的github。
(2)BaseActivity继承AppCompatActivity,主要处理权限管理,网络管理,Log和Toast,和软键盘的问题,比较容易扩展。
public abstract class BaseActivity extends AppCompatActivity {
private static final int ACTIVITY_RESUME = 0;
private static final int ACTIVITY_PAUSE = 2;
InputMethodManager _inputMethodManager;
protected Resources res;
protected App baseApp;
protected static final String TAG = BaseFragment.class.getName();
protected Toast mToast;
public int activityState;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.WRITE_CONTACTS
, Manifest.permission.GET_ACCOUNTS
, Manifest.permission.READ_CONTACTS
, Manifest.permission.READ_CALL_LOG
, Manifest.permission.READ_PHONE_STATE
, Manifest.permission.CALL_PHONE
, Manifest.permission.WRITE_CALL_LOG
, Manifest.permission.USE_SIP
, Manifest.permission.PROCESS_OUTGOING_CALLS
, Manifest.permission.ADD_VOICEMAIL
, Manifest.permission.READ_CALENDAR
, Manifest.permission.WRITE_CALENDAR
, Manifest.permission.CAMERA
, Manifest.permission.CAMERA
, Manifest.permission.BODY_SENSORS
, Manifest.permission.ACCESS_FINE_LOCATION
, Manifest.permission.ACCESS_COARSE_LOCATION
, Manifest.permission.READ_EXTERNAL_STORAGE
, Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.RECORD_AUDIO
, Manifest.permission.READ_SMS
, Manifest.permission.RECEIVE_WAP_PUSH
, Manifest.permission.RECEIVE_MMS
, Manifest.permission.RECEIVE_SMS
, Manifest.permission.SEND_SMS
};
public abstract void initView();
public abstract void initData();
public abstract void initListener();
protected abstract int getLayout();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
res = this.getApplicationContext().getResources();
baseApp = (App) this.getApplication();
_inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏锁定
verifyStoragePermissions(this);
ButterKnife.inject(this);
initView();
initData();
initListener();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
activityState = ACTIVITY_RESUME;
}
@Override
protected void onPause() {
super.onPause();
activityState = ACTIVITY_PAUSE;
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onDestroy() {
super.onDestroy();
baseApp.removeActivity(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (getCurrentFocus() != null
&& getCurrentFocus().getWindowToken() != null) {
_inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return super.onTouchEvent(event);
}
//网络错误种类
protected int getNetworkErrorTip(int code) {
Log.d(TAG, "getNetworkErrorTip - code = \"" + code + "\"");
int textResId = R.string.error_network_time_out;
switch (code) {
case RespHandleListener.ErrCode.ERR_NETWORK_NOT_AVAILABLE:
textResId = R.string.error_network_not_available;
break;
case RespHandleListener.ErrCode.ERR_SERVER_ERROR:
textResId = R.string.error_network_server_busy;
break;
case RespHandleListener.ErrCode.ERR_TIME_OUT:
case RespHandleListener.ErrCode.ERR_CLIENT_ERROR:
case RespHandleListener.ErrCode.ERR_UNKNOWN_ERROR:
break;
default:
break;
}
Log.d(TAG, "getNetworkErrorTip - textResId = \"" + textResId + "\"");
return textResId;
}
public static void verifyStoragePermissions(AppCompatActivity activity) {
// Check if we have write permission
//访问媒体文件的权限
int WRITE_EXTERNAL_STORAGE = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (WRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
// 我们没有权限,以提示用户
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}
public void showToast(String text) {
if (!TextUtils.isEmpty(text)) {
if (mToast == null) {
mToast = Toast.makeText(getApplicationContext(), text,
Toast.LENGTH_SHORT);
} else {
mToast.setText(text);
}
mToast.show();
}
}
public void showToast(int resId) {
if (mToast == null) {
mToast = Toast.makeText(getApplicationContext(), resId,
Toast.LENGTH_SHORT);
} else {
mToast.setText(resId);
}
mToast.show();
}
//隐藏软键盘
private void hideKeyboard() {
View view = getCurrentFocus();
if (view != null) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
(3)一般utils工具类,什么时候用到什么什么讲解,在这里介绍两个常用的。
MD5
public class MD5 {
public void MD5() {
}
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
}
图像转换相关
public class ImageUtils {
private ImageUtils() {
throw new AssertionError();
}
/**
* convert Bitmap to byte array
*
* @param b
* @return
*/
public static byte[] bitmapToByte(Bitmap b) {
if (b == null) {
return null;
}
ByteArrayOutputStream o = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, o);
return o.toByteArray();
}
/**
* convert byte array to Bitmap
*
* @param b
* @return
*/
public static Bitmap byteToBitmap(byte[] b) {
return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);
}
/**
* convert Drawable to Bitmap
*
* @param d
* @return
*/
public static Bitmap drawableToBitmap(Drawable d) {
return d == null ? null : ((BitmapDrawable)d).getBitmap();
}
/**
* convert Bitmap to Drawable
* @param b
* @return
*/
public static Drawable bitmapToDrawable(Bitmap b) {
return b == null ? null : new BitmapDrawable(b);
}
/**
* convert Drawable to byte array
*
* @param d
* @return
*/
public static byte[] drawableToByte(Drawable d) {
return bitmapToByte(drawableToBitmap(d));
}
/**
* convert byte array to Drawable
*
* @param b
* @return
*/
public static Drawable byteToDrawable(byte[] b) {
return bitmapToDrawable(byteToBitmap(b));
}
/**
* scale image
*
* @param org
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap scaleImageTo(Bitmap org, int newWidth, int newHeight) {
return scaleImage(org, (float) newWidth / org.getWidth(), (float) newHeight / org.getHeight());
}
/**
* scale image
*
* @param org
* @param scaleWidth sacle of width
* @param scaleHeight scale of height
* @return
*/
public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) {
if (org == null) {
return null;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
}
public static Bitmap getImageByFilePath(String filePath, int scale) {
Bitmap res = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
return res;
}
public static Bitmap getImageByFilePath(String filePath, int Towidth, int ToHeight) {
Bitmap res = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
if (!new File(filePath).exists())
return res;
BitmapFactory.decodeFile(filePath, options);
int origionalWidth = options.outHeight;
int origionalHeight = options.outWidth;
options.inJustDecodeBounds = false;
int scale = Math.max(origionalWidth / Towidth, origionalHeight / ToHeight);
options.inSampleSize = scale;
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
try {
res = BitmapFactory.decodeFile(filePath, options);
} catch (Exception e) {
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
return res;
}
}
第一部分先介绍这些,下节讲解Bmob云的使用和登陆,注册的相关。