반응형

안드로이드 타겟버전은 정하지않고 최소버전이 12인 상태에서 Theme.Holo.Light 테마를 쓰는 상태일경우

DatePickerDialog, DatePickerDialog가 앱이 죽는 현상 발생


현재 매니페스트 상태

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testdatepicker"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="12"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


해결방법

날짜

private void showCalendarDialog() {
Context context = null;
DatePickerDialog dialog = null;
Calendar calendar = Calendar.getInstance();

// 안드로이드 7.0버전부터 Theme.Holo.Light를 지원하지 않음
if (Build.VERSION.SDK_INT >= 24) {
context = new ContextThemeWrapper(mContext, android.R.style.Theme_DeviceDefault_Light_Dialog);
}else{
context = mContext;
}

dialog = new DatePickerDialog(context, mDateSetListener, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
dialog.show();
}


private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub

}

};


시간

private void showTimeDialog() {

Context context = null;
TimePickerDialog dialog = null;
Calendar calendar = Calendar.getInstance();

// 안드로이드 7.0버전부터 Theme.Holo.Light를 지원하지 않음
if (Build.VERSION.SDK_INT >= 24) {
context = new ContextThemeWrapper(mContext, android.R.style.Theme_DeviceDefault_Light_Dialog);
}else{
context = mContext;
}

dialog = new TimePickerDialog(context, mTimeSetListener, calendar.get(Calendar.HOUR_OF_DAY), 0, true);
dialog.show();
}

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub

}

};



어떤 테마스타일 이쁜지 확인하고 싶을경우

MainActivity.class


import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {
private final static boolean isShowDatePickerDialog = true; // DatePickerDialog 노출여부

private Context mContext = null;
private LinearLayout mLinearLayout = null;
private ListView mListView = null;
private int[] mStyleIdArr = {
android.R.style.Theme,
android.R.style.Theme_Black,
android.R.style.Theme_Black_NoTitleBar,
android.R.style.Theme_Black_NoTitleBar_Fullscreen,
android.R.style.Theme_DeviceDefault,
android.R.style.Theme_DeviceDefault_Dialog,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,
android.R.style.Theme_DeviceDefault_Dialog_NoActionBar,
android.R.style.Theme_DeviceDefault_Dialog_NoActionBar_MinWidth,
android.R.style.Theme_DeviceDefault_DialogWhenLarge,
android.R.style.Theme_DeviceDefault_DialogWhenLarge_NoActionBar,
android.R.style.Theme_DeviceDefault_InputMethod,
android.R.style.Theme_DeviceDefault_Light,
android.R.style.Theme_DeviceDefault_Light_DarkActionBar,
android.R.style.Theme_DeviceDefault_Light_Dialog,
android.R.style.Theme_DeviceDefault_Light_Dialog_MinWidth,
android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar,
android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar_MinWidth,
android.R.style.Theme_DeviceDefault_Light_DialogWhenLarge,
android.R.style.Theme_DeviceDefault_Light_DialogWhenLarge_NoActionBar,
android.R.style.Theme_DeviceDefault_Light_NoActionBar,
android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen,
android.R.style.Theme_DeviceDefault_Light_Panel,
android.R.style.Theme_DeviceDefault_NoActionBar,
android.R.style.Theme_DeviceDefault_NoActionBar_Fullscreen,
android.R.style.Theme_DeviceDefault_Panel,
android.R.style.Theme_DeviceDefault_Wallpaper,
android.R.style.Theme_DeviceDefault_Wallpaper_NoTitleBar,
android.R.style.Theme_Dialog, android.R.style.Theme_Holo,
android.R.style.Theme_Holo_Dialog,
android.R.style.Theme_Holo_Dialog_MinWidth,
android.R.style.Theme_Holo_Dialog_NoActionBar,
android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth,
android.R.style.Theme_Holo_DialogWhenLarge,
android.R.style.Theme_Holo_DialogWhenLarge_NoActionBar,
android.R.style.Theme_Holo_InputMethod,
android.R.style.Theme_Holo_Light,
android.R.style.Theme_Holo_Light_DarkActionBar,
android.R.style.Theme_Holo_Light_Dialog,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
android.R.style.Theme_Holo_Light_Dialog_NoActionBar,
android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth,
android.R.style.Theme_Holo_Light_DialogWhenLarge,
android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar,
android.R.style.Theme_Holo_Light_NoActionBar,
android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen,
android.R.style.Theme_Holo_Light_Panel,
android.R.style.Theme_Holo_NoActionBar,
android.R.style.Theme_Holo_NoActionBar_Fullscreen,
android.R.style.Theme_Holo_Panel,
android.R.style.Theme_Holo_Wallpaper,
android.R.style.Theme_Holo_Wallpaper_NoTitleBar,
android.R.style.Theme_InputMethod, android.R.style.Theme_Light,
android.R.style.Theme_Light_NoTitleBar,
android.R.style.Theme_Light_NoTitleBar_Fullscreen,
android.R.style.Theme_Light_Panel,
android.R.style.Theme_Light_WallpaperSettings,
android.R.style.Theme_NoDisplay, android.R.style.Theme_NoTitleBar,
android.R.style.Theme_NoTitleBar_Fullscreen,
android.R.style.Theme_NoTitleBar_OverlayActionModes,
android.R.style.Theme_Panel, android.R.style.Theme_Translucent,
android.R.style.Theme_Translucent_NoTitleBar,
android.R.style.Theme_Translucent_NoTitleBar_Fullscreen,
android.R.style.Theme_Wallpaper,
android.R.style.Theme_Wallpaper_NoTitleBar,
android.R.style.Theme_Wallpaper_NoTitleBar_Fullscreen,
android.R.style.Theme_WallpaperSettings,
android.R.style.Theme_WithActionBar };

private String[] mStyleNameArr = { "Theme", "Theme_Black",
"Theme_Black_NoTitleBar", "Theme_Black_NoTitleBar_Fullscreen",
"Theme_DeviceDefault", "Theme_DeviceDefault_Dialog",
"Theme_DeviceDefault_Dialog_MinWidth",
"Theme_DeviceDefault_Dialog_NoActionBar",
"Theme_DeviceDefault_Dialog_NoActionBar_MinWidth",
"Theme_DeviceDefault_DialogWhenLarge",
"Theme_DeviceDefault_DialogWhenLarge_NoActionBar",
"Theme_DeviceDefault_InputMethod", "Theme_DeviceDefault_Light",
"Theme_DeviceDefault_Light_DarkActionBar",
"Theme_DeviceDefault_Light_Dialog",
"Theme_DeviceDefault_Light_Dialog_MinWidth",
"Theme_DeviceDefault_Light_Dialog_NoActionBar",
"Theme_DeviceDefault_Light_Dialog_NoActionBar_MinWidth",
"Theme_DeviceDefault_Light_DialogWhenLarge",
"Theme_DeviceDefault_Light_DialogWhenLarge_NoActionBar",
"Theme_DeviceDefault_Light_NoActionBar",
"Theme_DeviceDefault_Light_NoActionBar_Fullscreen",
"Theme_DeviceDefault_Light_Panel",
"Theme_DeviceDefault_NoActionBar",
"Theme_DeviceDefault_NoActionBar_Fullscreen",
"Theme_DeviceDefault_Panel", "Theme_DeviceDefault_Wallpaper",
"Theme_DeviceDefault_Wallpaper_NoTitleBar", "Theme_Dialog",
"Theme_Holo", "Theme_Holo_Dialog", "Theme_Holo_Dialog_MinWidth",
"Theme_Holo_Dialog_NoActionBar",
"Theme_Holo_Dialog_NoActionBar_MinWidth",
"Theme_Holo_DialogWhenLarge",
"Theme_Holo_DialogWhenLarge_NoActionBar", "Theme_Holo_InputMethod",
"Theme_Holo_Light", "Theme_Holo_Light_DarkActionBar",
"Theme_Holo_Light_Dialog", "Theme_Holo_Light_Dialog_MinWidth",
"Theme_Holo_Light_Dialog_NoActionBar",
"Theme_Holo_Light_Dialog_NoActionBar_MinWidth",
"Theme_Holo_Light_DialogWhenLarge",
"Theme_Holo_Light_DialogWhenLarge_NoActionBar",
"Theme_Holo_Light_NoActionBar",
"Theme_Holo_Light_NoActionBar_Fullscreen",
"Theme_Holo_Light_Panel", "Theme_Holo_NoActionBar",
"Theme_Holo_NoActionBar_Fullscreen", "Theme_Holo_Panel",
"Theme_Holo_Wallpaper", "Theme_Holo_Wallpaper_NoTitleBar",
"Theme_InputMethod", "Theme_Light", "Theme_Light_NoTitleBar",
"Theme_Light_NoTitleBar_Fullscreen", "Theme_Light_Panel",
"Theme_Light_WallpaperSettings", "Theme_NoDisplay",
"Theme_NoTitleBar", "Theme_NoTitleBar_Fullscreen",
"Theme_NoTitleBar_OverlayActionModes", "Theme_Panel",
"Theme_Translucent", "Theme_Translucent_NoTitleBar",
"Theme_Translucent_NoTitleBar_Fullscreen", "Theme_Wallpaper",
"Theme_Wallpaper_NoTitleBar",
"Theme_Wallpaper_NoTitleBar_Fullscreen", "Theme_WallpaperSettings",
"Theme_WithActionBar" };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView = (ListView) findViewById(R.id.test_list);
for (int i = 0; i < mStyleIdArr.length; i++) {
Button btnButton = new Button(this);
btnButton.setText(mStyleNameArr[i]);
}
ArrayAdapter<String> testAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mStyleNameArr);
mListView.setAdapter(testAdapter);
mListView.setOnItemClickListener(this);

}

//날짜 다이얼로그
private void showCalendarDialog(int style) {
Calendar calendar = Calendar.getInstance();

DatePickerDialog dialog = null;

dialog = new DatePickerDialog(mContext, style, mDateSetListener,
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));

dialog.show();

}

//시간 다이얼로그
private void showTimeDialog(int style) {
Calendar calendar = Calendar.getInstance();
TimePickerDialog dialog = null;
dialog = new TimePickerDialog(mContext, style, mTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY), 0, true);

dialog.show();

}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub

}

};

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub

}

};

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "position" + position, Toast.LENGTH_SHORT).show();
if(isShowDatePickerDialog) {
showCalendarDialog(mStyleIdArr[position]);
}else{
showTimeDialog(mStyleIdArr[position]);
}
}


}


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >


<ListView
android:id="@+id/test_list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>

</RelativeLayout>


반응형
반응형

Random random = new Random();

//0~100 랜덤

int num1 = random.nextInt(100);

//1~100 랜덤

int num2 = random.nextInt(100)+1;

//50~100 랜덤

int num3 = random.nextInt(50)+51;

//70~100 랜덤

int num4 = random.nextInt(70)+31;

//20~30 랜덤

int num5 = random.nextInt(10)+21;

//100~120 랜덤

int num6 = random.nextInt(20)+101;

 System.out.println("1번 = "+num1);

 System.out.println("2번 = "+num2);

 System.out.println("3번 = "+num3); 

 System.out.println("4번 = "+num4); 

 System.out.println("5번 = "+num5); 

 System.out.println("6번 = "+num6);


결과

1번 = 41

2번 = 76

3번 = 67

4번 = 54

5번 = 28

6번 = 112



반응형

'Java' 카테고리의 다른 글

안드로이드 특수문자 체크 로직  (2) 2019.06.10
java 정렬  (0) 2017.05.23
java 파일용량 계산  (0) 2017.05.23
액티비티 할당된 메모리 즉시 반환하기  (0) 2016.01.12
Java Null Check 코드  (0) 2015.06.29
반응형


public class TestData {
private String name = null;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
/**
* 이름 정렬
* @param isSort true=내림차순 false=오름차순

*/
public static ArrayList<?> testNameSort(boolean isSort,ArrayList<?> list){
Comparator<Object> nameSortConparator= new Comparator<Object>() {

private final Collator collator = Collator.getInstance();

@Override

public int compare(Object object1, Object object2) {
int i = 0;
i = collator.compare(((TestData)object1).getName(), ((TestData)object2).getName());
return i;
}

};

if(list !=null)
{
//Comparator 를 만든다.
Collections.sort(list, nameSortConparator);
if(isSort) {
Collections.reverse(list);
}
}

return list;
}



반응형

'Java' 카테고리의 다른 글

안드로이드 특수문자 체크 로직  (2) 2019.06.10
자바 랜덤  (0) 2017.05.23
java 파일용량 계산  (0) 2017.05.23
액티비티 할당된 메모리 즉시 반환하기  (0) 2016.01.12
Java Null Check 코드  (0) 2015.06.29
반응형

/**파일 확장자 가져오기
* @param fileStr 경로나 파일이름
* @return*/
public static String getExtension(String fileStr){
String fileExtension = fileStr.substring(fileStr.lastIndexOf(".")+1,fileStr.length());
return TextUtils.isEmpty(fileExtension) ? null : fileExtension;
}

/**파일 이름 가져오기
* @param fileStr 파일 경로
* @param isExtension 확장자 포함 여부
* @return */
public static String getFileName(String fileStr , boolean isExtension){
String fileName = null;
if(isExtension)
{
fileName = fileStr.substring(fileStr.lastIndexOf("/"),fileStr.lastIndexOf("."));
}else{
fileName = fileStr.substring(fileStr.lastIndexOf("/")+1);
}
return fileName;
}


반응형
반응형


FileCache.java

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public interface FileCache {

public FileEntry get(String key);

public void put(String key, ByteProvider provider) throws IOException;

public void put(String key, InputStream is) throws IOException;

public void put(String key, File sourceFile, boolean move) throws IOException;

public void remove(String key);

public void clear();

public boolean has(String key);
}


FileEntry.java

public class FileEntry {

private String key;
private File file;

public FileEntry(String key, File file) {
this.key = key;
this.file = file;
}

public InputStream getInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}

public String getKey() {
return key;
}

public File getFile() {
return file;
}

}


FileCacheImpl.java

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class FileCacheImpl implements FileCache {

private CacheStorage cacheStorage;

public FileCacheImpl(File cacheDir, int maxKBSizes) {
long maxBytesSize = maxKBSizes <= 0 ? 0 : maxKBSizes * 1024;
cacheStorage = new CacheStorage(cacheDir, maxBytesSize);
}

@Override
public FileEntry get(String key) {
File file = cacheStorage.get(keyToFilename(key));
if (file == null) {
return null;
}
if (file.exists()) {
return new FileEntry(key, file);
}
return null;
}

@Override
public void put(String key, ByteProvider provider) throws IOException {
cacheStorage.write(keyToFilename(key), provider);
}

@Override
public void put(String key, InputStream is) throws IOException {
put(key, ByteProviderUtil.create(is));
}

@Override
public void put(String key, File sourceFile, boolean move)
throws IOException {
if (move) {
cacheStorage.move(keyToFilename(key), sourceFile);
} else {
put(key, ByteProviderUtil.create(sourceFile));
}
}

@Override
public void remove(String key) {
cacheStorage.delete(keyToFilename(key));
}

private String keyToFilename(String key) {
String filename = key.replace(":", "_");
filename = filename.replace("/", "_s_");
filename = filename.replace("\\", "_bs_");
filename = filename.replace("&", "_bs_");
filename = filename.replace("*", "_start_");
filename = filename.replace("?", "_q_");
filename = filename.replace("|", "_or_");
filename = filename.replace(">", "_gt_");
filename = filename.replace("<", "_lt_");
return filename;
}

@Override
public void clear() {
cacheStorage.deleteAll();
}

@Override
public boolean has(String key) {
return cacheStorage.has(key);
}


}


IOUtils.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public abstract class IOUtils {

public static String read(InputStream is) throws IOException {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
char[] readDate = new char[1024];
int len = -1;
while ((len = reader.read(readDate)) != -1) {
builder.append(readDate, 0, len);
}
return builder.toString();
} finally {
close(reader);
}
}

public static void copy(InputStream is, OutputStream out)
throws IOException {
byte[] buff = new byte[4096];
int len = -1;
while ((len = is.read(buff)) != -1) {
out.write(buff, 0, len);
}
}


public static void copy(File source, OutputStream os) throws IOException {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(source));
IOUtils.copy(is, os);
} finally {
IOUtils.close(is);
}
}

public static void copy(InputStream is, File target) throws IOException {
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(target));
IOUtils.copy(is, os);
} finally {
IOUtils.close(os);
}
}

public static void copy(String str, OutputStream os) throws IOException {
os.write(str.getBytes());
}

public static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}

}


FileCacheFactory.java

import android.content.Context;
import java.io.File;
import java.util.HashMap;

public class FileCacheFactory {

private static boolean initialized = false;
private static FileCacheFactory instance = new FileCacheFactory();

public static void initialize(Context context, String file_dir) {
if (!initialized) {
synchronized (instance) {
if (!initialized) {
instance.init(context,file_dir);
initialized = true;
}
}
}
}

public static FileCacheFactory getInstance() {
if (!initialized) {
throw new IllegalStateException(
"Not initialized. You must call FileCacheFactory.initialize() before getInstance()");
}
return instance;
}

private HashMap<String, FileCache> mCacheMap = new HashMap<String, FileCache>();
private File mCacheBaseDir;

private FileCacheFactory() {
}

private void init(Context context) {
mCacheBaseDir = context.getCacheDir();
}

private void init(Context context, String file_dir) {
// cacheBaseDir = context.getCacheDir();
mCacheBaseDir = new File(file_dir);
}

public FileCache create(String cacheName, int maxKbSizes) {
synchronized (mCacheMap) {
FileCache cache = mCacheMap.get(cacheName);
File cacheDir = new File(mCacheBaseDir, cacheName);
if (cache != null) {
try {
cache = new FileCacheImpl(cacheDir, maxKbSizes);
mCacheMap.put(cacheName, cache);
} catch (Exception e) {
String.format("FileCache[%s] Aleady exists", cacheName);
}
}


return cache;
}
}

public FileCache get(String cacheName) {
synchronized (mCacheMap) {
FileCache cache = mCacheMap.get(cacheName);
if (cache == null) {
try {

}catch (Exception e)
{
String.format("FileCache[%s] not founds.", cacheName);
}
}
return cache;
}
}

public void destroy(String cacheName)
{
FileCache cache = mCacheMap.get(cacheName);

File file = new File(mCacheBaseDir+File.separator+cacheName);
if(file.exists())
{
file.delete();
}
}

public void clear(){
mCacheMap.clear();
}

public boolean has(String cacheName) {
return mCacheMap.containsKey(cacheName);
}
}

설명

캐시 디렉토리 안에 캐시파일이 여러개 저장되는 방식입니다. 


사용방법

1. 캐시 디렉토리

private FileCache mFileCache = null;

public static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "FolderName" + File.separator + ".cache"; //캐시 기본폴더

FileCacheFactory.initialize(mContext, CACHE_PATH);
if (!FileCacheFactory.getInstance().has(zipDirName)) // 해당 키의 캐시 디렉토리가 있는지 확인
{
FileCacheFactory.getInstance().create(zipDirName, 0); // 캐시디렉토리가 없을경우 만든다.
}
mFileCache = FileCacheFactory.getInstance().get(zipDirName); // 해당 파일의 캐시 디렉토리를 가져온다.


- 캐시 객체 생성

FileCacheFactory.initialize(mContext, CACHE_PATH);

- 캐시디렉토리 존재 여부 체크

FileCacheFactory.getInstance().has(Dirkey)

- 캐시디렉토리 생성

FileCacheFactory.getInstance().create(Dirkey, 0); // 캐시디렉토리가 없을경우 만든다.

- 캐시디렉토리 가져오기

mFileCache = FileCacheFactory.getInstance().get(Dirkey); // 해당 파일의 캐시 디렉토리를 가져온다.


2. 캐시 

-캐시 저장

/**
* @param key cache
* @param val cache 내용
* @param isMove ture = val파일이 캐시경로로 이동됨, false = val파일이 캐시경로로 복사됨
*/
private void setCacheFile(String key, File val, boolean isMove) {
if (!mFileCache.has(key)) {
try {
mFileCache.put(key, val, isMove);
} catch (IOException e) {
e.printStackTrace();
}
}
}

-캐시 가져오기

/**
* 캐시내용을 가져온다.
* @param key cache
* @return
*/
public FileEntry getCacheFile(String key) {

return mFileCache.get(key);
}


chche.zip


반응형
반응형
/**
* 용량계산
* @param size
* @return
*/
public static String sizeCalculation(long size) {
String CalcuSize = null;
int i = 0;

double calcu = (double) size;
while (calcu >= 1024 && i < 5) { // 단위 숫자로 나누고 한번 나눌 때마다 i 증가
calcu = calcu / 1024;
i++;
}
DecimalFormat df = new DecimalFormat("##0.0");
switch (i) {
case 0:
CalcuSize = df.format(calcu) + "Byte";
break;
case 1:
CalcuSize = df.format(calcu) + "KB";
break;
case 2:
CalcuSize = df.format(calcu) + "MB";
break;
case 3:
CalcuSize = df.format(calcu) + "GB";
break;
case 4:
CalcuSize = df.format(calcu) + "TB";
break;
default:
CalcuSize="ZZ"; //용량표시 불가

}
return CalcuSize;
}




반응형

'Java' 카테고리의 다른 글

자바 랜덤  (0) 2017.05.23
java 정렬  (0) 2017.05.23
액티비티 할당된 메모리 즉시 반환하기  (0) 2016.01.12
Java Null Check 코드  (0) 2015.06.29
Java 인스턴스 하나만 사용하기(싱글턴 패턴)  (0) 2015.06.29
반응형

Apache Commons Compress 1.14

라이브러리를 import 해줍니다.

jar파일 다운로드 url


import org.apache.commons.compress.utils.IOUtils;

/**
* 파일 복사
*
* @return exist 복사 성공 여부

*/
public synchronized boolean copyFile(String inFilePath, String outFilePath) {
FileInputStream fis = null;
FileOutputStream fos = null;
File file = null;
boolean exist = false;
try {
fis = new FileInputStream(inFilePath);
fos = new FileOutputStream(outFilePath);
IOUtils.copy(fis, fos);

file = new File(outFilePath);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
// 마지막에 FileInputStream / FileOutputStream을 닫아준다.
if (fis != null) try {
fis.close();
}
catch (IOException e) {
Log.i("파일복사", "fileInput error");
}

if (fos != null)
try {
fos.close();
}
catch (IOException e) {
Log.i("파일복사", "fileOutput error");
}
if (file != null) {                 // 복사한 경로에 File있는지 확인
if (file.exists()) {
exist = true;
}
else {
exist = false;
}
}

}
return exist;
}



반응형
반응형

이번에 알림기능을 넣고 앱을 테스트 하면서

안드로이드 ics 버전에서 앱이 죽는 현상이 발생하여 다음과 같이 해결

public static void ViewNotice(String notiTitle ,String notiContent,Context context){ NotificationManager mNM; mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);         Intent mI = new Intent(); mI.setClass(context, NotiViewActivity.class); mI.putExtra("NOTICE", notiContent); mI.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mI, PendingIntent.FLAG_UPDATE_CURRENT);     Notification notification = null;                 //안드로이드 버전 체크 if(Build.VERSION_CODES.KITKAT<Build.VERSION.SDK_INT){                     //킷켓보다 버전 보다 높을 경우

Notification.Builder builder = new Notification.Builder(context); builder.setSmallIcon(R.drawable.icon_t); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle("공지 제목"); builder.setContentText("공지 내용"); builder.setContentIntent(contentIntent); notification = builder.build(); }else{                     //킷켓 버전이하일 경우

    notification = new Notification(R.drawable.icon_t, null, System.currentTimeMillis());     notification.setLatestEventInfo(context, "공지 제목","공지 내용", contentIntent); } notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE; notification.defaults |= Notification.DEFAULT_SOUND; mNM.notify(0, notification); }


특정버전 이하에서는 Notification notification = builder.build(); 지원하지 않는것 같음

안드로이드 ics 버전에서는 다음과 같이 정의하면 오류가 나지 않는다.

		    notification = new Notification(R.drawable.icon_t, null, System.currentTimeMillis());
	            notification.setLatestEventInfo(context, "공지 제목","공지 내용", contentIntent);




반응형

+ Recent posts