在经过几年的经验累积之后,我终于决定整理一下曾经遇到的各种问题,给各位走在android开发路上的朋友一点帮助,更多相关问题,请访问我的博客:http://blog.youkuaiyun.com/xiaoliluote 如果您对该问题有更多的解决方式,请留言,验证之后我会编辑博客
编写过好些个程序之后,我发现每个程序中都有一些方法是常常用到的,这里呢,就整理出来,下次使用的时候就不用再去到处找或者重新写啦。
俗话说,站在巨人的肩膀上,事半功倍嘛。
方法一:快捷获取网络数据,写入数据到文件中
//获取网络数据
//传入数据网址,以及将要存放的名字
public void getUrlData(String url,String file_name){
try{
HttpURLConnection conn=(HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
if(conn.getResponseCode() ==200){
InputStream inputStream=conn.getInputStream();
byte[]jsonBytes=convertIsToByteArray(inputStream);
FileOutputStream outStream =_context.openFileOutput(file_name, Context.MODE_PRIVATE);
outStream.write(jsonBytes);//向文件中写入数据,将字符串转换为字节
outStream.close();
return true;
}
}catch(Exception e){
}
}
//上面方法中,用到了一个叫做convertIsToByteArray的方法读取数据转换为byte[]
public static byte[] convertIsToByteArray(InputStream inputStream) {
// TODO Auto-generated method stub
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte buffer[]=new byte[1024];
int length=0;
try {
while ((length=inputStream.read(buffer))!=-1) {
baos.write(buffer, 0, length);
}
inputStream.close();
baos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return baos.toByteArray();
}
方法二,快速读取文件,与方法一共用的哦
//输入方法一存放的文件名,就可以读取出数据啦
public String read(String filename) throws Exception{
//得到输入流之后
FileInputStream inStream =_context.openFileInput(filename);
//创建一个往内存输出流对象
ByteArrayOutputStream outStream =new ByteArrayOutputStream();
byte[] buffer =new byte[1024];
int len =0;
while((len=inStream.read(buffer))!=-1){
//把每次读到的数据写到内存中
outStream.write(buffer,0,len);
}
//得到存放在内存中的所有的数据
byte [] data =outStream.toByteArray();
String result = new String(data,"UTF8");
return result;
}
方法三,读取assets目录下的图片资源
//传入context,以及文件名就OK了,比如文件目录是assets/image/1.png,那么这里就传入image/1.png就可以了
public static Bitmap getImageFromAssetsFile(Context context, String fileName) {
Bitmap image = null;
AssetManager am = context.getResources().getAssets();
try {
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
方法四,将base64转换成bitmap
public Bitmap stringtoBitmap(String string){
//将字符串转换成Bitmap类型
Bitmap bitmap=null;
try {
byte[]bitmapArray;
bitmapArray=Base64.decode(string, Base64.DEFAULT);
bitmap=BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
方法五,合成两张图片变成一张图片
//传入合成后想要的图片的宽,高,以及需要合成的两张图片,这里请留意两张图片的顺序,是secondBitmap覆盖在firstBitmap上面的
public Bitmap mergeBitmap(int width,int height,Bitmap firstBitmap, Bitmap secondBitmap) {
firstBitmap =resizeImage(firstBitmap,width,height);
secondBitmap =resizeImage(secondBitmap,width,height);
Bitmap bitmap = Bitmap.createBitmap(width, height,
firstBitmap.getConfig());
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(firstBitmap, new Matrix(), null);
canvas.drawBitmap(secondBitmap, new Matrix(), null);
return bitmap;
}
public 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);
// 如果你想旋转图片的话
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}
方法六,将图片裁剪成圆角
//传入需要裁剪的图片,以及四个圆角的角度
public Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
方法七,md5加密数据
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("卧槽,不支持md5加密?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("卧槽,不支持utf-8编码?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
public final static String getMessageDigest(byte[] buffer) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(buffer);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
方法八,给某个控件画圆角
//某些时候,我们为了美观效果,会让一些控件以圆角的形式展现,比如下图
//比如这张微信的图片,去评分,欢迎页 外部的这个白色背景,就是圆角的,这样看起来比较美观
//那么这里我以LinearLayout为例子
public class MYLinearLayout extends LinearLayout{
float _corners;
public MYLinearLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MYLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MYLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
//记得调用该方法,传入要生成的角度,这里我只传入了一个参数,是因为我要求四个角度都是一样的,如果你要求上面和下面的角度不一样,那么请设定两个参数
public void set_corners(float corners){
_corners = corners;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(StaticParameter.shape_color);
paint.setStyle(Paint.Style.STROKE);
//这个就是画圆角的方法啦,通过 _corners这个参数来设定圆角大小
canvas.drawRoundRect(new RectF(1,1,this.getWidth() - 1,this.getHeight() - 1), _corners, _corners, paint);
}
}
方法九,java反射
//有时我们的东西是提供给第三方使用,第三方在我们的代码操作后,需要回调给第三方,而我们并不知道第三方的东西,于是就有了反射机制
@SuppressWarnings("rawtypes")
Class handMachine = Class.forName("反射的类名,请写完整包名+类名");
@SuppressWarnings("unchecked")
Method method1 = handMachine.getMethod("反射到上述类名中的哪个方法,这里后面我带了两个String.class,是代表这个方法有两个参数,如果没有的话,就可以不写啦",String.class,String.class);
@SuppressWarnings("unused")
Object handMachineInstance= method1.invoke(handMachine.newInstance(),"这里就是上面第一个String参数的值","第二个String参数的值");
方法十,新浪微博的分享功能
//当我们的应用需要和社交软件分享的时候,用到,这里是新浪分享的代码
//传入在新浪开放平台申请的appid,以及要分享出去的内容
public void shareToWB(String content,String WB_APP_ID){
IWeiboShareAPI mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(_context,WB_APP_ID);
if (mWeiboShareAPI.checkEnvironment(true)) {
mWeiboShareAPI.registerApp();
if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
if (supportApi >= 10351 ) {
// 1. 初始化微博的分享消息
WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
TextObject textObject = new TextObject();
textObject.text = content;
weiboMessage.textObject = textObject;
// 2. 初始化从第三方到微博的消息请求
SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
// 用transaction唯一标识一个请求
request.transaction = String.valueOf(System.currentTimeMillis());
request.multiMessage = weiboMessage;
// 3. 发送请求消息到微博,唤起微博分享界面
mWeiboShareAPI.sendRequest(request);
} else {
WeiboMessage weiboMessage = new WeiboMessage();
TextObject textObject = new TextObject();
textObject.text = content;
weiboMessage.mediaObject = textObject;
// 2. 初始化从第三方到微博的消息请求
SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
// 用transaction唯一标识一个请求
request.transaction = String.valueOf(System.currentTimeMillis());
request.message = weiboMessage;
// 3. 发送请求消息到微博,唤起微博分享界面
mWeiboShareAPI.sendRequest(request);
}
} else {
Toast.makeText(_context,"微博客户端不支持 SDK 分享或微博客户端未安装或微博客户端是非官方版本。",
Toast.LENGTH_SHORT).show();
}
}
}
方法十一,QQ空间的分享以及回调
//分享的type,指分享到空间,还是分享给某个朋友(群),分享的title,summary标题,描述等内容,分享的url,网址,用户点击进去查看的网址,分享的image_json,图片内容,这里由于我想分享多张图片,于是用了一个Jsonarray,但好像只能显示一张图片出来, QQ_API_ID是在腾讯开放平台申请的ID
public void shareToQQ(final String type,final String title,final String summary,final String url,final String image_json,String QQ_API_ID){
mHandler.post(new Runnable(){
@Override
public void run() {
Tencent mTencent= Tencent.createInstance(QQ_API_ID,(Activity) _context);
Bundle params = new Bundle();
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);
params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);
String image_url="";
ArrayList<String> imageUrls = new ArrayList<String>();
try {
JSONArray json_arr = new JSONArray(image_json);
for(int i=0;i<json_arr.length();i++){
image_url=json_arr.getString(i);
imageUrls.add(json_arr.getString(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mTencent != null){
if(type.equals("qzone")){
StaticParameter.QQ_SHARE_TYPE ="qzone";
params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
mTencent.shareToQzone((Activity) _context, params, qZoneShareListener);
}else if(type.equals("qq")){
StaticParameter.QQ_SHARE_TYPE ="qq";
params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image_url);
mTencent.shareToQQ((Activity) _context, params, qZoneShareListener);
}
}else{
Log.e("QQ空间分享失败", "参数配置错误");
}
}});
}
IUiListener qZoneShareListener = new IUiListener() {
@Override
public void onCancel() {
Log.i("QQ空间分享", "用户取消分享");
}
@Override
public void onError(UiError e) {
Log.e("QQ空间分享失败", e.errorMessage);
}
@Override
public void onComplete(Object response) {
Log.i("QQ空间分享成功", response.toString());
}
};
方法十二,微信分享
//传入分享的方式,是分享到朋友圈(wxfriend),还是给朋友(weixin),传入title,标题,传入image,图片网址,传入url,点击跳转的网页,WX_APP_ID是在微信开放平台申请的ID
public void shareToWX(final String way,final String title,final String image,final String url,String WX_APP_ID){
final IWXAPI api;
api =WXAPIFactory.createWXAPI(_context, WX_APP_ID,true);
api.registerApp(WX_APP_ID);
if(api.isWXAppInstalled()){
new Thread(){
public void run(){
WXWebpageObject ob = new WXWebpageObject();
ob.webpageUrl=url;
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = ob;
msg.description = title;
if(way.equalsIgnoreCase("wxfriend"))
msg.title =title;
if(image.length()>0){
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(new URL(image).openStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
bmp.recycle();
// msg.thumbData = bmpToByteArray(thumbBmp, true);
msg.thumbData =getBitmapBytes(thumbBmp,false);
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction ="img"+String.valueOf(System.currentTimeMillis());
req.message = msg;
//WXSceneSession 是分享给微信好友,WXSceneTimeline 是朋友圈
req.scene=way.equalsIgnoreCase("weixin")?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
boolean result=api.sendReq(req);
}
}.start();
}else{
//这里是我写的一个自定义dialog,请参考方法十三
WXConfirmDialog dialog = new WXConfirmDialog(StaticParameter._context);
dialog.set_content("您尚未安装微信,点击确定安装微信");
dialog.show();
}
}
private static byte[] getBitmapBytes(Bitmap bitmap, boolean paramBoolean) {
Bitmap localBitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.RGB_565);
Canvas localCanvas = new Canvas(localBitmap);
int i;
int j;
if (bitmap.getHeight() > bitmap.getWidth()) {
i = bitmap.getWidth();
j = bitmap.getWidth();
} else {
i = bitmap.getHeight();
j = bitmap.getHeight();
}
while (true) {
localCanvas.drawBitmap(bitmap, new Rect(0, 0, i, j), new Rect(0, 0,80, 80), null);
if (paramBoolean)
bitmap.recycle();
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
localByteArrayOutputStream);
localBitmap.recycle();
byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
try {
localByteArrayOutputStream.close();
return arrayOfByte;
} catch (Exception e) {
}
i = bitmap.getHeight();
j = bitmap.getHeight();
}
}
方法十三,自定义dialog控件,这里连接方法十二,该控件给方法十二使用,大家可以再自行扩展
public class WXConfirmDialog extends AlertDialog{
public String _title;
public String _content;
private Context _context;
public WXConfirmDialog(Context context) {
super(context);
this._context=context;
}
public void set_title(String title){
this._title=title;
}
public void set_content(String content){
this._content = content;
}
public void show(){
new AlertDialog.Builder(_context)
.setTitle(_title)
.setMessage(_content)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
Uri uri = Uri.parse("http://weixin.qq.com/cgi-bin/readtemplate?uin=&stype=&fr=&lang=zh_CN&check=false&t=w_down");
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
_context.startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
})
.show();
}
}
方法十四,自定义常见动画类
public class AnimationExecuter {
//动画类
//这个animId可以是这里设定的几种简单动画,0,1之类的,也可以是外部的动画,R.anim.xxx
public static void execute( Context context, int animId, View view, AnimSimpleListener listener ){
Animation anim=null;
switch(animId){
case 0:
//从左往右边退出
anim = new TranslateAnimation(
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,1f,
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,0f);
anim.setDuration(500);
break;
case 1:
//从上往下退出
anim = new TranslateAnimation(
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,1f);
anim.setDuration(500);
break;
case 2:
//360°旋转
anim = new RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
anim.setDuration(500);
anim.setRepeatCount(-1);
break;
case 3:
//从右往左边推进
anim = new TranslateAnimation(
Animation.RELATIVE_TO_SELF,1f,
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,0f);
anim.setDuration(500);
break;
case -1:
//不使用动画
anim = new TranslateAnimation(
Animation.RELATIVE_TO_SELF,1f,
Animation.RELATIVE_TO_SELF,1f,
Animation.RELATIVE_TO_SELF,0f,
Animation.RELATIVE_TO_SELF,0f);
anim.setDuration(500);
break;
default:
anim = AnimationUtils.loadAnimation(context, animId);
break;
}
if(anim != null){
anim.setAnimationListener(listener);
view.startAnimation(anim);
}
}
//这里是监听动画的执行状态
public static class AnimSimpleListener implements AnimationListener{
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation){
}
}
}
//以下是演示调用方法
//传入context,动画ID,执行动画的view
AnimationExecuter.execute(_context, 0,
view, new AnimSimpleListener() {
@Override
public void onAnimationEnd(Animation animation) {
//动画执行完毕,做什么操作
}
});
方法十五,检查网络连接状态
//请留意该方法,如果用在部分写机顶盒应用的机器上,会报空指针哦
public static boolean checkNetWorkInfo(Context context){
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile 2G/3G/4G Data Network
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//wifi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
//如果2G/3G/4G网络和wifi网络都未连接,则return false;
if((mobile == State.DISCONNECTED || mobile == State.DISCONNECTING || mobile == State.UNKNOWN) &&
(wifi == State.DISCONNECTED || wifi == State.DISCONNECTING || wifi == State.UNKNOWN))
return false;
else
return true;
}
方法十六,获取当前是2G/3G/4G网络还是 WIFI网络
public static String getNetWorkAccess(Context context){
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile 2G/3G/4G Data Network
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//wifi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(mobile ==State.CONNECTED)
return "WLAN";
if(wifi == State.CONNECTED)
return "WIFI";
return "UNKNOWN";
}
今天就整理到这里,以上所有内容纯原创,如果转载,请说明出处,国内的各大论坛抄袭的内容太多,经常是一个问题,一搜,csdn是这个答案,eoe也是这个答案,新浪博客也是这个答案,真正有意义的东西太少。