레이블이 Android Develop인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Android Develop인 게시물을 표시합니다. 모든 게시물 표시

2022년 12월 17일 토요일

Java LTrim RTrim 처리 방법

 Java 언어는 많은 지원 함수를 제공합니다.

그런데 trim 함수는 전체 trim 함수 밖에 제공을 안하네요

해서 LeftTrim 만 또는 RightTrim만 처리 하는 방법을 알아 보겠습니다.

<처리방법 1>

문자열을 뒤에서 부터 또는 앞에서 부터 공백을 찾아 지우는 방법입니다.

//Left Trim
String sLTemp = " Left Trim";
int nIdx = 0;
while(nIdx < sLTemp.length() && Character.isWhitespace(sLTemp.charAt(nIdx)))
{
  nIdx++;
}

String sLResult = sLTemp.substring(nIdx);
System.out.println(String.format("Left Trim [%s] ==> [%s]", sLTemp, sLResult));

//Right Trim
String sRTemp = "Right Trim ";
nIdx = sRTemp.length() - 1;
while(nIdx >= sRTemp .length() && Character.isWhitespace(sRTemp .charAt(nIdx)))
{
  nIdx--;
}

String sRResult = sRTemp.substring(0, nIdx+1);
System.out.println(String.format("Right Trim [%s] ==> [%s]", sRTemp, sRResult));

<처리방법 2>

regex 를 이용하여 전체 바꾸는 방법입니다.

String sLTemp = " Left Trim", sRTemp = "Right Trim";
String sLResult = sLTemp.replaceAll("^\\s+", "");
String sRResult = sRTemp .replaceAll("\\s+$", "");

System.out.println(String.format("Left Trim [%s] ==> [%s]", sLTemp, sLResult));
System.out.println(String.format("Right Trim [%s] ==> [%s]", sRTemp, sRResult));

그외에도 다른 방법(Pattern 등)을 사용할수 있습니다.

그럼 ^^

2022년 8월 27일 토요일

Android 절전모드 사용 체크

 Android 폰을 절전모드를 기본을 사용하는 폰을 위해 체크 하는 코드를 가이드 합니다.

절전모드를 쓰는 폰들은 앱이 백그라운드로 내려갈때 일부 자원(네트워크 등)이 바로 다시 회수 되지 않기 떄문에

문제가 발생할 소지가 있습니다.

그에 따른 적절한 조치를 하기 위해서는 해당 모드를 쓰고 있는지 체크 하고 그것에 따른 예외 처리를 추가 해야 합니다.


PowerManager oPM = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (oPM != null)
{
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && oPM.isPowerSaveMode())
	{
		//절전모드 사용.
	}
}

그럼 ^^

Android 갤러리 이미지 가져오기

 Android 앱 개발시 자신의 갤러리 이미지를 가져오는 기능을 개발하는 경우가 있습니다.

Android O/S 버젼이 올라가면서 접근 제한이 많이 일어나고 갤러리 프로그램도 로컬 방식이 아닌

클라우드 방식(구글포토) 을 쓰는것들도 있기 때문에 그것들에 대한 처리 가이드를 안내하려 합니다.

코드는 Java로 구성 되어 있습니다.

일단 Android 주 앱 소스에 AndroidManifest.xml 에 권한을 추가 합니다.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

갤러리 호출은 Intent 를 통해서 호출하여 가져 올수 있습니다.

아래 코드를 Activity Content 를 통해서 호출 합니다.

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 ((Activity)m_oContext).startActivityForResult(i, 1);

startActivityForResult 호출시 두번째 인자는 호출후 돌려받는 리턴 코드값입니다.

편의상 1 로 설정 했습니다.

갤러리 호출후 리턴받는 곳은 활성화된 Activity 에서 돌려 받아 처리 합니다.

코드는 아래와 같습니다.


@Override
protected void onActivityResult(int nReqCode, int nRetCode, @Nullable Intent data)
{
    super.onActivityResult(nReqCode, nRetCode, data);

    switch (nReqCode)
    {
        case 1://Gallery
        {
            if (nRetCode == RESULT_OK && data != null)
            {
                Bitmap bmImage = null;
                try
                {
                    Uri oSelectImg = data.getData();
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P)
                    {
                        bmImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), oSelectImg);
                    }
                    else
                    {
                        ImageDecoder.Source oSrc = ImageDecoder.createSource(this.getContentResolver(), oSelectImg);
                        bmImage = ImageDecoder.decodeBitmap(oSrc);
                    }

                    if(m_oTestMainView != null)
                    {
                        m_oTestMainView.m_oImgGallery.setImageBitmap(bmImage);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            else if(nRetCode == RESULT_CANCELED)
            {
                Toast.makeText(this, "사진 선택 취소", Toast.LENGTH_LONG).show();
            }
        }break;
    }
}

"m_oTestMainView" 는 별도로 구성된 LinearLayout 입니다. 그 안에 ImageVIew m_oImgGallery 를 만들어 놓고 불러들인 갤러리 이미지를 비트맵 으로 셋팅하면 이미지가 나옵니다.

갤러리 이미지는 직접 Uri 경로로 접근해서 읽어 들일수도 있으나 위에서 언급한것처럼 클라우드 기반 갤러리는 경로를 가져올수 없습니다.

그래서 범용적으로 처리를 하시려면 Bitmap 을 자기 앱 경로에 직접 이미지 파일로 저장하여 처리 하는것을 권장합니다.

Bitmap 을 이미지 파일로 저장 하시려면

저장할 File의 OutputStream 을 만들고 아래 코드를 호출하여 저장하시면 됩니다.


File oFile = new File(context.getFilesDir(), '저장상대경로');
OutputStream osFile = new FileOutputStream(oFile);
bmImage.compress(Bitmap.CompressFormat.PNG, 100, osFile);

그럼 ^^

2020년 9월 16일 수요일

Android Souce Inspect 사용예

 Android 개발을 하다 보면 기준 API를 지정하고 지정된 API 이상 사용되지 않게 작업을 합니다.

하지만 여러 개발자가 같이 작업을 하다 보면 이 기준이 어긋날때가 있기 때문에 이걸 검증하고 수정하는

방법을 이야기 할까 합니다.

첫번째로 minsdk 를 지정하고 이것보다 높은 함수를 사용할때 개발을 하고 나면 빌드는 되지만 조건이 충족되지 않는 폰에서는 에러가 발생하며 앱이 크래쉬가 일어 날겁니다.

검증하는 방법은

Android Studio Menu에서 "Analyze" -> "Inspect Code" 를 누릅니다.

누르고 나면 한참동안 작업을 한후 결과창에 Inspect된 내용이 보일겁니다.

위 내용에 해당하는것은 아래 경로로 가시면 확인할수 있습니다.

Android -> Lint -> Correctness -> Calling new methods on older versions

두번쨰로는 depercate 된 API를 처리하는 찾아내어 수정하는 방법입니다.

첫번쨰와 마찬가지로 Inspect Code 를 누르시고나서 결과창에

Java -> Code maturity -> Deprecated API usage

위 내용으로 걸러지는 내용을 수정하시면 됩니다.

그럼 ~~

2018년 1월 12일 금요일

How to control loading screen (white / black) when running Android App

After you develop and run your app in Android Studio, you'll see an initial white or black screen popping up and running your code.

This is what happens after building with Android Studio. I had never seen this phenomenon when I was building it in Eclipse before (maybe I was not interested.

This phenomenon occurs when the number of jobs in OnCreate increases.

To prevent this, you can do the following three methods.

1. Transparent treatment.
  It is a way to make it disappear altogether. However, if you use this method, the app may seem to stop for a while after you press the button.
 Open the res-> values-> styles.xml file and add the following two items to the style item set in AndroidManifest.xml.
<item name = "android: windowContentOverlay"> @ null </ item>
<item name = "android: windowIsTranslucent"> true </ item>

2. Color change processing.
 How to change the color to the color you want.
 Open the res-> values-> styles.xml file and add the following two items to the style item set in AndroidManifest.xml.
<item name = "android: windowBackground"> ​​@ color / red </ item>

3. Image processing.
How to specify an image in the same way as iPhone.
 Open the res-> values-> styles.xml file and add the following two items to the style item set in AndroidManifest.xml.
<item name = "android: windowBackground"> ​​@ drawable / splash </ item>

 Of course, the above image must be registered.

Then ^^;

2017년 10월 21일 토요일

Android WIFI Debuging

Today we talk about Android WIFI debugging.
iOS has recently provided WIFI debugging, but Android has been around for a while now.
For debugging, the development PC and smartphone must be in the same network.
How to set it is as follows.
Navigate to the folder where adb is installed and open the Window Command window in that location.
adb -d tcpip 9999.
Then the following message appears.
restarting in TCP mode port: 9999
Next, obtain the local IP of the smartphone to be debugged.(You can easily get information by installing a tool to get WIFI information from Google Play.)
Once you have obtained the IP, type Command as shown below.
After typing adb connect XXX.XXX.XXX.XXX:9999, the following message is displayed and the connection is successful.
connect to XXX.XXX.XXX.XXX:9999
How to verify your connection
If you type adb devices, you can check the list.
List of devices attachedXXX.XXX.XXX.XXX:9999 device
Finally, the way to turn debugging connected with WIFI back to USB is as follows.
adb -s XXX.XXX.XXX.XXX:9999 usb
Feel free to develop and develop wireless ^^

2017년 2월 14일 화요일

Android Studio 에서 "error failed to crunch file max path" 에러시 처리방법.

Android Studio 에서 빌드시 "error failed to crunch file max path" 에러가 나타날때 처리 방법입니다.
맥장비랑 윈도우 장비 모두 사용중인데 유독 윈도우 장비에서만 나타나서 검색을 해보니
빌드되는 패스가 240자가 넘어가면 나타나는 오류라고 하네요. (ㅡㅡ.)
다행이도 처리 방법이 존재 합니다.
프로젝트에 최상위 build.gradle 파일에 아래와 같이 셋팅 하여 처리 하면


allprojects {
    buildDir = "C:/tmp/${rootProject.name}/${project.name}"
    repositories {
       ...
    }
}



해당 패스로 빌드 경로를 설정 하기 때문에 "error failed to crunch file max path" 오류가 나타나지 안습니다.

2016년 9월 7일 수요일

Eclipse Neon 사용중 우측 뷰 사라지는 버그 해결법.

Eclipse Neon 으로 업그레이드후 개발중 종종 우측 뷰 리스트들이 사라지는 경우가 생긴다.
어째 업그레이드 하면 좋아지는것도 있지만 버그도 만들어 놓는지 ㅡㅡ.
해결법은 Windows -> Perspective -> Reset Perspective 로 하면 디폴트 값으로 변경이 된다.
후에 기존에 쓰던것들은 다시 추가 하면 된다.
Android LogCat 은 Show View 에 바로 안나오니 Other 로 찾아서 등록하면 된다.

2016년 5월 3일 화요일

Double, Float 지수e 표현을 일반 숫자표현으로 처리 하는 방법.

서버와 데이터 통신을 하다 보면 float 형 또는 double 형 데이터를 Byte Array 로 받아서 해당 형으로 변환 시켜야 할때가 있다.

이때 숫자로 표현 하고자 할때 아래와 같은 문제가 발생한다.

<원데이터>
102571293.000000
<ByteArray 받은것 double 변환후 스트링 표현하면 아래와 같이>
1.02571293E8

위와 같이 실수가 지수e 표현 되는것을 알수 있다.

위와 같이 표현을 필요도 하지만 일반적인곳에서는 일반적인 숫자로 표현 하기를 원하기 때문에 처리 하려면
아래와 같이 하면 일반적인 숫자로 표현이 가능하다.

DecimalFormat df = new DecimalFormat("#.#");
String sValue = df.format(ByteBuffer.wrap(output1, 0, 8).getDouble());

위에서 output1 은 서버에서 받은 byte[] 배열 8바이트 double 형이고 이것을 변환 할때 "DecimalFormat" 을 이용하면 원하는

결과를 얻을수 있다. ^^

2015년 2월 6일 금요일

Java 기준 스트링 검색/추출/분리(Find/SubString/Split)

오늘 포스팅 할 내용은 Java 환경에서 스트링 검색/추출/분리 작업에 대해서 이야기 합니다.

프로그램을 만들다 보면 스트링 핸들링은 중요한 항목중에 하나이고 뭐 대충 검색 해보면 많은곳에서 가이드 하고 있습니다.

그래도 샘플을 찾다 보면 내가 제시한 샘플을 찾고 자 하는 사람들을 위해서 ^^

일단 선행 조건은 특정 디렉토리에 파일이 있을경우 파일명만 찾아서 추출하고 과정과 디렉토리 를 "\\" 문자로 분리 하는 과정을

소개 합니다.

String strOrgPath = "C:\\Temp\\Dummy.txt";
String strOnlyFileName = "";

// 파일을 분리 하기 위한 Reverse Find
int nFind = strOrgPath.lastIndexOf("\\");

// 파일 이름 분리 작업
if (nFind >= 0)
{
    strOnlyFileName = strOrgPath.substring(nFind+1, strOrgPath.length());
    System.out.println(strOnlyFileName);
}

//디렉토리를 "\\" 로 분리 하는 작업
String[] sArrSplitPath = strOrgPath.split("[\\\\]");
for (int i = 0; i < sArrSplitPath.length; i++ )
{
    System.out.println(sArrSplitPath[i]);
}

여기까지 ^^;

2014년 7월 2일 수요일

Eclipse Andorid Plugin 22.6 에서 23 버젼으로 업데이트 되지 않을때 조치 방법.

Android SDK 4.4 버젼이 나오면서 ADT Manager 를 통해서 업데이트를 받고 나면 Android Plugin update 를 하라고 하지만

실제로는 업데이트가 되지 않는다. (개인 개발 환경은 Ecliplse Juno)

이전에 설치된 Android Plugin 을 지워야 하는데 지우는 방법은 아래와 같다.

1. Eclipse에 관하여 메뉴를 누른다(Mac 유저는 Eclipse 에 존재 하고 Windows 유저는 Help 메뉴 밑에 있음)
2. 팝업창이 하나 뜨면 "Installation Details" 버튼을 누른다.
3. 목록중에 Andorid 관련된 플러그인 라이브러리를 모두 언인스톨 한다(22.6 버젼으로 찾으면 됨)
4. Eclipse 재 실행후 ADT Plugin 을 재 설치 한다(https://dl-ssl.google.com/android/eclipse/ )

왜 자동 업데이트가 안되는지는 모르겠지만.. 위와 같은 방법으로 하면 해결됩니다.. ^^

2012년 12월 12일 수요일

"already exists but is not a source folder. Convert to a source folder or rename it" 오류 해결방법

안드로이드 개발하다 보면 소스가 꼬여서 "already exists but is not a source folder. Convert to a source folder or rename it" 오류가

나올때가 있다.

이럴떄에는 아래 스탭으로 처리 하면 해결 가능하다.

1. 해당 안드로이드 프로젝트 프로퍼티를 열어서 "Java Build Path"에 Source 탭에 /src,, /gen 폴더가 빠져 있을거니 추가 해준다.
2. 해당 안드로이드 프로젝트 Android Tools->Fix Project Properties 를 눌러서 수정한다.
3. 해당 안드로이드 프로젝트 를 클린 컴파일 한다.

2012년 11월 22일 목요일

Java 에 C modf 함수 구현하기.

Visual Studio 에서 코드를 모바일로 이식 시키기 위해서 작업 하다 보니


iOS 는 기반이 C 라서 C에서 제공하는 함수를 그대로 쓸수 있는데 Java 에서는 없는 함수가 있다.


그중에 modf 라는 함수 인데 이것을 Java 에서 구현 하는 법은 아래와 같다.

(modf 라는 함수는 정수부와 소수부를 나눠서 값을 얻을수 있는 함수)


Java 에 Math 라는 클래스에서  Math.floor 라는 함수를 이용하면 되고 사용법은 아래와 같다.



dValue = 123.456;

double dFractional, dInt;

dInt = Math.floor(dValue);

dFractional = dValue - dInt;


2012년 8월 16일 목요일

Handler 메모리 릭 없이 쓰기.(Lint Warnings 제거)

Android 개발 하면서 메세지 처리를 위해서 Handler 를 이용한다. 보통 쓰는 방법은 아래와 같다.

  1. public class Parent
  2. {     
  3.     private Handler m_handlerProc = new Handler()
  4.     {
  5.         @Override
  6.         public void handleMessage(Message message)
  7.         {
  8.            ...
  9.         }
  10.     };
  11. }

쓰는데는 무리가 없지만 패키지 말을때 "Lint Warnings) 가 나타난다.

해서 Warnings 을 제거 하기 위해서는 코드를 아래와 같이 수정하면 된다.

  1. public class Parent
  2. {
  3.     static class InnerHandler extends Handler
  4.     {
  5.         WeakReference<Parent> m_HandlerObj;
  6.         InnerHandler(Parent handlerobj)
  7.         {
  8.             m_HandlerObj = new WeakReference<Parent>(handlerobj);
  9.         }
  10.  
  11.         @Override
  12.         public void handleMessage(Message message)
  13.         {
  14.             Parent handlerobj = m_HandlerObj.get();
  15.             ....
  16.         }
  17.     }
  18.  
  19.     private InnerHandler m_handlerproc = new InnerHandler(this);
  20. }

^^ 그럼 즐프들 하세요..


2012년 8월 13일 월요일

Android 날짜 일수 계산

Android 개발할때 두개의 날짜를 가지고 날짜 일수를 계산 하는 방법입니다.


Date today = new Date();


Calendar calToday = Calendar.getInstance();
calToday.setTime(today);


Calendar calEnd = Calendar.getInstance();
calEnd.set(2012, 8-1, 5);// month 의 경우 해당 월수에 -1을 해줍니다.


int nRemainCnt = 0;


while(!calToday.after(calEnd))
{
nRemainCnt++;
calToday.add(Calendar.DATE, 1);
}



위 while 루프를 빠져 나오면 nRemainCnt 변수에 일수가 저장된다. ^^

2012년 8월 6일 월요일

Eclipse 툴 ctrl+k 옵션.

Android 를 개발하면서 eclipse 를 사용하기 시작하였는데

쓰다 보니  Visual Studio 툴이랑 틀려서 특히 이게 왜 디폴트 인지는 모르겠는데

Visual Studio 에서는 F3키를 누르면 특정 단어를 찾아서 한 에디트에서 계속적으로

반복해서(키를 누를때마다) 호출이 되는데 Eclipse에서는 ctrl+k(아래로 찾기) ctrl+shift+k(위로찾기) 이렇게 나뉘어 있어서 불편했다.

뭐 처음에는 그냥 그러려니 하고 썼는데 영 불편에서 구글링으로 검색을 해보니

방법이 있었다.. 쩝.


위 그림과 같이 "Wrap search"항목을 체크 해두면 ctrl+k 를 계속 누를경우 같은 에디트 안에서 반복적으로 문자를 찾는다.

위 그림은  mac에서 캡춰 했지만 windows eclipse 도 동일함.

^^..