안드로이드 화면 메세지 출력 Toast

안드로이드 앱 개발시에 LOG창도 많이 보지만 아무래도 간단하게 안드로이드 스마트폰에서 바로 확인할수 있는

Toast를 잘 사용하실텐데요. 

Toast를 사용하는 방법에 대해서 정리할께요. 

Toast toast = Toast.makeText(getApplicationContext(), 출력내용, Toast.LENGTH_SHORT); //Toast.LENGTH_LONG 길게
toast.show();

이러면 화면에 출력이 되는데요. 

롱과숏 옵션이 있는데 화면에 나타나는 시간에서 차이가 나요. 

toast를 잘 사용하는것도 좋은데요. 이걸 좀더 응용해서 boolean debug=true;

를 이용하면 좀더 쉽게 사용할수 있어요. 

static public Context ctx;
static public boolean isdebug=true;
public void Toast(String message)
    {
    	if(isdebug)
        {
        	Toast toast = Toast.makeText(global.ctx, message, Toast.LENGTH_LONG);
        	toast.show();
         }
    }

 안드로이드 앱 시작시 ctx에 ctx = this.getApplicationContext(); 컨텍스트를 구해놓구요. 

필요할때마다. Toast("출력내용");으로 호출해서 사용할수 있습니다. 

간혹 쓰레드 안에서 값을 매번찍을땐 확인하기가 힘들지만 간혹가다 찍을경우엔 핸들을 이용하면 됩니다. 

oncreate에서 핸들러 선언해놓기.
global.mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Toast toast;
                switch (msg.arg1) {
                    case 1: //로그인성공
                        global.login_idx=(String) msg.obj;

                        SharedPreferences.Editor editor = global.sharedPreferences.edit();
                        editor.putString("login_idx",global.login_idx); // key, value를 이용하여 저장하는 형태
                        editor.commit();
                        globle.Toast(global.login_idx);
                        break;

                }
            }
        };


//호출시.
Message message = global.mHandler.obtainMessage();
                message.arg1 = 1;
                message.obj = str;
                global.mHandler.sendMessage(message);

이상 정리를 마칩니다.

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

안드로이드 WEBVIEW 웹뷰 ERR_CLEARTEXT_NOT_PERMITTED

안녕하세요. 간만에 웹뷰를 이용한 웹앱을 만들려고 안드로이드 개발을 시작했어요. 

네비게이션 바텀뷰로 생성하니 알수 없는 값으로 빈공간이 생겨 이부분을 해결하는데 시간이 소요되었는데요. 

웹뷰를 붙이고나서 저의 티스토리페이지를 호출해보았어요. 

ERR_CLEARTEXT_NOT_PERMITTED

에러가 나면서 접속이 안되었어요. 

찾아보니 안드로이드 OS 9 Pie부터는 HTTP://로 된 주소가 막혔다는데요. 

이는 수정을 해줘야 하더라구요. 

첫번째 방법은 제일 간단하지만 보안에 취약? 그런데 이게 취약할일이 있나 모르겠어요. 

여하튼 모든 http://로 된 주소를 사용할수 있게 해줘요. 

androidManifest.xml 파일에 추가해주시면 되요. 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sms2020.dentalapp3">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

android:usesCleartextTraffic="true" 이부분을 추가해주는것인데요. 

두번째 방법은 허가된 주소만 접근하게 하는방법이에요. 

res/xml/network_security_config.xml파일을 만들어요. 

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">secure.example.com</domain>
        </domain-config>
    </network-security-config>
    <?xml version="1.0" encoding="utf-8"?>
    <manifest ... >
        <application android:networkSecurityConfig="@xml/network_security_config"
                        ... >
            ...
        </application>
    </manifest>
    

이렇게 추가해주시면 되는데요 뭔가 귀찮네요 .

안드로이드 개발에 뭔가 제한사항이 하나하나 생길때 마다 개발이 성가셔 지는것 같네요. 

 

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

안드로이드 webview ERR_CONNECTION_ABORTED

안드로이드 개발시 만날수 있는 문구 인데요.

웹페이지를 로드 할수 없다며 나오는 메세지 인데요. 

이사이트에 연결할수 없습니다. 웹페이지가 일시적으로 다운되었거나 새로운 웹페이지주소로  이동했을수

있을때 발생하는 메세지 같아요. 

이럴때 www.naver.com 이나 www.daum.net 이나 www.google.com 으로 주소를 변경하여 테스트 해보시면 될것 같아요.

 

 

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

Failed to find Build Tools revision 25.0.3

S PEN 개발 소스를 열었다. 

Failed to find Build Tools revision 25.0.3 


여기 체크를 합니다.

버전을 체크합니다. 

해결되었습니다.

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

String finalUrl = "javascript:" + 

"var to = '"+Global.UrlAddress+"/friend_invite.php';" +

"var p = {userNo:'"+Global.user_data.userNo+"',macAddr:'"+Global.user_data.d_macAddr+"'};"+        

"var myForm = document.createElement('form');" +

"myForm.method='post' ;" +

"myForm.action = to;" +

"for (var k in p) {" +

"var myInput = document.createElement('input') ;" +

"myInput.setAttribute('type', 'text');" +

"myInput.setAttribute('name', k) ;" +

"myInput.setAttribute('value', p[k]);" +

"myForm.appendChild(myInput) ;" +

"}" +

"document.body.appendChild(myForm) ;" +

"myForm.submit() ;" +

"document.body.removeChild(myForm) ;";

Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW,

Uri.parse(finalUrl));

startActivity(browserIntent);

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

//절대 좌표에 따른 터치 처리..(안씀..)

public static boolean inBounds(TouchEvent event, int x, int y, int width,

int height) 

{

if (event.x > x && event.x < x+ width - 1 && event.y > y

&& event.y < y+ height - 1)

return true;

else

return false ;

}

public static boolean inBounds(MotionEvent event, int x, int y,

int width, int height) {

if (event.getX() > x && event.getX() < x+ width - 1 && event.getY() > y

&& event.getY() < y+ height - 1)

return true;

else

return false ;

}

//상대 좌표에 따른 충돌 처리.. 씀

public static boolean inBounds(int in_x,int in_y, int x, int y, int width,

int height) 

{

if (in_x > x && in_x < x+ width - 1 && in_y > y

&& in_y < y+ height - 1)

return true;

else

return false ;

}

'ANDROID' 카테고리의 다른 글

Failed to find Build Tools revision 25.0.3  (0) 2018.01.30
자바스크립트로 웹호출 (post)  (2) 2014.10.11
두 좌표의 거리 구하기.  (0) 2014.10.11
bitmap to byte 비트맵을 바이트정보로.  (0) 2014.10.11
android 치트 막기.  (0) 2014.10.11
블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

public static float getDistance(float x,float y,float x1, float y1)

{

return (float) Math.sqrt(Math.pow(Math.abs(x - x1),2)+ Math.pow(Math.abs(y - y1),2));

}



블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,


public static byte[] bitmapToByteArray( Bitmap $bitmap ) 

{  

        ByteArrayOutputStream stream = new ByteArrayOutputStream() ;  

        $bitmap.compress( CompressFormat.PNG, 100, stream) ;  

        byte[] byteArray = stream.toByteArray() ;  

        Log("bytesize : "+byteArray.length);

        return byteArray ;  

    }  

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

android 치트 막기.

ANDROID 2014. 10. 11. 13:41

패키지 명을 검색하여 막는 방법 

패키지명은 추가로 계속 넣어주시면 됩니다. 

public static void noCheat() {

if(Global.mContext==null||Global.g==null)

{

return;

}

PackageManager pm = Global.mContext.getPackageManager();

List< ApplicationInfo > appList = pm.getInstalledApplications( 0 );

int nSize = appList.size();

for( int i = 0; i < nSize; i++ ) 

{

if(

(appList.get(i).packageName.indexOf("com.cih.gamecih2") != -1) ||

(appList.get(i).packageName.indexOf("com.cih.game_cih") != -1) ||

(appList.get(i).packageName.indexOf("cn.maocai.gamekiller") != -1) ||

(appList.get(i).packageName.indexOf("com.google.android.xyz") != -1) ||

(appList.get(i).packageName.indexOf("com.google.android.kkk") != -1) ||

(appList.get(i).packageName.indexOf("com.cih.gamecih") != -1) ||

(appList.get(i).packageName.indexOf("cn.luomao.gamekiller") != -1) ||

(appList.get(i).packageName.indexOf("com.android.xxx") != -1) ||

(appList.get(i).packageName.indexOf("cn.maocai.gameki11er") != -1) ||

(appList.get(i).packageName.indexOf("cn.mc.sq") != -1) ||

(appList.get(i).packageName.indexOf("org.aqua.gg") != -1) ||

(appList.get(i).packageName.indexOf("idv.aqua.bulldog") != -1)

{

            String message ="<size=25><color=255255255><color=074074074>치트프로그램이 발견되었습니다.<enter=>삭제 후 실행해주세요<enter=>게임을 종료합니다.<color=255000000>";

            Global.g.getSupervisionpopup().setPopup(new Exitpopup(Popup.ekey_close,message,11,200));             

}

}

 }

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,

웹으로 파일 업로드.

ANDROID 2014. 10. 11. 13:40

웹으로 파일 업로드 주소와 파일명은 각자조건에 맞게 수정해서 사용하세요. 

public static String uploadFile(String sourceFileUri) 

{

        

String upLoadServerUri = Global.UrlAddress+"/picture_register.php";

int serverResponseCode=0;

String doc = "";

        String fileName = Global.user_data.userNo+".png"; 

        

        Util.Log("file name:"+sourceFileUri);

        HttpURLConnection conn = null;

        DataOutputStream dos = null;  

        String lineEnd = "\r\n";

        String twoHyphens = "--";

        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;

        byte[] buffer;

        int maxBufferSize = 1 * 1024 * 1024; 

        File sourceFile = new File(sourceFileUri);

      

        if (!sourceFile.isFile()) 

        {           

             return "";       

             

        }

        else

        {

             try { 

                  

                   // open a URL connection to the Servlet

                 FileInputStream fileInputStream = new FileInputStream(sourceFileUri);

                 URL url = new URL(upLoadServerUri);

                  

                 // Open a HTTP  connection to  the URL

                 conn = (HttpURLConnection) url.openConnection(); 

                 conn.setDoInput(true); // Allow Inputs

                 conn.setDoOutput(true); // Allow Outputs

                 conn.setUseCaches(false); // Don't use a Cached Copy

                 conn.setRequestMethod("POST");


                 

                 conn.setRequestProperty("Connection", "Keep-Alive");

                conn.setRequestProperty("ENCTYPE", "multipart/form-data");

                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                 conn.setRequestProperty("uploaded_file", fileName); 

                  Log("fileName : "+fileName);

                 dos = new DataOutputStream(conn.getOutputStream());                 

                 //////////////////////////////////////////////////////////////////////////////////////////

              dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"" + "userNo" + "\"" + lineEnd);

        dos.writeBytes(lineEnd);

        dos.writeBytes(Global.user_data.userNo);

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"" + "macAddr" + "\"" + lineEnd);

        dos.writeBytes(lineEnd);

        dos.writeBytes(Global.user_data.d_macAddr);

        dos.writeBytes(lineEnd);

                 /////////////////////////////////////////////////////////////////////////////////////////

                 dos.writeBytes(twoHyphens + boundary + lineEnd); 

                 dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""

                                           + fileName + "\"" + lineEnd);

                 

                 dos.writeBytes(lineEnd);

        

                 // create a buffer of  maximum size

                 bytesAvailable = fileInputStream.available(); 

        

                 bufferSize = Math.min(bytesAvailable, maxBufferSize);

                 buffer = new byte[bufferSize];

        

                 // read file and write it into form...

                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                    

                 while (bytesRead > 0) {

                      

                   dos.write(buffer, 0, bufferSize);

                   bytesAvailable = fileInputStream.available();

                   bufferSize = Math.min(bytesAvailable, maxBufferSize);

                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                    

                  }

        

                 // send multipart form data necesssary after file data...

                 dos.writeBytes(lineEnd);

                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        

                 // Responses from the server (code and message)

                 serverResponseCode = conn.getResponseCode();

                 String serverResponseMessage = conn.getResponseMessage();

                   

                 Log.i("uploadFile", "HTTP Response is : "

                         + serverResponseMessage + ": " + serverResponseCode);

                  

                 if(serverResponseCode == 200)

                 {                      

              

                 }    

                  

                 //close the streams //

                 fileInputStream.close();

                 dos.flush();

                 dos.close();

                 sourceFile.delete();

              String buffer2 = null;

             

    BufferedReader in = new BufferedReader(new InputStreamReader

                (conn.getInputStream()));

    while ((buffer2 = in.readLine()) != null) 

    {

    doc = doc + buffer2 + "\n";

    }

    in.close();    

   

     

            } catch (MalformedURLException ex) {  

          

                ex.printStackTrace();                

             

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  

            } catch (Exception e) {                 

           

                e.printStackTrace();

                 

            

                Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  

            }

          Util.Log("doc : "+doc);

             doc= java.net.URLDecoder.decode(doc);

      Util.Log("doc decoder : "+doc);

            return doc; 

             

         } // End else block 

       }

블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,