Centos7安装Mysql

欢迎来到风的博客

Centos7安装Mysql

1、配置YUM源
下载mysql源安装包
shell> wget http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm
安装mysql源
shell> yum localinstall mysql57-community-release-el7-8.noarch.rpm
检查mysql源是否安装成功
shell> yum repolist enabled | grep “mysql.-community.
2、安装MySQL
shell> yum install mysql-community-server
3、启动MySQL服务
shell> systemctl start mysqld
4、开机启动
shell> systemctl enable mysqld
shell> systemctl daemon-reload
5、修改root默认密码
shell> grep ‘temporary password’ /var/log/mysqld.log
shell> mysql -uroot -p
mysql> ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘MyNewPass4!’;
或者
mysql> set password for ‘root’@’localhost’=password(‘MyNewPass4!’);

6.设置ip登录
检查root配置
root用户登录
$ mysql -u root -p
切换到mysql这个数据库
mysql> use mysql;
指定密码策略
validate_password_policy=0
set global validate_password_policy=0;
修改密码
update mysql.user set authentication_string=PASSWORD(‘ysrfeng-001’) where User=’root’;
给用户授权
mysql> grant all privileges on . to ‘root’@’%’ identified by ‘123456’ with grant option;
使配置生效
mysql> flush privileges;

http://www.cnblogs.com/ivictor/p/5142809.html

Kotlin集合使用

欢迎来到风的博客

Kotlin动态

  • At the Google I/O keynote,Kotlin 成为 Android 官方编程语言
  • ACM-ICPC World Finals 2018将新增Kotlin作为编程语言

    集合

    集合类型Collections

    • 有序不可重复 -Array
    • 无序不重复 -set
    • 无序可重复 -Map

大小固定,元素类型不可变

1
2
3
4
5
6
fun main(array: Array<String>) {
var arrays = arrayOf("java","c","Kotlin")
for (a in arrays ){
println(a)
}
}

创建默认值数组

1
var arrays = Array(20, { "Kotlin" })

创建自增数组

1
var count = Array(10, { i -> i + 1 })

数组常用方法

1
2
3
4
//数组计数
count.size
//数组是否为空
count.isEmpty()

过滤重复数组

1
2
3
println(arrays.distinct())
//或
println(arrays.toSet())

提示:hashSetOf自身有去重

1
2
3
4
5
var has = hashSetOf("java", "Kotlin", "Kotlin", "Kotlin", "Kotlin", "Kotlin")
for (h in has) {
println(h)
}
//输出结果 java Kotlin

切割数组

1
val Intercept=arrays.sliceArray(2..4)

大小可变,元素类型不可变

1
2
3
4
5
var mutableListOfs = mutableListOf("java","c","C++","java","Visual Basic"," Scala","Kotlin","java","c","Kotlin")
//数组末尾添加
mutableListOfs.add("Swift")
//添加一个数组
mutableListOfs.addAll(arrays)

无序不重复

1
2
3
4
5
6
7
8
9
10
val mainLine = setOf("Java", "Swift", "C++", "PHP", "Go", "Python")
val twoLine = setOf("C++", "C", "Ruby", "Objective-C")
val threeLine = setOf("C++", "Scala", "Dart")
//元素计数
println(mainLine.count())
//是否为空
println(mainLine.isEmpty())
//是否包含
println(mainLine.contains("Swift"))
println(mainLine.containsAll(twoLine))

转换数组

1
2
3
4
val array = mainLine.toTypedArray()
for (a in array) {
println(a)
}

集合运算

1
2
3
4
5
6
val meetLines = mainLine.intersect(twoLine)//交集
println(meetLines)
val diffLine = mainLine.subtract(twoLine)//差集
println(diffLine)
println(mainLine.union(twoLine))//并集
println(mainLine.minus(twoLine))//补集

Map使用,没有顺序位置会改变

1
2
3
4
5
6
7
8
val mapList = mapOf<String, String>(Pair("a", "1"), Pair("b", "1"), Pair("c", "1"), Pair("d", "1"))
//获取key值
println("a".toLowerCase())
println("a".toUpperCase())
println(mapList.getOrDefault("A".toLowerCase(), "不存在"))
//返回所有key/value
mapList.keys
mapList.values

转换为可变

1
2
3
4
5
6
7
8
9
10
11
val tmapList = mapList.toMutableMap()
//修改
tmapList["a"] = "8648"
//添加
tmapList.put("e", "156156")
//移除
tmapList.remove("a")
for (t in tmapList) {
println(t)
}

Demo下载地址:https://github.com/Ysrfengnull/kt.git

  • Search in QQ group 200409033

Android网络传输中必用的两个加密算法

#欢迎来到风的博客

###MD5 和 RSA
MD5和RSA是网络传输中最常用的两个算法,了解这两个算法原理后就能大致知道加密是怎么一回事了。但这两种算法使用环境有差异,刚好互补


MD5加密

######首先MD5是不可逆的,只能加密而不能解密。比如明文是yanzi1225627,得到MD5加密后的字符串是:14F2AE15259E2C276A095E7394DA0CA9 但不能由后面一大串倒推出yanzi1225627.因此可以用来存储用户输入的密码在服务器上。现在下载文件校验文件是否中途被篡改也是用的它,原理参见:http://blog.csdn.net/forgotaboutgirl/article/details/7258109 无论在Android上还是pc上用java实现MD5都比较容易,因为java已经把它做到了java.security.MessageDigest里。下面是一个MD5Util.java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package org.md5.util;
import java.security.MessageDigest;
public class MD5Util {
public final static String getMD5String(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes();
//获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
//使用指定的字节更新摘要
mdInst.update(btInput);
//获得密文
byte[] md = mdInst.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) {
e.printStackTrace();
return null;
}
}
}

通过下面两行代码调用:

1
2
3
//MD5加密测试
String srcString = "yanzi1225627";
System.out.println("MD5加密后 = " + MD5Util.getMD5String(srcString));

##RSA 加密
RSA是可逆的,一个字符串可以经rsa加密后,经加密后的字符串传到对端如服务器上,再进行解密即可。前提是服务器知道解密的私钥,当然这个私钥最好不要再网络传输。
RSA算法描述中需要以下几个变量:

  • 1:p和q 是不相等的,足够大的两个质数。 p和q是保密的
  • 2:n = p*q n是公开的
  • 3:f(n) = (p-1)*(q-1)
  • 4:e 是和f(n)互质的质数
  • 5:计算参数d
  • 6:经过上面5步计算得到公钥KU=(e,n) 私钥KR=(d,n)
    下面两篇文章对此有清晰的描述:
    http://wenku.baidu.com/view/e53fbe36a32d7375a417801b.html
    http://bank.hexun.com/2009-06-24/118958531.html
    ####下面是java实现RSAUtil.java类:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    import javax.crypto.Cipher;
    import java.security.*;
    import java.security.spec.RSAPublicKeySpec;
    import java.security.spec.RSAPrivateKeySpec;
    import java.security.spec.InvalidKeySpecException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.io.*;
    import java.math.BigInteger;
    /**
    * RSA 工具类。提供加密,解密,生成密钥对等方法。
    * 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
    * RSA加密原理概述
    * RSA的安全性依赖于大数的分解,公钥和私钥都是两个大素数(大于100的十进制位)的函数。
    * 据猜测,从一个密钥和密文推断出明文的难度等同于分解两个大素数的积
    * ===================================================================
    * (该算法的安全性未得到理论的证明)
    * ===================================================================
    * 密钥的产生:
    * 1.选择两个大素数 p,q ,计算 n=p*q;
    * 2.随机选择加密密钥 e ,要求 e 和 (p-1)*(q-1)互质
    * 3.利用 Euclid 算法计算解密密钥 d , 使其满足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互质)
    * 4:至此得出公钥为 (n,e) 私钥为 (n,d)
    * ===========================================================
    * 加解密方法:
    * 1.首先将要加密的信息 m(二进制表示) 分成等长的数据块 m1,m2,...,mi 块长 s(尽可能大) ,其中 2^s<n
    * 2:对应的密文是: ci = mi^e(mod n)
    * 3:解密时作如下计算: mi = ci^d(mod n)
    * ===========================================================
    * RSA速度
    * 由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论 是软件还是硬件实现。
    * 速度一直是RSA的缺陷。一般来说只用于少量数据 加密。
    *文件名:RSAUtil.java<br>
    *@author 董利伟<br>
    *版本:<br>
    *描述:<br>
    *创建时间:2008-9-23 下午09:58:16<br>
    *文件描述:<br>
    *修改者:<br>
    *修改日期:<br>
    *修改描述:<br>
    */
    public class RSAUtil {
    //密钥对
    private KeyPair keyPair = null;
    /**
    * 初始化密钥对
    */
    public RSAUtil(){
    try {
    this.keyPair = this.generateKeyPair();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    /**
    * 生成密钥对
    * @return KeyPair
    * @throws Exception
    */
    private KeyPair generateKeyPair() throws Exception {
    try {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
    //这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
    final int KEY_SIZE = 1024;
    keyPairGen.initialize(KEY_SIZE, new SecureRandom());
    KeyPair keyPair = keyPairGen.genKeyPair();
    return keyPair;
    } catch (Exception e) {
    throw new Exception(e.getMessage());
    }
    }
    /**
    * 生成公钥
    * @param modulus
    * @param publicExponent
    * @return RSAPublicKey
    * @throws Exception
    */
    private RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {
    KeyFactory keyFac = null;
    try {
    keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    } catch (NoSuchAlgorithmException ex) {
    throw new Exception(ex.getMessage());
    }
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
    try {
    return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException ex) {
    throw new Exception(ex.getMessage());
    }
    }
    /**
    * 生成私钥
    * @param modulus
    * @param privateExponent
    * @return RSAPrivateKey
    * @throws Exception
    */
    private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {
    KeyFactory keyFac = null;
    try {
    keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    } catch (NoSuchAlgorithmException ex) {
    throw new Exception(ex.getMessage());
    }
    RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
    try {
    return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
    } catch (InvalidKeySpecException ex) {
    throw new Exception(ex.getMessage());
    }
    }
    /**
    * 加密
    * @param key 加密的密钥
    * @param data 待加密的明文数据
    * @return 加密后的数据
    * @throws Exception
    */
    public byte[] encrypt(Key key, byte[] data) throws Exception {
    try {
    Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    cipher.init(Cipher.ENCRYPT_MODE, key);
    //获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127 byte,加密后为128个byte;
    //因此共有2个加密块,第一个127 byte第二个为1个byte
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(data.length);//获得加密块加密后块大小
    int leavedSize = data.length % blockSize;
    int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
    byte[] raw = new byte[outputSize * blocksSize];
    int i = 0;
    while (data.length - i * blockSize > 0) {
    if (data.length - i * blockSize > blockSize)
    cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
    else
    cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
    //这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中
    //,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。
    i++;
    }
    return raw;
    } catch (Exception e) {
    throw new Exception(e.getMessage());
    }
    }
    /**
    * 解密
    * @param key 解密的密钥
    * @param raw 已经加密的数据
    * @return 解密后的明文
    * @throws Exception
    */
    public byte[] decrypt(Key key, byte[] raw) throws Exception {
    try {
    Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
    cipher.init(cipher.DECRYPT_MODE, key);
    int blockSize = cipher.getBlockSize();
    ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
    int j = 0;
    while (raw.length - j * blockSize > 0) {
    bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
    j++;
    }
    return bout.toByteArray();
    } catch (Exception e) {
    throw new Exception(e.getMessage());
    }
    }
    /**
    * 返回公钥
    * @return
    * @throws Exception
    */
    public RSAPublicKey getRSAPublicKey() throws Exception{
    //获取公钥
    RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
    //获取公钥系数(字节数组形式)
    byte[] pubModBytes = pubKey.getModulus().toByteArray();
    //返回公钥公用指数(字节数组形式)
    byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
    //生成公钥
    RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
    return recoveryPubKey;
    }
    /**
    * 获取私钥
    * @return
    * @throws Exception
    */
    public RSAPrivateKey getRSAPrivateKey() throws Exception{
    //获取私钥
    RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
    //返回私钥系数(字节数组形式)
    byte[] priModBytes = priKey.getModulus().toByteArray();
    //返回私钥专用指数(字节数组形式)
    byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
    //生成私钥
    RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);
    return recoveryPriKey;
    }
    }

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
try {
RSAUtil rsa = new RSAUtil();
String str = "yanzi1225627";
RSAPublicKey pubKey = rsa.getRSAPublicKey();
RSAPrivateKey priKey = rsa.getRSAPrivateKey();
byte[] enRsaBytes = rsa.encrypt(pubKey,str.getBytes());
String enRsaStr = new String(enRsaBytes, "UTF-8");
System.out.println("加密后==" + enRsaStr);
System.out.println("解密后==" + new String(rsa.decrypt(priKey, rsa.encrypt(pubKey,str.getBytes()))));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

下面是执行结果:
加密后==s?ko?1@lo????BJ?iE???1Ux?Kx&??=??nO? ?l?>?????2r?y??8v- \A??`????r?t3?-3y?hjL?M??Se?Z???????~?”??e??XZ?苜?
解密后==yanzi1225627
上面代码需要用到一个包rsa.jar,下载链接及上面的测试代码我已打包,下载链接见下:
http://download.csdn.net/detail/yanzi1225627/7382263

原文引自http://blog.csdn.net/yanzi1225627/article/details/26508035

实现扫描二维码和生成带logo的二维码

#欢迎来到风的博客
今天讲的是如何引用google的zxing库实现扫描二维码和生成带logo的二维码,源码库可以从github上下载[https://github.com/zxing/zxing];在文章结尾也会分享我的Demo

#####扫描二维码

1
2
Intent startScan = new Intent(MainActivity.this,CaptureActivity.class);
startActivity(startScan);

#####生成不带logo的二维码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
String in = input.getText().toString();
if (in.equals("")) {
Toast.makeText(MainActivity.this, "请输入文本", Toast.LENGTH_SHORT).show();
}
try {
//TODO 也可以生成二维码
// Bitmap qrcod = EncodingHandler.createQRCode(in, 400);
// img.setImageBitmap(qrcod);
// 写入数据信息到图片
int width = 400, height = 400;
QRCodeWriter writer = new QRCodeWriter();
//把内容编码
BitMatrix matrix = writer.encode(in, BarcodeFormat.QR_CODE, width, height);
int ms[] = new int[width * height];
//变换赋值
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
//黑点
ms[y * width + x] = 0xff000000;
} else {
//白点
ms[y * width + x] = 0xffffffff;
}
}
}
//TODO 缓存
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
image.setPixels(ms, 0, width, 0, 0, width, height);
//TODO 展示图片
img.setImageBitmap(image);
FileOutputStream out = new FileOutputStream("/sdcard/code2.png");
//TODO 压缩
image.compress(Bitmap.CompressFormat.PNG, 100, out);
Log.e("MMMM", "创建成功");
} catch (WriterException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

#####带logo的二维码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//Todo 带logo的二维码
@Override
public void onClick(View v) {
String in = input.getText().toString();
if (in.equals("")) {
Toast.makeText(MainActivity.this, "请输入文本", Toast.LENGTH_SHORT).show();
}
try {
// 写入数据信息到图片
int width = 400, height = 400;
QRCodeWriter writer = new QRCodeWriter();
//把内容编码
BitMatrix matrix = writer.encode(in, BarcodeFormat.QR_CODE, width, height);
int ms[] = new int[width * height];
//变换赋值
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
//黑点
ms[y * width + x] = 0xff000000;
} else {
//白点
ms[y * width + x] = 0xffffffff;
}
}
}
//TODO 缓存
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
image.setPixels(ms, 0, width, 0, 0, width, height);
//logo地址
Bitmap logo = BitmapFactory.decodeFile("/sdcard/gur03.png");
image = insertLogo(image, logo);
//TODO 展示图片
img.setImageBitmap(image);
//存储生成的二维码地址
FileOutputStream out = new FileOutputStream("/sdcard/code2.png");
//TODO 压缩
image.compress(Bitmap.CompressFormat.PNG, 100, out);
Log.e("MMMM", "创建成功");
} catch (WriterException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public Bitmap insertLogo(Bitmap src, Bitmap logo) {
// 获取到两张图片的宽高
int width = src.getWidth();
int height = src.getHeight();
int gwidth = logo.getWidth();
int gheight = logo.getHeight();
// 大小图片的比例
float scale = width * 1.0f / 5 / gwidth;
// 工作缓冲区
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// 获取缓冲区的画布
Canvas ca = new Canvas(bitmap);
// 话大图片
ca.drawBitmap(src, 0, 0, null);
ca.scale(scale, scale, width / 2, height / 2);
// 话小图片
ca.drawBitmap(logo, (width - gwidth) / 2, (height - gheight) / 2, null);
// 保存所画内容
ca.save(Canvas.ALL_SAVE_FLAG);
// 还原画布
ca.restore();
return bitmap;
}

注意利用画布将图片覆盖在生成的二维码上,图片是30*30的,
原理是二维码中间有可以忽略的阴影
app引用BarCodeTest类库
Demo下载地址:https://github.com/MyfengNull/QrCode

本文原创下载请注明出处

Android中Socket通信

#欢迎来到风的博客

###Android中Socket通信

Socket链接的建立过程

  • 1服务器监听
  • 2客户端发出请求
  • 3建立链接
  • 4通信

Socket特点

  • 1Socket基于TCP链接,数据传输有保障
  • 2适用于建立长时间链接
  • 3Socket编程常应用于即时通讯

实现左右点击图片预览

#欢迎来到风的博客

###实现左右点击图片预览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class MainActivity extends Activity {
private ImageView iv;
int img_[] = new int[] { R.drawable.img_1, R.drawable.img_2,
R.drawable.img_3, R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7, R.drawable.img_8,
R.drawable.img_9, };
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int width = this.getWindowManager().getDefaultDisplay()
.getWidth();
iv = (ImageView) findViewById(R.id.imageView1);
iv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
int x = (int) event.getX();
if (x >= (width / 2)) {
if (count == 8) {
count = -1;
}
view.setImageResource(img_[++count]);
} else {
if (x < (width / 2)) {
if (count == 0) {
count = 9;
}
view.setImageResource(img_[--count]);
}
}
return false;
}
});
}
}

判断sdCard是否挂载

#欢迎来到风的博客

###判断sdCard是否挂载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class FileUtils {
/**
* 判断sdCard是否挂载
* @return
*/
public static boolean isConnSdCard(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
/**
* 将图片的字节数组保存到 sd卡上
* @return
*/
public static boolean writeToSdcard(byte[] buffer ,String imagName){
FileOutputStream outputStream =null;
boolean flag = false;
String fileName = imagName.substring(imagName.lastIndexOf("/")+1);
File file = new File(Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
try {
outputStream = new FileOutputStream(file);
outputStream.write(buffer);
flag = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return flag;
}
}

判断是否有网络

#欢迎来到风的博客

###Android判断是否有网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class HttpUtils {
/**
* 判断是否有网络
* @param context
* @return
*/
public static boolean isNetWork(Context context){
//得到网络的管理者
ConnectivityManager manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info!=null){
return true;
}else{
return false;
}
}
/**
* 获取数据
* @param path
* @return
*/
public static byte[] getData(String path) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int temp = 0;
while ((temp = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, temp);
outputStream.flush();
}
}
return outputStream.toByteArray();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

重写listview,使其嵌套scrollview

#欢迎来到风的博客

###重写listview,使其嵌套scrollview

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class ListViewForScrollView extends ListView {
public ListViewForScrollView(Context context) {
super(context);
}
public ListViewForScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* 重写该方法,达到使ListView适应ScrollView的效果
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}

px,dip(dp),sp,dpi,分辨率详解

#欢迎来到风的博客

###px,dip(dp),sp,dpi,分辨率详解
1.px (pixels)像素: 是像素,就是屏幕上实际的像素点单位。
dip或dp (device independent pixels)设备独立像素, 与设备屏幕有关。
sp (scaled pixels : best for text size):类似dp, 主要处理字体的大小。
dpi(dot per inch):屏幕像素密度,每英寸多少像素

density:density表示每英寸有多少个显示点(逻辑值),它的单位是dpi

2.dpi是屏幕像素密度。就是1英寸上像素点的个数。对于屏幕来说,dpi越大,屏幕的精细度越高,屏幕看起来就越清楚。比如iphone4的视网膜级的屏幕肯定比iphone 3gs的屏幕像素密度高的多。

3.sp由于是放大像素,主要是用于字体显示,由此根据google的建议,TextView的字体大小最好用sp做单位

4.dp是与密度无关,sp除了与密度无关外,还与scale无关。如果屏幕密度为160,这时dp和sp和px是一样的。1dp=1sp=1px,但如果使用px作单位,如果屏幕大小不变(假设还是3.2寸),而屏幕密度变成了320。那么原来TextView的宽度设成160px,在密度为320的3.2寸屏幕里看要比在密度为160的3.2寸屏幕上看短了一半。但如果设置成160dp或160sp的话。系统会自动将width属性值设置成320px的。也就是160 * 320 / 160。其中320 / 160可称为密度比例因子。也就是说,如果使用dp和sp,系统会根据屏幕密度的变化自动进行转换。

5.dip值 =(dpi值/160)* pixel值

6.像素密度和分辨率是两个不同的概念,分辨率是总的像素点,像素密度是单位长度的像素点

HVGA屏density=160;QVGA屏density=120;WVGA屏density=240;WQVGA屏density=120

VGA:Video Graphics Array,即:显示绘图矩阵,相当于640×480
HVGA:Half-size VGA;即:VGA的一半,分辨率为480×320;

QVGA:Quarter VGA;即:VGA的四分之一,分辨率为320×240;

WVGA:Wide Video Graphics Array;即:扩大的VGA,分辨率为800×480像素;

WQVGA:Wide Quarter VGA;即:扩大的QVGA,分辨率比QVGA高,比VGA低,一般是:400×240,480×272


px :是屏幕的像素点
in :英寸
mm :毫米
pt :磅,1/72 英寸
dp :一个基于density的抽象单位,如果一个160dpi的屏幕,1dp=1px
dip :等同于dp
sp :同dp相似,但还会根据用户的字体大小偏好来缩放。
建议使用sp作为文本的单位,其它用dip
针对dip和px 的关系,做以下概述:
QVGA屏density=120; QVGA(240320)
HVGA屏density=160; HVGA(320
480)
WVGA屏density=240; WVGA(480800)
WQVGA屏density=120 WQVGA(240
400)
density值表示每英寸有多少个显示点,与分辨率是两个概念。
不同density下屏幕分辨率信息,以480dip800dip的 WVGA(density=240)为例
density=120时
屏幕实际分辨率为240px
400px (两个点对应一个分辨率)
状态栏和标题栏高各19px或者25dip
横屏是屏幕宽度400px 或者800dip,工作区域高度211px或者480dip
竖屏时屏幕宽度240px或者480dip,工作区域高度381px或者775dip

density=160时
屏幕实际分辨率为320px*533px (3个点对应两个分辨率)
状态栏和标题栏高个25px或者25dip
横屏是屏幕宽度533px 或者800dip,工作区域高度295px或者480dip
竖屏时屏幕宽度320px或者480dip,工作区域高度508px或者775dip

density=240时
屏幕实际分辨率为480px*800px (一个点对于一个分辨率)
状态栏和标题栏高个38px或者25dip
横屏是屏幕宽度800px 或者800dip,工作区域高度442px或者480dip
竖屏时屏幕宽度480px或者480dip,工作区域高度762px或者775dip

apk的资源包中
当屏幕density=240时,使用hdpi 标签的资源
当屏幕density=160时,使用mdpi标签的资源
当屏幕density=120时,使用ldpi标签的资源。
不加任何标签的资源是各种分辨率情况下共用的。
布局时尽量使用单位dip,少使用px

dp与px换算公式:

$$ pixs =dips (densityDpi/160)$$
$$ dips=(pixs
160)/densityDpi$$

dp这个单位可能对web开发的人比较陌生,因为一般都是使用px(像素)
但是,现在在开始android应用和游戏后,基本上都转换成用dp作用为单位了,因为可以支持多种分辨率的手机.

以下是这两个单位的概念:
px (pixels)像素: 一个像素通常被视为图像的最小的完整采样,这个用的比较多,特别是web开发,页面基本都是使用像素作为单位的.
dip或dp (device independent pixels)设备独立像素 ― 这个和设备硬件有关,一般我们为了支持手机上多种分辨率,如WVGA、HVGA和QVGA,都会使用dip作为长度的单位
在Android开发我们一般都可以不需要使用px的,但是某一些控件的属性没有直接支持dip,像下面的代码

1
2
android.view.ViewGroup.LayoutParams.height
android.view.ViewGroup.LayoutParams.width

上面这两个属性的单位为像素,但是为了兼容多种分辨率的手机,我们需要最好使用dip,时候我们可以调用以下的代码进行转换.

1
2
int heightPx= DisplayUtil.dip2px(this, 33);
mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = heightPx;

以上代码可以在我另一篇文章看得到.该功能是设置Tab的高度,单位是像素.以上的单位转换是为了支持多分辨率手机的.

1
2
3
4
5
6
7
8
9
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}