- 图片上添加文字
/**
* 在指定图片上指定位置添加文字
*
* @param context
* @param id
* @param text
* @return
*/
public static Drawable addTextOnDrawable(Context context, int id, String text) {
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), id);
int w = bmp.getWidth();
int h = bmp.getHeight();
Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas cv = new Canvas(newb);
cv.drawBitmap(bmp, 0, 0, null);
Paint p = new Paint();
Typeface font = Typeface.create(Typeface.SERIF, Typeface.BOLD_ITALIC);
p.setColor(Color.BLACK);
p.setTypeface(font);
p.setAlpha(127);
p.setTextSize(18);
cv.drawText(text, w * 0.15f, h * 0.85f, p);
cv.save(Canvas.ALL_SAVE_FLAG);
cv.restore();
return new BitmapDrawable(newb);
}
- Frame图片动画
/**
* 获取一个动画图片
*
* @param context
* @param icon
* @param num
* @return
*/
public static AnimationDrawable getAnimationDrawable(Context context, String icon, int num) {
AnimationDrawable frameAnimation = new AnimationDrawable();
for (int i = 1; i <= num; i++) {
Drawable frame = context.getResources().getDrawable(
Utils.getDrawableID(context, icon + i));
frameAnimation.addFrame(frame, 200);
}
frameAnimation.setOneShot(false);
return frameAnimation;
}
- 手写签名Gesture
public class TestGestureActivity extends Activity implements GestureOverlayView.OnGestureListener, OnGesturingListener {
private Gesture gesture;
private int i =0;
private Button button;
private GestureOverlayView gestrues;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button) this.findViewById(R.id.test_btn);
gestrues=(GestureOverlayView) this.findViewById(R.id.gestures);
gestrues.setFadeOffset(6000);
gestrues.addOnGesturePerformedListener(listener);
gestrues.addOnGestureListener(this);
gestrues.addOnGesturingListener(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
gestrues.clear(false);
}
});
}
OnGesturePerformedListener listener=new OnGesturePerformedListener() {
@Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
Bitmap bm = gesture.toBitmap(240, 240, 0, Color.YELLOW);
ImageView im = new ImageView(TestGestureActivity.this);
im = (ImageView) findViewById(R.id.image);
if(bm != null){
im.setImageBitmap(bm);
}
if(Environment.getExternalStorageState().endsWith(Environment.MEDIA_MOUNTED)){
String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
i++;
File images=new File(dir+"/gestureImages");
if(!images.exists()){
images.mkdirs();
}
File image=new File(images.getAbsolutePath()+"/gesture"+i+".png");
FileOutputStream out=null;
try {
image.createNewFile();
out =new FileOutputStream(image);
boolean result=bm.compress(CompressFormat.PNG, 100, out);
if(result){
Toast.makeText(TestGestureActivity.this, "gesture已保存在/sdcard/gestureImages/下", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TestGestureActivity.this, "gesture保存失败", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
};
@Override
public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
// overlay.clear(false);
}
@Override
public void onGesture(GestureOverlayView overlay, MotionEvent event) {
}
@Override
public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
//画完得到手势,如果长度过短则清除
gesture = overlay.getGesture();
if (gesture.getLength() < 100) {
overlay.clear(false);
}
}
@Override
public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {
}
@Override
public void onGesturingStarted(GestureOverlayView overlay) {
}
@Override
public void onGesturingEnded(GestureOverlayView overlay) {
}
}
- android动态加载处理过的jar(dex)
/**
* 加载jar包的index页面
*/
public void initContainer(){
LayoutInflater flater=this.getLayoutInflater();
container=(LinearLayout)flater.inflate(R.layout.container, null);
Intent intent=this.getIntent();
String packgeName=intent.getStringExtra("packgeName");
String codeFilePath=intent.getStringExtra("codeFilePath");
try {
File codeFile = new File(codeFilePath);
DexClassLoader cl = new DexClassLoader(codeFile.getAbsolutePath(),this.getCacheDir().getAbsolutePath(), null, getClassLoader());
Class c=cl.loadClass(packgeName+".IndexView");
Class[] parameterTypes={Activity.class};
Constructor constructor= c.getConstructor(parameterTypes);
Object[] parameters={this};
View view=(View)constructor.newInstance(parameters);
container.addView(view);
currentView=view;
} catch (Exception e) {
Log.e(Tag, "load index view error");
e.printStackTrace();
}
}
- 异步缓冲加载图片imageLoader
public class ImageLoader {
private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
private BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
/**下载线程管理*/
private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 3, 5, TimeUnit.SECONDS,
workQueue, new ThreadPoolExecutor.CallerRunsPolicy());
private Context mContext;
/**客户端放功能点图标的缓存路径*/
private String IconCachePath;
// 尝试次数
private int num = 3;
public ImageLoader(Context context) {
this.mContext = context;
IconCachePath = context.getDir("iconFile", Context.MODE_PRIVATE).getAbsolutePath();
}
/**
* 异步加载图片时调用该方法
* @param imageUrl 服务器图片url
* @param cacheIcon 本地要缓存该图片的文件名称
* @param callback 下载完毕要执行的回调方法
* @return
*/
public Drawable loadDrawable(final String imageUrl, String cacheIcon,
final ImageCallback callback) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
callback.imageLoaded((Drawable)msg.obj, imageUrl);
}
};
try {
threadPool.execute(new ImageThread(handler, cacheIcon, imageUrl));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 用url下载图片,加入失败重试,默认重试次数是3次
* @param imageUrl
* @return
*/
protected Drawable loadImageFromUrl(String imageUrl) {
// 开始下载
AndroidHttpClient client = null;
try {
Drawable drawable = null;
while (num > 0) {
client = AndroidHttpClient.newInstance(null, mContext);
HttpGet request = new HttpGet(imageUrl);
HttpResponse response = client.execute(request);
InputStream entityStream = response.getEntity().getContent();
drawable = Drawable.createFromStream(entityStream, "src");
if (drawable != null && drawable.getIntrinsicWidth() > 0) {
break;
}
//下载失败一次会去检查一次网络是否正常,如果因为网络错误的原因导致下载失败,直接跳出重试循环
boolean netStatus = GlobalUtil.isNetAvailable(mContext);
if (!netStatus) {
Toast.makeText(mContext, "网络错误,请检查网络设置!", Toast.LENGTH_SHORT).show();
break;
}
num--;
}
return drawable;
} catch (Exception e) {
return null;
} finally {
if (client != null) {
client.close();
client = null;
}
}
}
// 下载完成之后回调接口
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
/**
* 加载图片工作线程类
*/
class ImageThread implements Runnable {
private String imageUrl;
private String cacheIcon;
private Handler handler;
public ImageThread(Handler handler, String cacheIcon, String imageUrl) {
this.handler = handler;
this.cacheIcon = cacheIcon;
this.imageUrl = imageUrl;
}
@Override
public void run() {
//本地缓存图片文件
File icon = new File(IconCachePath + "/" + cacheIcon);
if (imageCache.containsKey(imageUrl)) { // 检查缓冲imageCache是否存在对应的KEY
SoftReference<Drawable> softReference = imageCache.get(imageUrl); // 存在就获取对应的值
if (softReference.get() != null) {
Message message = handler.obtainMessage(0, softReference.get());
handler.sendMessage(message);
}
} else if (icon.exists()) { //首先检查本地是否存在该图片文件,存在则取本地的文件加载
Drawable drawable = Drawable.createFromPath(IconCachePath + "/" + cacheIcon);
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
} else { //如果不存在则通过网络去下载
Drawable drawable = loadImageFromUrl(imageUrl); // 使用下面的方法获取Drawable
if (drawable != null && drawable.getIntrinsicWidth() > 0) {
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); // 把图片放到HasMap中
// 判断下载是否成功,如果下载正确,则把图片缓存写入本地文件
try {
icon.createNewFile();
FileOutputStream out = new FileOutputStream(icon);
BitmapDrawable b = (BitmapDrawable)drawable;
Bitmap bitmap = b.getBitmap();
bitmap.compress(CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
}
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}
}
}
- 防篡改签名验证机制
/**
* 获取当前应用的签名公钥
*
* @param context
* @return
*/
public static String getPublicKey(Context context) {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pinfo = pm.getPackageInfo(context.getPackageName(),
PackageManager.GET_SIGNATURES);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)certFactory
.generateCertificate(new ByteArrayInputStream(pinfo.signatures[0].toByteArray()));
String publickey = cert.getPublicKey().toString();
publickey = publickey.substring(publickey.indexOf("modulus: ") + 9,
publickey.indexOf("\n", publickey.indexOf("modulus:")));
return publickey;
} catch (CertificateException e) {
e.printStackTrace();
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
- MD5文件验证
/**
* md5加密文件
*
* @param fileName
* @return
*/
public static String md5sum(String fileName) {
InputStream fis;
byte[] buffer = new byte[1024];
int numRead = 0;
MessageDigest md5;
try {
fis = new FileInputStream(fileName);
md5 = MessageDigest.getInstance("MD5");
while ((numRead = fis.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
fis.close();
return bytesToHexStr(md5.digest());
} catch (Exception e) {
Log.i(TAG, "MD5 " + fileName + " error!");
return null;
}
}
/**
* MD5加密字符串。32位
*
* @param inStr
* @return
*/
public static String MD5(String str) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
char[] charArray = str.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte)charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
return bytesToHexStr(md5Bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Transform the specified byte into a Hex String form.
*/
public static final String bytesToHexStr(byte[] bcd) {
StringBuffer s = new StringBuffer(bcd.length * 2);
for (int i = 0; i < bcd.length; i++) {
s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
s.append(bcdLookup[bcd[i] & 0x0f]);
}
return s.toString();
}