您的位置:首页 > 理论基础 > 计算机网络

【Android】开发集——Camera/Device/File/Http/IOCallback/Log/TimerIO

2017-02-20 10:48 411 查看
package com.rex.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import java.io.File;

/**
* Created by Rex on 14-5-20.
*/
public class ApkUtil {

public static void install(Context context,String filePath)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
context.startActivity(intent);
}

public static void unInstall(Context context,String packageString)
{
Uri packageURI = Uri.parse("package:"+packageString); //com.demo.CanavaCancel
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(uninstallIntent);
}
}

package com.rex.utils;

import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.util.Log;

/**
* Created by Visionin on 16/11/26.
*/
public class CameraUtil {
public static Camera mCamera = null;

public static Camera.Size openCamera(boolean isFront) {
if (mCamera != null) {
throw new RuntimeException("camera already initialized");
}
int mPosition;
if(isFront){
mPosition= Camera.CameraInfo.CAMERA_FACING_FRONT;
}else {
mPosition=Camera.CameraInfo.CAMERA_FACING_BACK;
}
mCamera=Camera.open(mPosition);

if (mCamera == null) {
Log.e("Visionin", "No front-facing camera found; opening default");
mCamera = Camera.open();    // opens first back-facing camera
}

Camera.Parameters parms = mCamera.getParameters();
return parms.getPreviewSize();
}

public static Camera.Size openCamera(int desiredWidth, int desiredHeight, boolean isFront) {
if (mCamera != null) {
throw new RuntimeException("camera already initialized");
}
int mPosition;
if(isFront){
mPosition= Camera.CameraInfo.CAMERA_FACING_FRONT;
mCamera = Camera.open(mPosition);
}else {
mPosition=Camera.CameraInfo.CAMERA_FACING_BACK;
mCamera=Camera.open(mPosition);
}

if (mCamera == null) {
Log.e("Visionin", "No front-facing camera found; opening default");
mCamera = Camera.open();    // opens first back-facing camera
}

Camera.Parameters parms = mCamera.getParameters();
Camera.Size ppsfv = parms.getPreferredPreviewSizeForVideo();
if (ppsfv != null) {
Log.e("Visionin", "Camera preferred preview size for video is " +
ppsfv.width + "x" + ppsfv.height);
parms.setPreviewSize(ppsfv.width, ppsfv.height);
}

for (Camera.Size size : parms.getSupportedPreviewSizes()) {
if (size.width == desiredWidth && size.height == desiredHeight) {
parms.setPreviewSize(desiredWidth, desiredHeight);
break;
}
}

parms.setRecordingHint(true);
parms.setPreviewFormat(ImageFormat.NV21);
mCamera.setParameters(parms);

int[] fpsRange = new int[2];
parms.getPreviewFpsRange(fpsRange);
return parms.getPreviewSize();
}

public static void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
Log.d("Visionin", "releaseCamera -- done");
}
}
}

package com.rex.utils;

import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* Created by Rex on 14-4-19.
*/
public class DeviceUtil {
public static float screenDensity = 0;

public static int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}

/**
* get the height of the device screen
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}

/**
* get the density of the device screen
*
* @param context
* @return
*/
public static float getScreenDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}

public static int getScreenDensityDpi(Context context){
return context.getResources().getDisplayMetrics().densityDpi;
}
/**
* dip to px
*
* @param context
* @param dp
* @return
*/
public static int dip2px(Context context, float dp) {
if(screenDensity==0) {
screenDensity = getScreenDensity(context);
}
return (int) (dp * screenDensity + 0.5);
}

private static String deviceId = null;
public static String deviceId(Context context){
if(deviceId==null){
String serial =  android.os.Build.SERIAL;
String androidId =  Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length()%10 +
Build.BRAND.length()%10 +
Build.CPU_ABI.length()%10 +
Build.DEVICE.length()%10 +
Build.DISPLAY.length()%10 +
Build.HOST.length()%10 +
Build.ID.length()%10 +
Build.MANUFACTURER.length()%10 +
Build.MODEL.length()%10 +
Build.PRODUCT.length()%10 +
Build.TAGS.length()%10 +
Build.TYPE.length()%10 +
Build.USER.length()%10 ;
String m_szLongID = serial + m_szDevIDShort
+ androidId;
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
m.update(m_szLongID.getBytes(),0,m_szLongID.length());
// get md5 bytes
byte p_md5Data[] = m.digest();
// create a hex string
String m_szUniqueID = new String();
for (int i=0;i<p_md5Data.length;i++) {
int b =  (0xFF & p_md5Data[i]);
// if it is a single digit, make sure it have 0 in front (proper padding)
if (b <= 0xF) {
m_szUniqueID += "0";
}
// add number to string
m_szUniqueID+=Integer.toHexString(b);
}
// hex string to uppercase
deviceId = m_szUniqueID.toUpperCase();

return deviceId;
}else
return deviceId;
}

// imei
public static String getDeviceId(Context context){
try{
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}catch (Exception e){
return deviceId(context);
}
}

// 手机号
public static String getLine1Number(Context context){
try {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getLine1Number();
}catch (Exception e){
return "";
}
}
// sim卡
public static String getSimSerialNumber(Context context){
try{
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSimSerialNumber();
}catch (Exception e){
return "";
}
}

public static String packageName;
public static String getPackageName(Context context){
packageName = context.getPackageName();
return packageName;
}

public static String getDeviceModel(){
return android.os.Build.MODEL;
}

public static String getSystemVersion(){
return android.os.Build.VERSION.RELEASE;
}

public static String getManufacturer(){
return android.os.Build.MANUFACTURER;
}
}
package com.rex.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
* Created by Rex on 14-5-5.
*/
public class FileUtil {
public static InputStream fileInputStream(String filePath) throws IOException{
File file = new File(filePath);
if(file.exists()){
return new FileInputStream(file);
}
else{
return null;
}
}

public static OutputStream fileOutputStream(String filePath) throws IOException{
File file = new File(filePath);
String tempPath = file.getAbsolutePath();
return new FileOutputStream(tempPath);
}

public static String read(InputStream inputStream) throws IOException{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = -1;
while((len = inputStream.read(buf)) != -1){
outStream.write(buf, 0, len);
}

byte[] data = outStream.toByteArray();
outStream.close();
inputStream.close();
return new String(data, "UTF-8");
}

public static boolean write(OutputStream outputStream, byte[] content, int offset, int size) throws IOException{
outputStream.write(content, offset, size);
outputStream.close();
return true;
}

public static boolean write(OutputStream outputStream, String content) throws IOException{
outputStream.write(content.getBytes("UTF-8"));
outputStream.close();
return true;
}

public static boolean write(OutputStream os, InputStream is) throws IOException {
byte buf[] = new byte[1024];
int len = -1;
while((len = is.read(buf)) != -1){
os.write(buf, 0, len);
}
is.close();
os.close();

return true;
}

public static boolean write(OutputStream os, InputStream is, IOCallback callback){
byte buf[] = new byte[callback.split];
int len = -1;
int total = 0;
try {
while((len = is.read(buf)) != -1){
os.write(buf, 0, len);
total += len;
callback.setParam(total*100/callback.length);
callback.onRunning();
}
is.close();
os.close();
callback.onSuccess();
} catch (IOException e) {
e.printStackTrace();
callback.onFailure(e);
}

return true;
}

public static boolean write(OutputStream os, InputStream is, TimerIOCallback callback){
byte buf[] = new byte[1024];
int len = -1;
int total = 0;
try {
while((len = is.read(buf)) != -1){
os.write(buf, 0, len);
total += len;
callback.setParam(total * 100 / callback.length);
}
is.close();
os.close();
callback.onSuccess();
} catch (IOException e) {
e.printStackTrace();
callback.onFailure(e);
}

return true;
}

public static boolean exists(String pathString){
File f = new File(pathString);
if(!f.exists()){
return false;
}
else{
return true;
}
}

public static void writeImage(Bitmap bitmap, OutputStream fileOutputStream){
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream);
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static Bitmap readPNG(String path){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
return BitmapFactory.decodeFile(path, options);
}

public static Bitmap readPNG(byte[] bytes){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}

public static boolean unzip(String src, String dest){
ZipInputStream inZip = null;
try {
inZip = new ZipInputStream(new FileInputStream(src));
ZipEntry zipEntry;
String szName = "";
while ((zipEntry = inZip.getNextEntry()) != null) {
szName = zipEntry.getName();
if (zipEntry.isDirectory()) {
szName = szName.substring(0, szName.length() - 1);
File folder = new File(dest + "/" + szName);
folder.mkdirs();
} else {

File file = new File(dest + "/" + szName);
file.createNewFile();

FileOutputStream out = new FileOutputStream(file);
int len;
byte[] buffer = new byte[1024];

while ((len = inZip.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush();
}

out.close();
}
}
inZip.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}

return true;
}
}


package com.rex.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Pair;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
* Created by Rex on 14-5-5.
*/
public class HttpUtil {

public static HttpURLConnection getConnection(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
if (conn.getResponseCode() != 200) {
return null;
}
return conn;
}

public static InputStream urlInputStream(HttpURLConnection conn) throws IOException {
return conn.getInputStream();
}

public static InputStream urlInputStream(String urlStr) throws IOException {
HttpURLConnection conn = getConnection(urlStr);
return urlInputStream(conn);
}

public static int getContentLength(String urlStr) throws IOException {
HttpURLConnection conn = getConnection(urlStr);
return conn.getContentLength();
}

public static String get(InputStream is)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;

while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
is.close();

return sb.toString();
}

public static String get(String urlStr) throws IOException{
return get(urlInputStream(urlStr));
}

public static Bitmap getBitMap(InputStream is) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}

public static Bitmap getBitMap(String urlStr) throws Exception {
return getBitMap(urlInputStream(urlStr));
}

public static String get(String host, String query) throws IOException{
Socket socket = new Socket(host, 80);
StringBuilder html = new StringBuilder();
//socket.connect(new InetSocketAddress("116.251.214.93", 80));
// 写与的内容就是遵循HTTP请求协议格式的内容,请求百度
StringBuilder requestHeader = new StringBuilder();
requestHeader.append("GET " + "http://"+host+ query + " HTTP/1.0\r\n");
requestHeader.append("Proxy-Connection: Keep-Alive\r\n");
requestHeader.append("Host: " + host + "\r\n");
requestHeader.append("Accept: Accept: textml,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n");
requestHeader.append("User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1707.0 Safari/537.36\r\n");
requestHeader.append("Accept-Encoding: deflate,sdch\r\n");
requestHeader.append("Accept-Language: zh-CN,zh;q=0.8\r\n");
requestHeader.append("Referer: http://"+ host +"/\r\n");
requestHeader.append("\r\n");
socket.getOutputStream().write(requestHeader.toString().getBytes());

byte[] buf = new byte[2048];
InputStream is = socket.getInputStream();
int i;

while ((i = is.read(buf)) > 0) {
html.append(new String(buf, 0, i, "UTF-8"));
}
is.close();
socket.close();
return html.toString();
}

public static String get(String https, Pair<String, String>[] headers){
return https(https, "GET", headers, null);
}
public static String post(String https, Pair<String, String>[] headers, String body){
return https(https, "POST", headers, body);
}
public static String put(String https, Pair<String, String>[] headers, String body){
return https(https, "PUT", headers, body);
}
public static String delete(String https, Pair<String, String>[] headers){
return https(https, "DELETE", headers, null);
}
public static String https(String https, String method, Pair<String, String>[] headers, String body){
//        try {
//            SSLContext sc = SSLContext.getInstance("TLS");
//            sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
//            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//            HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
//            HttpURLConnection.setFollowRedirects(true);
//            HttpsURLConnection conn = (HttpsURLConnection)new URL(https).openConnection();
//            conn.setRequestMethod(method);
//            for (int i=0; i<headers.length; i++){
//                conn.setRequestProperty(headers[i].first, headers[i].second);
//            }
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            if (body!=null){
//                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//                out.write(body.getBytes());
//                out.flush();
//                out.close();
//            }
//
//            conn.connect();
//            if (conn.getResponseCode() != 200) {
//                throw new Exception("服务器错误:"+conn.getResponseCode());
//            }
//
//            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            StringBuffer sb = new StringBuffer();
//            String line;
//            while ((line = br.readLine()) != null)
//                sb.append(line);
//
//            return sb.toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
return null;
}
//    static private class MyHostnameVerifier implements HostnameVerifier {
//
//        @Override
//        public boolean verify(String hostname, SSLSession session) {
//            // TODO Auto-generated method stub
//            return true;
//        }
//    }
//    static private class MyTrustManager implements X509TrustManager {
//
//        @Override
//        public void checkClientTrusted(X509Certificate[] chain, String authType)
//                throws CertificateException {
//            // TODO Auto-generated method stub
//
//        }
//
//        @Override
//        public void checkServerTrusted(X509Certificate[] chain, String authType)
//                throws CertificateException {
//            // TODO Auto-generated method stub
//
//        }
//
//        @Override
//        public X509Certificate[] getAcceptedIssuers() {
//            // TODO Auto-generated method stub
//            return null;
//        }
//    }
}

package com.rex.utils;

/**
* Created by Rex on 14-5-19.
*/
public abstract class IOCallback {
// 没个split调用一次callback
public int length;
public int split;
public IOCallback(int length, int split){
this.length = length;
this.split = split;
}

// 设置参数
public abstract void setParam(int param);
public abstract void onRunning();
public abstract void onSuccess();
public abstract void onFailure(Exception e);
}

package com.rex.utils;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by Rex on 14-8-18.
*/
public class LogUtil {
public static void initialize(String path){
LogUtil.path = path;
}

public static void log(String type, String s){
try {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
FileWriter writer = new FileWriter(path+ dateFormat.format(date) +".log", true);
writer.append("["+type+"]"+ timeFormat.format(date)+"\t\t"+ s+"\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void debug(String s){
log("debug", s);
}
public static void notice(String s){
log("notice", s);
}
public static void err(String s){
log("err", s);
}
private static String path = null;
}

package com.rex.utils;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

/**
* Created by Rex on 14-5-18.
* 获取Manifest中得meta-data配置
*/
public class ManifestUtil {
public static String getVersionName(Context context){
try {
return getPackageInfo(context).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}

return "";
}
public static int getVersionCode(Context context){
try {
return getPackageInfo(context).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}

return 0;
}

public static Bundle getActivityMeta(Activity activity) throws PackageManager.NameNotFoundException {
return activity.getPackageManager().getActivityInfo(activity.getComponentName(), PackageManager.GET_META_DATA).metaData;
}

public static Bundle getApplicationMeta(Activity activity) throws PackageManager.NameNotFoundException {
return activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA).metaData;
}

public static Bundle getServiceMeta(Service service) throws PackageManager.NameNotFoundException {
return service.getPackageManager().getServiceInfo(new ComponentName(service, service.getClass()), PackageManager.GET_META_DATA).metaData;
}

public static Bundle getReceiverMeta(Context context, BroadcastReceiver receiver) throws PackageManager.NameNotFoundException {
return context.getPackageManager().getReceiverInfo(new ComponentName(context, receiver.getClass()), PackageManager.GET_META_DATA).metaData;
}

public static PackageInfo getPackageInfo(Context context) throws PackageManager.NameNotFoundException {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
}
}


package com.rex.utils;

import java.util.Timer;
import java.util.TimerTask;

/**
* Created by Rex on 14-5-20.
*/
public abstract  class TimerIOCallback extends IOCallback{
private Timer       timer;
private TimerTask   task;

public TimerIOCallback(int length, int split){
super(length, split);
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
onRunning();
}
};
// 立即开始,每隔split执行一次
timer.schedule(task, 0, split);
}
public void stop(){
timer.cancel();
timer = null;
task = null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐