分类
Android开发

Android获取应用程序版本信息

该类获取Android应用程序版本号及版本名称

/**
* 应用程序信息
*/
public class AppUtil {

/**
* 获取Android应用程序版本号
* @param context
* @return
*/
public static int getVersionCode(Context context){
	int versionCode = -1;
	try {
	PackageManager pm = context.getPackageManager();
	versionCode = pm.getPackageInfo(context.getPackageName(), 0).versionCode;
	} catch (Exception e) {
	// TODO: handle exception
	}
	return versionCode;
}

/**
* 获取Android应用程序版本名称
* @param context
* @return
*/
public static String getVersionName(Context context){
	String versionName = null;
	try {
	PackageManager pm = context.getPackageManager();
	versionName = pm.getPackageInfo(context.getPackageName(), 0).versionName;
	} catch (Exception e) {
	// TODO: handle exception
	}
	return versionName;
}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

Android系统获取SIM卡信息

以下工具类获取手机SIM卡相关信息:

/**
* SIMCard工具类,获取SIM卡相关信息
*/
public class SIMCardUtil {
/**
* 通过系统接口获取手机号码,不一定能够获取
* 需要权限 
* @param context
* @return
*/
public static String getNativePhoneNumber(Context context){
	String phone = "";
	try {
	TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	phone = tm.getLine1Number();
	} catch (Exception e) {
	// TODO: handle exception
	}
	return phone;
}

/**
* 获取服务提供商信息
* 需要加入权限
* @param context
* @return
*/
public static String getProvidersName(Context context){
	String ProvidersName = null;
	try {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String IMSI = tm.getSubscriberId();
		// IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
		//System.out.println(IMSI);
		if (IMSI.startsWith(“46000″) || IMSI.startsWith(“46002″)) {
		ProvidersName = "中国移动";
		} else if (IMSI.startsWith(“46001″)) {
		ProvidersName = "中国联通";
		} else if (IMSI.startsWith(“46003″)) {
		ProvidersName = "中国电信";
		}
	} catch (Exception e) {
	// TODO: handle exception
	}
	return ProvidersName;
}

/**
* 获取手机SIM卡IMSI号
* 需要加入权限
* @param context
* @return
*/
public static String getImsi(Context context){
	String imsi = null;
	try {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		imsi = tm.getSubscriberId();
	} catch (Exception e) {
		// TODO: handle exception
	}
	return imsi;
}

/**
* 获取SIM序列号
* 需要加入权限
* @param context
* @return
*/
public static String getSimSerialNumber(Context context){
	String simSerialNum = null;
	try {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		simSerialNum = tm.getSimSerialNumber();
	} catch (Exception e) {
		// TODO: handle exception
	}
	return simSerialNum;
}

/**
* 获取设备id(IMEI)
* 需要加入权限
* @param context
* @return
*/
public static String getDeviceId(Context context){
	String deviceId = null;
	try {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		deviceId = tm.getDeviceId();
	} catch (Exception e) {
		// TODO: handle exception
	}
	return deviceId;
}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android短信数据库监听

1、内容监听类

public class SMSContentObserver extends ContentObserver {

public static final int READ_MSG_SUCC = 2133;
private static String TAG = "SMSContentObserver";
private Context mContext;
private Handler mHandler;//更新UI线程
public SMSContentObserver(Context context,Handler handler) {
	super(handler);
	mContext = context;
	mHandler = handler;
}
/**
* 当所监听的Uri发生改变时,就会回调此方法
* @param selfChange 此值意义不大 一般情况下该回调值false
*/
@Override
public void onChange(boolean selfChange){
	try {
		Log.i(TAG, "the sms table has changed");
		String[] projection = new String[] { "_id", "address", "person",
		"body", "date", "type" };
		Uri uri = Uri.parse("content://sms");
		Cursor cusor = mContext.getContentResolver().query(uri, projection, null, null,
		"date desc");
		if(cusor != null){
		cusor.moveToFirst();
		SmsBean bean = new SmsBean();
		bean.setContent_(cusor.getString(3));
		bean.setSrcAddr_(cusor.getString(1));
		bean.setTime_(cusor.getString(4));
		bean.setName_(cusor.getString(2));
		LogUtil.showPrint("SmsBean="+bean.toString());
		Message msg = mHandler.obtainMessage(READ_MSG_SUCC, bean);
		msg.sendToTarget();
	}
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}
}

2、短信bean

public class SmsBean implements Serializable{

private static final long serialVersionUID = 4425719463747374158L;
private String srcAddr_ = null;
private String content_ = null;
private String time_ = null;
private String name_ = null;

public String getName_() {
	return name_;
}
public void setName_(String name_) {
	this.name_ = name_;
}
public String getSrcAddr_() {
	return srcAddr_;
}
public void setSrcAddr_(String srcAddr_) {
	this.srcAddr_ = srcAddr_;
}
public String getContent_() {
	return content_;
}
public void setContent_(String content_) {
	this.content_ = content_;
}
public String getTime_() {
	return time_;
}
public void setTime_(String time_) {
	this.time_ = time_;
}
@Override
public String toString() {
	// TODO Auto-generated method stub
	return "srcAddress="+srcAddr_+" name="+name_+" time="+time_+" content="+content_;
}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android接收处理短信广播

1、注册广播接收:


	
	

2、添加短信广播接收权限:


3、业务处理代码

public class SmsReceiver extends BroadcastReceiver {

private static final String ACTION = “android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {
	// TODO Auto-generated method stub
	if (intent != null && intent.getAction() != null && intent.getAction().equalsIgnoreCase(ACTION)) {
		//业务处理
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			// 通过pdus获得接收到的所有短信消息,获取短信内容;
			Object[] pdus = (Object[]) bundle.get(“pdus");
			if(pdus != null && pdus.length > 0){
				SmsMessage[] msgs = new SmsMessage[pdus.length];
				for (int i = 0; i < pdus.length; i++) {
				msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}
				for(SmsMessage msg : msgs){
					//读取消息信息
				}
			}
		}
	}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android获取sdcard可用、已用空间大小的方法

android获取sdcard可用、已用空间大小的方法:

/**
* 获取sdcard使用情况
*/
private void setSdcardInfo(){
	if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
		File filePath = Environment.getExternalStorageDirectory();    //获得sd卡的路径
		StatFs stat=new StatFs(filePath.getPath());                 //创建StatFs对象
		long blockSize=stat.getBlockSize();                         //获取block的size
		float totalBlocks=stat.getBlockCount();                     //获取block的总数
		float totalGbSize = (blockSize*totalBlocks)/1024/1024/1024;
		DecimalFormat df = new DecimalFormat("#0.0");
		String totalGbSizeStr = df.format(totalGbSize);            //总共大小
		long availableBlocks=stat.getAvailableBlocks();             //获取可用块大小
		String usedTotalGbSizeStr = df.format((totalBlocks – availableBlocks) * blockSize /1024/1024/1024);//已用大小
		System.out.println("存储空间"+totalGbSizeStr+"G,已用"+usedTotalGbSizeStr+"G");
	}
	else{
		Toast.makeText(this,"SD卡不存在",Toast.LENGTH_LONG).show();
	}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android上传文本到服务器

1、服务器jsp页面upload.jsp

<%@page import="java.io.FileWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.FileReader"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStream"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("UTF-8");
	String savePath = "../log/";
	BufferedReader reader = null;
	BufferedWriter writer = null;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	String fileName = sdf.format(new Date()) + ".log";
	File file = null;
	StringBuffer buffer = new StringBuffer();
	String temp = null;
	try {
		reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
		file = new File(savePath + fileName);
		if(!file.exists()){
		file.createNewFile();
		}
		writer = new BufferedWriter(new FileWriter(file));
		while((temp = reader.readLine()) != null){
		buffer.append(temp);
		}
		writer.write(buffer.toString());
		out.print("upload Success");
	} catch (Exception e) {
	e.printStackTrace();
		out.print("upload server Exception");
	}finally{
		try{
			if(reader != null){
				reader.close();
			}
			if(writer != null){
				writer.close();
			}
		}catch(IOException e){}
	}
%>

2、上传文本文件方法

public static void uploadFile(String uploadFile)
{
	String filePath = "/mnt/sdcard/"+ uploadFile;
	try
	{
		URL url = new URL("http://www.geekapp.cn/upload.jsp");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		/* 允许Input、Output,不使用Cache */
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		/* 设定传送的method=POST */
		con.setRequestMethod("POST");
		/* setRequestProperty */
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty("Content-Type",
		"multipart/form-data" );
		/* 设定DataOutputStream */
		DataOutputStream ds = new DataOutputStream(con.getOutputStream());
		/* 取得文件的FileInputStream */
		FileInputStream fStream = new FileInputStream(filePath);
		/* 设定每次写入1024bytes */
		byte[] buffer = new byte[1024];
		int length = -1;
		/* 从文件读取数据到缓冲区 */
		while ((length = fStream.read(buffer)) != -1)
		{
			/* 将数据写入DataOutputStream中 */
			ds.write(buffer, 0, length);
		}
		fStream.close();
		ds.flush();
		ds.close();
	} catch (Exception e)
	{
	Log.e("文件上传", e.getMessage());
	}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android加载、保存bitmap图片

1、从本地加载图片

/**
* 加载本地图片
* @param imagePath图片路径
* @return
*/
public Bitmap loadImageFromLocal(String imagePath){
	Bitmap img = null;
	File file = new File(imagePath);
	if(file.exists()){
		BitmapDrawable bitmap = new BitmapDrawable(imagePath);
		img = bitmap.getBitmap();
	}
	return img;
}

2、保存图片到本地

/**
* 保存图片
* @param bm
* @param filePath
* @throws IOException
*/
public void saveBitmap(Bitmap bm, String filePath) throws IOException {
	File myCaptureFile = new File(filePath);
	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
	bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
	bos.flush();
	bos.close();
}

3、加载网络图片

/**
* 下载网络图片
* @param url
* @param width
* @param height
* @return
*/
private Bitmap downloadBitmap(String url, int width, int height) {
	try {
		Bitmap bitmap = null;
		url.replaceAll(” “, “%20″);
		bitmap = BitmapFactory.decodeStream((InputStream) new URL(
		url).getContent());
		bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
		return bitmap;
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android sqlite数据库实例

1、数据库封装工具类

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBTools {
	public static void insert(Context context, DownloadInfoBean bean){
		DBHelper db = new DBHelper(context);
		db.open();
		db.insert(bean);
		db.close();
	}

	public static void delete(Context context){
		DBHelper db = new DBHelper(context);
		db.open();
		db.delete();
		db.close();
	}

	public static void update(Context context, DownloadInfoBean bean){
		DBHelper db = new DBHelper(context);
		db.open();
		db.update(bean);
		db.close();
	}

	public static DownloadInfoBean query(Context context){
		DownloadInfoBean bean = null;
		DBHelper db = new DBHelper(context);
		db.open();
		Cursor cursor = db.query();
		if(cursor != null){
			if(cursor.getCount() > 0){
				cursor.moveToFirst();
				bean = new DownloadInfoBean();
				bean.filesize = cursor.getInt(1);
				bean.complete = cursor.getInt(2);
			}
			cursor.close();
		}
		db.close();
		return bean;
	}

	public static final class DBHelper extends SQLiteOpenHelper{

	private final static String DB_NAME = "download_info.db";
	private final static int DB_VERSION = 1;
	private final String TB_DOWNLOAD_INFO = "tb_download_info";
	private static SQLiteDatabase sqlDb = null;
	private static Object lock = new Object();

	public DBHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		// TODO Auto-generated constructor stub
	}

	public void open(){
		synchronized (lock) {
			sqlDb = this.getReadableDatabase();
		}
	}

	public void close(){
		synchronized (lock) {
			if(sqlDb != null){
				sqlDb.close();
			}
		}
	}

	public void insert(DownloadInfoBean bean){
		synchronized (lock) {
			ContentValues values = new ContentValues();
			values.put("filesize", bean.filesize);
			values.put("complete", bean.complete);
			sqlDb.insert(TB_DOWNLOAD_INFO, null, values);
		}
	}

	public void delete(){
		synchronized (lock) {
			sqlDb.delete(TB_DOWNLOAD_INFO, null, null);
		}
	}

	public void update(DownloadInfoBean bean){
		synchronized (lock) {
			ContentValues values = new ContentValues();
			values.put("complete", bean.complete);
			sqlDb.update(TB_DOWNLOAD_INFO, values, "filesize=?", new String[]{bean.filesize+""});
		}
	}

	public Cursor query(){
		synchronized (lock) {
			return sqlDb.query(TB_DOWNLOAD_INFO, null, null, null, null, null, null);
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("CREATE TABLE IF NOT EXISTS "+
		TB_DOWNLOAD_INFO+"("+
		"id integer NOT NULL PRIMARY KEY AUTOINCREMENT,"+
		"filesize  integer NOT NULL default 0,"+//文件大小
		"complete integer NOT NULL default 0)");//下载完成大小
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		onCreate(db);
	}

	}
}

2、数据对象bean

public class DownloadInfoBean {
	public int filesize = 0;
	public int complete = 0;
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

android获取手机IMSI号

1、什么是imsi号

国际移动用户识别码(IMSI:International Mobile SubscriberIdentification Number)是区别移动用户的标志,储存在SIM卡中,可用于区别移动用户的有效信息。其总长度不超过15位,使用0~9的数字。其中MCC是移动用户所属国家代号,占3位数字,中国的MCC规定为460;MNC是移动网号码,最多由两位数字组成,用于识别移动用户所归属的移动通信网;MSIN是移动用户识别码,用以识别某一移动通信网中的移动用户。

MNC:Mobile Network Code,移动网络码,2~3位,中国移动系统使用00、02、07,中国联通GSM系统使用01,中国电信CDMA系统使用03,一个典型的IMSI号码为460030912121001;

2、获取手机imsi号

public static String getImsi(Context context) {
	TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	String _imsi = tm.getSubscriberId();
	if(_imsi != null && !_imsi.equals("")){
	return _imsi;
	}
	return "未知";
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

HorizontalScrollView结合LinearLayout实现Gallery

1、xml布局







2、自定义MyGallery

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;

public class MyGallery extends LinearLayout {

	private Context mContext;
	private BaseAdapter adapter;
	private AdapterView.OnItemClickListener onItemClickListener;

	public MyGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mContext = context;
		setOrientation(HORIZONTAL);
	}

	public MyGallery(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		mContext = context;
		setOrientation(HORIZONTAL);
	}

	public void setAdapter(BaseAdapter adapter){
		this.adapter = adapter;
		for(int i=0;i

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

Android Sensor重力感应

1、定义变量

private SensorManager mSensorManager = null;
private Sensor mSensor = null;
private SensorEventListener mSensorEventListener = null;
private long lastUpdate = 0;
private float last_x,last_y,last_z;
private final float SHAKE_THRESHOLD = 800f;

2、初始化变量

private void initSensor(){
	mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	if(mSensorManager != null){
		mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorEventListener = new SensorEventListener() {
			@Override
			public void onSensorChanged(SensorEvent event) {
				// TODO Auto-generated method stub
				long curTime = System.currentTimeMillis();
				// 每100毫秒检测一次
				if ((curTime – lastUpdate) > 100) {
					long diffTime = (curTime – lastUpdate);
					lastUpdate = curTime;

					float x = event.values[SensorManager.DATA_X];
					float y = event.values[SensorManager.DATA_Y];
					float z = event.values[SensorManager.DATA_Z];

					float speed = Math.abs(x + y + z – last_x – last_y
					- last_z)
					/ diffTime * 10000;
					Log.i("speed", "speed=" + speed);
					if (speed > SHAKE_THRESHOLD) {
						//do something相应的处理
					}
					last_x = x;
					last_y = y;
					last_z = z;
				}
			}

			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub
			}
		};
	}
}

3、注册、取消注册监听

@Override
protected void onResume() {
	if(mSensorManager != null){
		mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
	}
	super.onResume();
}

@Override
protected void onPause() {
	if(mSensorManager != null){
		mSensorManager.unregisterListener(mSensorEventListener);
	}
	super.onPause();
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

Android图像bitmap与drawable相互转换

1、bitmap转换为drawable

public static Drawable bitmap2Drawable(Bitmap bitmap)
{
if(bitmap == null)
return null;
else
return new BitmapDrawable(bitmap);
}

2、drawable转换为bitmap

public static Bitmap drawable2Bitmap(Drawable drawable)
{
if(drawable == null)
return null;
else
return ((BitmapDrawable)drawable).getBitmap();
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

Android显示隐藏软键盘

1、显示软键盘

public static void showSoftKeyboard(Activity activity)
{
	InputMethodManager inputmethodmanager = (InputMethodManager)activity.getSystemService("input_method");
	if(activity.getCurrentFocus() != null)
	inputmethodmanager.showSoftInput(activity.getCurrentFocus(), 2);
	inputmethodmanager.toggleSoftInput(0, 2);
}

2、隐藏软键盘

public static void hideSoftkeyboard(Activity activity)
{
	if(activity != null && activity.getCurrentFocus() != null)
	{
		InputMethodManager inputmethodmanager = (InputMethodManager)activity.getSystemService("input_method");
		if(inputmethodmanager != null)
		inputmethodmanager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 2);
	}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

Android单位px与dip相互转化

1、px转化为dip

public static int px2dip(Context context, float f)
{
return (int)(0.5F + f / context.getResources().getDisplayMetrics().density);
}

2、dip转化为px

public static int dip2px(Context context, float f)
{
return (int)(0.5F + f * context.getResources().getDisplayMetrics().density);
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

分类
Android开发

Android安装、卸载应用

1、安装下载的apk文件

/**
* 安装已下载应用
* @param mContext
* @param filePath apk文件路径
*/
public void installApp(Context mContext, String filePath){
java.io.File file = new java.io.File(filePath);
if(file.exists()){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
mContext.startActivity(intent);
}else {
Toast.makeText(mContext, "安装文件不存在", Toast.LENGTH_LONG).show();
}
}

2、卸载已安装应用

/**
* 卸载应用
* @param mContext
* @param packageName 安装应用包名
*/
public void unInstallApp(Context mContext, String packageName){
Uri packageURI = Uri.parse("package:"+packageName);
Intent intent = new Intent(Intent.ACTION_DELETE,packageURI);
mContext.startActivity(intent);
}

3、根据已下载apk文件获取应用包名

/**
* 获取apk文件包名
* @param mContext
* @param mFilePath apk文件路径
* @return
*/
public String getPackageNameFromApk(Context mContext, String mFilePath){
try {
PackageManager pm = mContext.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(mFilePath, PackageManager.GET_ACTIVITIES);
if(info != null){
ApplicationInfo appInfo = info.applicationInfo;
String packageName = appInfo.packageName;//得到安装包名称
return packageName;
}
} catch (Exception e) {
return "";
}
return "";
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。