【移動應用開發(fā)技術】Android開發(fā)中常用到的工具類有哪些_第1頁
【移動應用開發(fā)技術】Android開發(fā)中常用到的工具類有哪些_第2頁
【移動應用開發(fā)技術】Android開發(fā)中常用到的工具類有哪些_第3頁
【移動應用開發(fā)技術】Android開發(fā)中常用到的工具類有哪些_第4頁
【移動應用開發(fā)技術】Android開發(fā)中常用到的工具類有哪些_第5頁
已閱讀5頁,還剩5頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

【移動應用開發(fā)技術】Android開發(fā)中常用到的工具類有哪些

這篇文章給大家介紹Android開發(fā)中常用到的工具類有哪些,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。作為一個程序員界的新晉司機,也是時候整理一些東西了,兩三年的路走來,代碼也是邊寫邊忘、邊走邊丟,很多問題忙著忙著就忘了,決定寫點隨筆供自己閑余時間回望,有需要的讀者也可以隨意瞄幾眼,哪里有錯有問題可以提出來,雖然我不見得會改,O(∩_∩)O哈哈~日常開發(fā)中很多東西都是寫過無數(shù)遍的,我本人沒有每次都去重新寫的習慣(不知道有沒有小伙伴會如此耿直??)那么整理好自己的工具類還是有必要的。這里就記錄幾個目前為止我使用較多的。常用工具類

/**

*

根據(jù)手機的分辨率從

dp

的單位

轉成為

px(像素)

*/

public

static

int

dip2px(Context

context,

float

dpValue)

{

final

float

scale

=

context.getResources().getDisplayMetrics().density;

return

(int)

(dpValue

*

scale

+

0.5f);

}

/**

*

根據(jù)手機的分辨率從

px(像素)

的單位

轉成為

dp

*/

public

static

int

px2dip(Context

context,

float

pxValue)

{

final

float

scale

=

context.getResources().getDisplayMetrics().density;

return

(int)

(pxValue

/

scale

+

0.5f);

}

/**

*

Md5

32位

or

16位

加密

*

*

@param

plainText

*

@return

32位加密

*/

public

static

String

Md5(String

plainText)

{

StringBuffer

buf

=

null;

try

{

MessageDigest

md

=

MessageDigest.getInstance("MD5");

md.update(plainText.getBytes());

byte

b[]

=

md.digest();

int

i;

buf

=

new

StringBuffer("");

for

(int

offset

=

0;

offset

<

b.length;

offset++)

{

i

=

b[offset];

if

(i

<

0)

i

+=

256;

if

(i

<

16)

buf.append("0");

buf.append(Integer.toHexString(i));

}

}

catch

(NoSuchAlgorithmException

e)

{

e.printStackTrace();

}

return

buf.toString();

}

/**

*

手機號正則判斷

*

@param

str

*

@return

*

@throws

PatternSyntaxException

*/

public

static

boolean

isPhoneNumber(String

str)

throws

PatternSyntaxException

{

if

(str

!=

null)

{

String

pattern

=

"(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}";

Pattern

r

=

Ppile(pattern);

Matcher

m

=

r.matcher(str);

return

m.matches();

}

else

{

return

false;

}

}

/**

*

檢測當前網絡的類型

是否是wifi

*

*

@param

context

*

@return

*/

public

static

int

checkedNetWorkType(Context

context)

{

if

(!checkedNetWork(context))

{

return

0;//無網絡

}

ConnectivityManager

cm

=

(ConnectivityManager)

context.getSystemService(Context.CONNECTIVITY_SERVICE);

if

(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting())

{

return

1;//wifi

}

else

{

return

2;//非wifi

}

}

/**

*

檢查是否連接網絡

*

*

@param

context

*

@return

*/

public

static

boolean

checkedNetWork(Context

context)

{

//

獲得連接設備管理器

ConnectivityManager

cm

=

(ConnectivityManager)

context.getSystemService(Context.CONNECTIVITY_SERVICE);

if

(cm

==

null)

return

false;

/**

*

獲取網絡連接對象

*/

NetworkInfo

networkInfo

=

cm.getActiveNetworkInfo();

if

(networkInfo

==

null

||

!networkInfo.isAvailable())

{

return

false;

}

return

true;

}

/**

*

檢測GPS是否打開

*

*

@return

*/

public

static

boolean

checkGPSIsOpen(Context

context)

{

boolean

isOpen;

LocationManager

locationManager

=

(LocationManager)

context

.getSystemService(Context.LOCATION_SERVICE);

if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){

isOpen=true;

}else{

isOpen

=

false;

}

return

isOpen;

}

/**

*

跳轉GPS設置

*/

public

static

void

openGPSSettings(final

Context

context)

{

if

(checkGPSIsOpen(context))

{

//

initLocation();

//自己寫的定位方法

}

else

{

//

//沒有打開則彈出對話框

AlertDialog.Builder

builder

=

new

AlertDialog.Builder(context,

R.style.AlertDialogCustom);

builder.setTitle("溫馨提示");

builder.setMessage("當前應用需要打開定位功能。請點擊\"設置\"-\"定位服務\"打開定位功能。");

//設置對話框是可取消的

builder.setCancelable(false);

builder.setPositiveButton("設置",

new

DialogInterface.OnClickListener()

{

@Override

public

void

onClick(DialogInterface

dialogInterface,

int

i)

{

dialogInterface.dismiss();

//跳轉GPS設置界面

Intent

intent

=

new

Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

context.startActivity(intent);

}

});

builder.setNegativeButton("取消",

new

DialogInterface.OnClickListener()

{

@Override

public

void

onClick(DialogInterface

dialogInterface,

int

i)

{

dialogInterface.dismiss();

ActivityManager.getInstance().exit();

}

});

AlertDialog

alertDialog

=

builder.create();

alertDialog.show();

}

}

/**

*

字符串進行Base64編碼

*

@param

str

*/

public

static

String

StringToBase64(String

str){

String

encodedString

=

Base64.encodeToString(str.getBytes(),

Base64.DEFAULT);

return

encodedString;

}

/**

*

字符串進行Base64解碼

*

@param

encodedString

*

@return

*/

public

static

String

Base64ToString(String

encodedString){

String

decodedString

=new

String(Base64.decode(encodedString,Base64.DEFAULT));

return

decodedString;

}這里還有一個根據(jù)經緯度計算兩點間真實距離的,一般都直接使用所集成第三方地圖SDK中包含的方法,這里還是給出代碼/**

*

補充:計算兩點之間真實距離

*

*

@return

*/

public

static

double

getDistance(double

longitude1,

double

latitude1,

double

longitude2,

double

latitude2)

{

//

維度

double

lat1

=

(Math.PI

/

180)

*

latitude1;

double

lat2

=

(Math.PI

/

180)

*

latitude2;

//

經度

double

lon1

=

(Math.PI

/

180)

*

longitude1;

double

lon2

=

(Math.PI

/

180)

*

longitude2;

//

地球半徑

double

R

=

6371;

//

兩點間距離

km,如果想要米的話,結果*1000就可以了

double

d

=

Math.acos(Math.sin(lat1)

*

Math.sin(lat2)

+

Math.cos(lat1)

*

Math.cos(lat2)

*

Math.cos(lon2

-

lon1))

*

R;

return

d

*

1000;

}常用文件類文件類的代碼較多,這里就只給出讀寫文件的/**

*

判斷SD卡是否可用

*

@return

SD卡可用返回true

*/

public

static

boolean

hasSdcard()

{

String

status

=

Environment.getExternalStorageState();

return

Environment.MEDIA_MOUNTED.equals(status);

}

/**

*

讀取文件的內容

*

<br>

*

默認utf-8編碼

*

@param

filePath

文件路徑

*

@return

字符串

*

@throws

IOException

*/

public

static

String

readFile(String

filePath)

throws

IOException

{

return

readFile(filePath,

"utf-8");

}

/**

*

讀取文件的內容

*

@param

filePath

文件目錄

*

@param

charsetName

字符編碼

*

@return

String字符串

*/

public

static

String

readFile(String

filePath,

String

charsetName)

throws

IOException

{

if

(TextUtils.isEmpty(filePath))

return

null;

if

(TextUtils.isEmpty(charsetName))

charsetName

=

"utf-8";

File

file

=

new

File(filePath);

StringBuilder

fileContent

=

new

StringBuilder("");

if

(file

==

null

||

!file.isFile())

return

null;

BufferedReader

reader

=

null;

try

{

InputStreamReader

is

=

new

InputStreamReader(new

FileInputStream(

file),

charsetName);

reader

=

new

BufferedReader(is);

String

line

=

null;

while

((line

=

reader.readLine())

!=

null)

{

if

(!fileContent.toString().equals(""))

{

fileContent.append("\r\n");

}

fileContent.append(line);

}

return

fileContent.toString();

}

finally

{

if

(reader

!=

null)

{

try

{

reader.close();

}

catch

(IOException

e)

{

e.printStackTrace();

}

}

}

}

/**

*

讀取文本文件到List字符串集合中(默認utf-8編碼)

*

@param

filePath

文件目錄

*

@return

文件不存在返回null,否則返回字符串集合

*

@throws

IOException

*/

public

static

List<String>

readFileToList(String

filePath)

throws

IOException

{

return

readFileToList(filePath,

"utf-8");

}

/**

*

讀取文本文件到List字符串集合中

*

@param

filePath

文件目錄

*

@param

charsetName

字符編碼

*

@return

文件不存在返回null,否則返回字符串集合

*/

public

static

List<String>

readFileToList(String

filePath,

String

charsetName)

throws

IOException

{

if

(TextUtils.isEmpty(filePath))

return

null;

if

(TextUtils.isEmpty(charsetName))

charsetName

=

"utf-8";

File

file

=

new

File(filePath);

List<String>

fileContent

=

new

ArrayList<String>();

if

(file

==

null

||

!file.isFile())

{

return

null;

}

BufferedReader

reader

=

null;

try

{

InputStreamReader

is

=

new

InputStreamReader(new

FileInputStream(

file),

charsetName);

reader

=

new

BufferedReader(is);

String

line

=

null;

while

((line

=

reader.readLine())

!=

null)

{

fileContent.add(line);

}

return

fileContent;

}

finally

{

if

(reader

!=

null)

{

try

{

reader.close();

}

catch

(IOException

e)

{

e.printStackTrace();

}

}

}

}

/**

*

向文件中寫入數(shù)據(jù)

*

@param

filePath

文件目錄

*

@param

content

要寫入的內容

*

@param

append

如果為

true,則將數(shù)據(jù)寫入文件末尾處,而不是寫入文件開始處

*

@return

寫入成功返回true,

寫入失敗返回false

*

@throws

IOException

*/

public

static

boolean

writeFile(String

filePath,

String

content,

boolean

append)

throws

IOException

{

if

(TextUtils.isEmpty(filePath))

return

false;

if

(TextUtils.isEmpty(content))

return

false;

FileWriter

fileWriter

=

null;

try

{

createFile(filePath);

fileWriter

=

new

FileWriter(filePath,

append);

fileWriter.write(content);

fileWriter.flush();

return

true;

}

finally

{

if

(fileWriter

!=

null)

{

try

{

fileWriter.close();

}

catch

(IOException

e)

{

e.printStackTrace();

}

}

}

}

/**

*

向文件中寫入數(shù)據(jù)<br>

*

默認在文件開始處重新寫入數(shù)據(jù)

*

@param

filePath

文件目錄

*

@param

stream

字節(jié)輸入流

*

@return

寫入成功返回true,否則返回false

*

@throws

IOException

*/

public

static

boolean

writeFile(String

filePath,

InputStream

stream)

throws

IOException

{

return

writeFile(filePath,

stream,

false);

}

/**

*

向文件中寫入數(shù)據(jù)

*

@param

filePath

文件目錄

*

@param

stream

字節(jié)輸入流

*

@param

append

如果為

true,則將數(shù)據(jù)寫入文件末尾處;

*

為false時,清空原來的數(shù)據(jù),從頭開始寫

*

@return

寫入成功返回true,否則返回false

*

@throws

IOException

*/

public

static

boolean

writeFile(String

filePath,

InputStream

stream,

boolean

append)

throws

IOException

{

if

(TextUtils.isEmpty(filePath))

throw

new

NullPointerException("filePath

is

Empty");

if

(stream

==

null)

throw

new

NullPointerException("InputStream

is

null");

return

writeFile(new

File(filePath),

stream,

append);

}

/**

*

向文件中寫入數(shù)據(jù)

*

默認在文件開始處重新寫入數(shù)據(jù)

*

@param

file

指定文件

*

@param

stream

字節(jié)輸入流

*

@return

寫入成功返回true,否則返回false

*

@throws

IOException

*/

public

static

boolean

writeFile(File

file,

InputStream

stream)

throws

IOException

{

return

writeFile(file,

stream,

false);

}

/**

*

向文件中寫入數(shù)據(jù)

*

@param

file

指定文件

*

@param

stream

字節(jié)輸入流

*

@param

append

為true時,在文件開始處重新寫入數(shù)據(jù);

*

為false時,清空原來的數(shù)據(jù),從頭開始寫

*

@return

寫入成功返回true,否則返回false

*

@throws

IOException

*/

public

static

boolean

writeFile(File

file,

InputStream

stream,

boolean

append)

throws

IOException

{

if

(file

==

null)

throw

new

NullPointerException("file

=

null");

OutputStream

out

=

null;

try

{

createFile(file.getAbsolutePath());

out

=

new

FileOutputStream(file,

append);

byte

data[]

=

new

byte[1024];

int

length

=

-1;

while

((length

=

stream.read(data))

!=

-1)

{

out.write(data,

0,

length);

}

out.flush();

return

true;

}

finally

{

if

(out

!=

null)

{

try

{

out.close();

stream.close();

}

catch

(IOException

e)

{

e.printStackTrace();

}

}

}

}日期工具類/**

*

將long時間轉成yyyy-MM-dd

HH:mm:ss字符串<br>

*

@param

timeInMillis

時間long值

*

@return

yyyy-MM-dd

HH:mm:ss

*/

public

static

String

getDateTimeFromMillis(long

timeInMillis)

{

return

getDateTimeFormat(new

Date(timeInMillis));

}

/**

*

將date轉成yyyy-MM-dd

HH:mm:ss字符串

*

<br>

*

@param

date

Date對象

*

@return

yyyy-MM-dd

HH:mm:ss

*/

public

static

String

getDateTimeFormat(Date

date)

{

return

dateSimpleFormat(date,

defaultDateTimeFormat.get());

}

/**

*

將年月日的int轉成yyyy-MM-dd的字符串

*

@param

year

*

@param

month

1-12

*

@param

day

*

注:月表示Calendar的月,比實際小1

*

對輸入項未做判斷

*/

public

static

String

getDateFormat(int

year,

int

month,

int

day)

{

return

getDateFormat(getDate(year,

month,

day));

}

/**

*

獲得HH:mm:ss的時間

*

@param

date

*

@return

*/

public

static

String

getTimeFormat(Date

date)

{

return

dateSimpleFormat(date,

defaultTimeFormat.get());

}

/**

*

格式化日期顯示格式

*

@param

sdate

原始日期格式

"yyyy-MM-dd"

*

@param

format

格式化后日期格式

*

@return

格式化后的日期顯示

*/

public

static

String

dateFormat(String

sdate,

String

format)

{

SimpleDateFormat

formatter

=

new

SimpleDateFormat(format);

java.sql.Date

date

=

java.sql.Date.valueOf(sdate);

return

dateSimpleFormat(date,

formatter);

}

/**

*

格式化日期顯示格式

*

@param

date

Date對象

*

@param

format

格式化后日期格式

*

@return

格式化后的日期顯示

*/

public

static

String

dateFormat(Date

date,

String

format)

{

SimpleDateFormat

formatter

=

new

SimpleDateFormat(format);

return

dateSimpleFormat(date,

formatter);

}

/**

*

將date轉成字符串

*

@param

date

Date

*

@param

format

SimpleDateFormat

*

<br>

*

注:

SimpleDateFormat為空時,采用默認的yyyy-MM-dd

HH:mm:ss格式

*

@return

yyyy-MM-dd

HH:mm:ss

*/

public

static

String

dateSimpleFormat(Date

date,

SimpleDateFormat

format)

{

if

(format

==

null)

format

=

defaultDateTimeFormat.get();

return

(date

==

null

?

""

:

format.format(date));

}

/**

*

將"yyyy-MM-dd

HH:mm:ss"

格式的字符串轉成Date

*

@param

strDate

時間字符串

*

@return

Date

*/

public

static

Date

getDateByDateTimeFormat(String

strDate)

{

return

getDateByFormat(strDate,

defaultDateTimeFormat.get());

}

/**

*

將"yyyy-MM-dd"

格式的字符串轉成Date

*

@param

strDate

*

@return

Date

*/

public

static

Date

getDateByDateFormat(String

strDate)

{

return

getDateByFormat(strDate,

defaultDateFormat.get());

}

/**

*

將指定格式的時間字符串轉成Date對象

*

@param

strDate

時間字符串

*

@param

format

格式化字符串

*

@return

Date

*/

public

static

Date

getDateByFormat(String

strDate,

String

format)

{

return

getDateByFormat(strDate,

new

SimpleDateFormat(format));

}

/**

*

將String字符串按照一定格式轉成Date<br>

*

注:

SimpleDateFormat為空時,采用默認的yyyy-MM-dd

HH:mm:ss格式

*

@param

strDate

時間字符串

*

@param

format

SimpleDateFormat對象

*

@exception

ParseException

日期格式轉換出錯

*/

private

static

Date

getDateByFormat(String

strDate,

SimpleDateFormat

format)

{

if

(format

==

null)

format

=

defaultDateTimeFormat.get();

try

{

return

format.parse(strDate);

}

catch

(ParseException

e)

{

e.printStackTrace();

}

return

null;

}

/**

*

將年月日的int轉成date

*

@param

year

*

@param

month

1-12

*

@param

day

*

注:月表示Calendar的月,比實際小1

*/

public

static

Date

getDate(int

year,

int

month,

int

day)

{

Calendar

mCalendar

=

Calendar.getInstance();

mCalendar.set(year,

month

-

1,

day);

return

mCalendar.getTime();

}

/**

*

求兩個日期相差天數(shù)

*

*

@param

strat

起始日期,格式y(tǒng)yyy-MM-dd

*

@param

end

終止日期,格式y(tǒng)yyy-MM-dd

*

@return

兩個日期相差天數(shù)

*/

public

static

long

getIntervalDays(String

strat,

String

end)

{

return

((java.sql.Date.valueOf(end)).getTime()

-

(java.sql.Date

.valueOf(strat)).getTime())

/

(3600

*

24

*

1000);

}

/**

*

獲得當前年份

*

@return

year(int)

*/

public

static

int

getCurrentYear()

{

Calendar

mCalendar

=

Calendar.getInstance();

return

mCalendar.get(Calendar.YEAR);

}

/**

*

獲得當前月份

*

@return

month(int)

1-12

*/

public

static

int

getCurrentMonth()

{

Calendar

mCalendar

=

Calendar.getInstance();

return

mCalendar.get(Calendar.MONTH)

+

1;

}

/**

*

獲得當月幾號

*

@return

day(int)

*/

public

static

int

getDayOfMonth()

{

Calen

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論