16. 10. 24.

VB로 MS-SQL 연동

insert,update,delete
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Dim connectionString As String
        Dim sqlConn As New SqlConnection
        Dim sqlComm As New SqlCommand
        connectionString = "server = 127.0.0.1,1433; uid = sa; pwd = password; database = member;"
        sqlConn = New SqlConnection(connectionString)
        sqlComm = New SqlCommand()
        sqlComm.Connection = sqlConn
        sqlComm.CommandText = "insert into tbl_member (code,id,addr) values (@param1,@param2,param3)"
        'sqlComm.CommandText = "update tbl_member set addr=@param3 where code=@param1 and id=param2"
        'sqlComm.CommandText = "delete tbl_member where code=@param1 and id=param2"
        sqlComm.Parameters.AddWithValue("@param1", "1")
        sqlComm.Parameters.AddWithValue("@param2", "abc")
        sqlComm.Parameters.AddWithValue("@param3", "서울")
        Try
            sqlConn.Open()
            sqlComm.ExecuteNonQuery()
            sqlConn.Close()
        Catch ex As Exception
            Response.Write(ex)
        End Try
    End Sub
End Class


select
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Dim connectionString As String
        Dim sqlConn As New SqlConnection
        Dim sqlComm As New SqlCommand
        Dim dt As DataTable
        dt = New DataTable("MEMBER")
        dt.Columns.Add("code", GetType(Integer))
        dt.Columns.Add("id", GetType(String))
        dt.Columns.Add("addr", GetType(String))
        connectionString = "server = 127.0.0.1,1433; uid = sa; pwd = password; database = member;"
        sqlConn = New SqlConnection(connectionString)
        sqlComm = New SqlCommand()
        sqlComm.Connection = sqlConn
        sqlComm.CommandText = "select top 10 code,id,addr from tbl_member where m_id=@param1 order by m_id asc"
        sqlComm.Parameters.AddWithValue("@param1", "master")
        Try
            sqlConn.Open()
            Dim rs As SqlDataReader = sqlComm.ExecuteReader()
            If rs.HasRows Then
                Do While rs.Read()
                    dt.Rows.Add(rs(0), rs(1), rs(2))
                Loop
            End If
            rs.Close()
            sqlConn.Close()
        Catch ex As Exception
            Response.Write(ex)
        End Try
        Response.Write("<table border=""1""><thead><tr><th>CODE</th><th>ID</th><th>ADDR</th></tr></thead><tbody>")
        For i As Integer = 0 To dt.Rows.Count - 1
            Response.Write(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", dt.Rows(i).Item("code"), dt.Rows(i).Item("id"), dt.Rows(i).Item("addr")))
        Next
        Response.Write("</tbody></table>")
    End Sub
End Class

PHP에서 ODBC 이용 MS-SQL 연동

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
 $ListArr = array();
 $conn = odbc_connect('dbserver', 'ID', 'PASSWORD');
 if($conn){
  $sql = "select top 10".PHP_EOL.
    "m_code,m_id,convert(char(10),m_regdate,120) as m_regdate".PHP_EOL.
    "from tbl_member".PHP_EOL.
    "order by m_code desc".PHP_EOL;
  $rs = odbc_exec($conn, $sql);
  while (odbc_fetch_row($rs)){
   array_push($ListArr,
    array(
     odbc_result($rs,"m_code"),
     iconv('euc-kr','utf-8',odbc_result($rs,"m_id")),
     odbc_result($rs,"m_regdate")
    )
   );
  }
  odbc_close($conn);
 }
?>
<table border="1">
<thead><tr><th>CODE</th><th>ID</th><th>DATE</th></tr></thead>
<tbody>
<?php
 if(count($ListArr)>0){
  foreach($ListArr as $arr1){
   echo "<tr><td>".$arr1[0]."</td><td>".$arr1[1]."</td><td>".$arr1[2]."</td></tr>";
  }
 }else{
  echo "<tr><td colspan=\"3\" align=\"center\">No Exist</td></tr>";
 }
?>
</tbody>
</table>

JQuery 한화면 단위 Mouse Wheel 이동

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>MouseWheel</title>
    <style type="text/css">
        html,body{ margin:0; padding:0; width:100%; height:100%;}
        .box{ width:100%; height:100%; position:relative; color:#ffffff; font-size:24pt;}
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            var elm = ".box";
            $(elm).each(function (index) {
                // 개별적으로 Wheel 이벤트 적용
                $(this).on("mousewheel DOMMouseScroll", function (e) {
                    e.preventDefault();
                    var delta = 0;
                    if (!event) event = window.event;
                    if (event.wheelDelta) {
                        delta = event.wheelDelta / 120;
                        if (window.opera) delta = -delta;
                    }
                    else if (event.detail)
                        delta = -event.detail / 3;
                    var moveTop = $(window).scrollTop();
                    var elmSelecter = $(elm).eq(index);
                    // 마우스휠을 위에서 아래로
                    if (delta < 0) {
                        if ($(elmSelecter).next() != undefined) {
                            try{
                                moveTop = $(elmSelecter).next().offset().top;
                            }catch(e){}
                        }
                    // 마우스휠을 아래에서 위로
                    } else {
                        if ($(elmSelecter).prev() != undefined) {
                            try{
                                moveTop = $(elmSelecter).prev().offset().top;
                            }catch(e){}
                        }
                    }
                     
                    // 화면 이동 0.8초(800)
                    $("html,body").stop().animate({
                        scrollTop: moveTop + 'px'
                    }, {
                        duration: 800, complete: function () {
                        }
                    });
                });
            });
        }
    </script>
</head>
<body>
    <div class="box" style="background-color:red;">1</div>
    <div class="box" style="background-color:orange;">2</div>
    <div class="box" style="background-color:yellow;">3</div>
    <div class="box" style="background-color:green;">4</div>
    <div class="box" style="background-color:blue;">5</div>
    <div class="box" style="background-color:indigo;">6</div>
    <div class="box" style="background-color:violet;">7</div>
</body>
</html>
ie 일 경우 ie 6 이하의 브라우저에서 안됨 이때에는 head에
<meta http-equiv="X-UA-Compatible" content="IE=edge">
를 넣어줘야한다

추가 (좌우)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>MouseWheel</title>
    <style type="text/css">
        html,body{ margin:0; padding:0; width:100%; height:100%;}
        .boxwrap{ display: table; table-layout: fixed; width: 700%; height: 100%; table-layout: fixed;}
        .box{ display: table-cell;position:relative; color:#ffffff; font-size:24pt;}
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            var elm = ".box";
            $(elm).each(function (index) {
                // 개별적으로 Wheel 이벤트 적용
                $(this).on("mousewheel DOMMouseScroll", function (e) {
                    e.preventDefault();
                    var delta = 0;
                    if (!event) event = window.event;
                    if (event.wheelDelta) {
                        delta = event.wheelDelta / 120;
                        if (window.opera) delta = -delta;
                    }
                    else if (event.detail)
                        delta = -event.detail / 3;
                    var moveTop = $(window).scrollLeft();
                    var elmSelecter = $(elm).eq(index);
                    // 마우스휠을 위에서 아래로
                    if (delta < 0) {
                        if ($(elmSelecter).next() != undefined) {
                            try{
                                moveTop = $(elmSelecter).next().offset().left;
                            }catch(e){}
                        }
                    // 마우스휠을 아래에서 위로
                    } else {
                        if ($(elmSelecter).prev() != undefined) {
                            try{
                                moveTop = $(elmSelecter).prev().offset().left;
                            }catch(e){}
                        }
                    }
                     
                    // 화면 이동 0.8초(800)
                    $("html,body").stop().animate({
                        scrollLeft: moveTop + 'px'
                    }, {
                        duration: 800, complete: function () {
                        }
                    });
                });
            });
        }
    </script>
</head>
<body>
    <div class="boxwrap">
    <div class="box" style="background-color:red;">1</div>
    <div class="box" style="background-color:orange;">2</div>
    <div class="box" style="background-color:yellow;">3</div>
    <div class="box" style="background-color:green;">4</div>
    <div class="box" style="background-color:blue;">5</div>
    <div class="box" style="background-color:indigo;">6</div>
    <div class="box" style="background-color:violet;">7</div>
    </div>
</body>
</html>
좀 복잡한 방법 : Jquery 한화면 단위 Mouse Wheel 이동 (응용)

VB.NET Email 전송

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Function eMailCDOSend(MailTitle As String, MailTag As String, Sender As String, Receiver As String, addFile As String) As Boolean
    ' MailTitle : 제목
     ' MailTag : html내용
     ' Sender : 보내는 사람
     ' Receiver : 받는사람
 
    Dim eMailObject, eMailConfig
    Dim SchemaPath
 
    eMailObject = Server.CreateObject("CDO.Message")
    eMailConfig = Server.CreateObject("CDO.Configuration")
    Try
        With eMailConfig.Fields
            .Item(SchemaPath & "sendusing") = 2  'CDOSendUsingPort
            .Item(SchemaPath & "smtpserver") = "127.0.0.1"  'CDOSendUsingPort [ServerIP]
            .Item(SchemaPath & "smtpserverport") = "325"     'Port
            .Update
        End With
        eMailObject.Configuration = eMailConfig
 
        eMailConfig = Nothing
        If addFile <> "" Then
            eMailObject.To = Receiver
            eMailObject.From = Sender
            eMailObject.Subject = MailTitle
            eMailObject.HTMLBody = MailTag
            eMailObject.BodyPart.Charset = "ks_c_5601-1987"
            eMailObject.HTMLBodyPart.Charset = "ks_c_5601-1987"
            eMailObject.HTMLBodyPart.ContentTransferEncoding = "quoted-printable"
            eMailObject.AddAttachment(addFile)
            eMailObject.fields.update
            eMailObject.Send
        Else
            With eMailObject
                .From = Sender
                .To = Receiver
                .Subject = MailTitle
                .HTMLBody = MailTag
                .BodyPart.Charset = "ks_c_5601-1987"
                .HTMLBodyPart.Charset = "ks_c_5601-1987"
                .HTMLBodyPart.ContentTransferEncoding = "quoted-printable"
                .Send
            End With
       End If
        eMailObject = Nothing
    Catch ex As Exception
        Return False
    End Try
    Return True
End Function

16. 7. 28.

C#으로 MS-SQL 연동

insert,update,delete
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Data.SqlClient;
 
namespace MsSql
{
    class Program
    {
         
        static void Main(string[] args)
        {
            // Sql 연결정보(서버:127.0.0.1, 포트:3535, 아이디:sa, 비밀번호 : password, db : member)
            string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
            // Sql 새연결정보 생성
            SqlConnection sqlConn = new SqlConnection(connectionString);
            SqlCommand sqlComm = new SqlCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = "insert into tbl_member (id,name,addr) values (@param1,@param2,@param3)";
            //sqlComm.CommandText = "update tbl_member set addr=@param3 where id=@param1 and name=@param2";
            //sqlComm.CommandText = "delete tbl_member where id=@param1 and name=@param2 and addr=@param3";
            sqlComm.Parameters.AddWithValue("@param1", "abc");
            sqlComm.Parameters.AddWithValue("@param2", "홍길동");
            sqlComm.Parameters.AddWithValue("@param3", "서울");
            sqlConn.Open();
            sqlComm.ExecuteNonQuery();
            sqlConn.Close();
        }
    }
}


select
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Data.SqlClient;
 
namespace MsSql
{
    class Program
    {
         
        static void Main(string[] args)
        {
            // Sql 연결정보(서버:127.0.0.1, 포트:3535, 아이디:sa, 비밀번호 : password, db : member)
            string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
            // Sql 새연결정보 생성
            SqlConnection sqlConn = new SqlConnection(connectionString);
            SqlCommand sqlComm = new SqlCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = "select top 10 id,addr from tbl_member where name=@param1 order by id asc";
            sqlComm.Parameters.AddWithValue("@param1", "김준");
            sqlConn.Open();
            using (SqlDataReader SqlRs = sqlComm.ExecuteReader())
            {
                Console.WriteLine("ID \t \t | Address");
                while (SqlRs.Read())
                {
                    Console.WriteLine(string.Format("{0} \t \t | {1}", SqlRs[0].ToString(),SqlRs[1].ToString()));
                }
            }
            sqlConn.Close();
        }
    }
}

16. 7. 20.

C#.NET 파일업로드

upload.html 파일
1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>파일업로드</title>
</head>
<body>
 <form name="form1" method="post" action="Upload.aspx" enctype="multipart/form-data">
  <input type="file" name="file1" multiple/>
  <input type="submit" value="업로드"/>
 </form>
</body>
</html>


Upload.aspx 파일
1
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Upload" %>


Upload.aspx.cs 파일
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
 
public partial class Upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpFileCollection uploadedFiles = Request.Files;
 
        int maxFile = 10;
 
        if (uploadedFiles.Count > maxFile)
        {
            Response.Write("한번에 올릴 수 있는 파일수는 " + maxFile.ToString() + "개입니다.");
            return;
        }
 
        for (int i = 0; i < uploadedFiles.Count; i++)
        {
            HttpPostedFile userPostedFile = uploadedFiles[i];
 
            if (userPostedFile.ContentLength > 0 && !String.IsNullOrEmpty(userPostedFile.FileName))
            {
                string result = UploadFileSave(userPostedFile, i);
                if (result != "")
                {
                    // 업로드 성공
                    Response.Write(result + " ");
                }
                else
                {
                    // 업로드 실패
                }
            }
        }
    }
 
    private string UploadFileSave(HttpPostedFile SaveFile, int no)
    {
        // 저장폴더
        string wPath = Server.MapPath("/file") + "\\";
        string thumPath = Server.MapPath("/file/thum") + "\\";
        DirectoryInfo di = new DirectoryInfo(wPath);
        // 폴더가 없을 경우 생성
        if (di.Exists == false)
            di.Create();
        di = new DirectoryInfo(thumPath);
        // 폴더가 없을 경우 생성
        if (di.Exists == false)
            di.Create();
        // 확장자
        string fileType = SaveFile.FileName.Substring(SaveFile.FileName.LastIndexOf(".") + 1);
        // 변경할 파일 이름
        string saveFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + no + "." + fileType;
        try
        {
            // 이미지 확장자 일 경우
            if (("jpg|jpeg|bmp|gif|png").IndexOf(fileType.ToLower()) > -1)
            {
                Bitmap img = new Bitmap(SaveFile.InputStream);
                RotateFlipType rft = RotateFlipType.RotateNoneFlipNone;
                PropertyItem[] properties = img.PropertyItems;
                foreach (PropertyItem p in properties)
                {
                    // 이미지가 똑바로 되어있지 않은 경우
                    if (p.Id == 274)
                    {
                        Int16 orientation = BitConverter.ToInt16(p.Value, 0);
                        switch (orientation)
                        {
                            case 1:
                                rft = RotateFlipType.RotateNoneFlipNone;
                                break;
                            case 3:
                                rft = RotateFlipType.Rotate180FlipNone;
                                break;
                            case 4:
                                rft = RotateFlipType.Rotate90FlipNone;
                                break;
                            case 8:
                                rft = RotateFlipType.Rotate270FlipNone;
                                break;
                        }
                    }
                }
                // 이미지가 부분은 이미지가 누워있을 경우 세워준다
                if (rft != RotateFlipType.RotateNoneFlipNone)
                {
                    img.RotateFlip(rft);
                }
                // 저장
                img.Save(wPath + "\\" + saveFileName);
 
                // 썸네일 작업
                // 썸네일 폭
                int thumW = 100;
                // 썸네일 높이
                int thumH = 100;
                // 썸네일 좌표 X
                int thumX = 0;
                // 썸네일 좌표 Y
                int thumY = 0;
                // 썸네일 이미지 그리기전 사이즈 지정
                Bitmap thumimg = new Bitmap(thumW, thumH);
                if (img.Width >= thumW && img.Height >= thumH)
                {
                    if (img.Width >= img.Height)
                    {
                        thumW = (thumH * img.Width) / img.Height;
                        thumX = (thumW - thumH) / 2;
                        thumY = 0;
                    }
                    else
                    {
                        thumH = (thumW * img.Height) / img.Width;
                        thumY = (thumH - thumW) / 2;
                        thumX = 0;
                    }
                }
                else if (img.Width >= img.Height && img.Height < thumH)
                {
                    thumW = img.Width;
                    thumH = img.Height;
                    thumX = (img.Width - thumW) / 2;
                    thumY = (img.Height - thumH) / 2 * -1;
                }
                else if (img.Width < img.Height && img.Height >= thumH)
                {
                    thumW = img.Width;
                    thumH = img.Height;
                    thumX = (img.Width - thumW) / 2 * -1;
                    thumY = (img.Height - thumH) / 2;
                }
                else
                {
                    thumW = img.Width;
                    thumH = img.Height;
                    thumX = (img.Width - thumW) / 2 * -1;
                    thumY = (img.Height - thumH) / 2 * -1;
                }
                Graphics gp = Graphics.FromImage(thumimg);
                gp.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gp.DrawImage(img, new Rectangle(-thumX, -thumY, thumW, thumH));
                // 썸네일 저장
                thumimg.Save(wPath + "\\thum\\" + saveFileName);
            }
            else
            {
                // 이미지가 아닐경우
                // 저장하기
                SaveFile.SaveAs(wPath + "\\" + saveFileName);
            }
        }
        catch
        {
            return "";
        }
        return saveFileName;
    }
}

16. 4. 8.

안드로이드 스튜디오 PUSH 받기

Project > app > build.gradle (파일)

dependencies 에 compile 'com.google.android.gms:play-services:8.1.0' 추가


ex.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.1.0'
}



Project > app > src > main > AndroidManifest.xml (파일)

코드보기로 전환한 다음 다음 항목들을 추가
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<service android:name=".PushNotificationService" android:exported="false">

<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>

<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">

<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="패키지명" />
</intent-filter>
</receiver>

패키지명 모르겠다면
Project > app > src > main > java > MainActivity.java (파일) 맨 첫번째줄 package 다음에 써진 단어들...
ex.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>
    package="패키지명">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.example.gcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".PushNotificationService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="패키지명" />
            </intent-filter>
        </receiver>
    </application>
</manifest>



Project > app > src > main > java (우클릭 후 파일 생성)

파일명 : GCMClientManager.java

아래코드 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package 패키지명;
 
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
 
public class GCMClientManager {
    public static final String TAG = "GCMClientManager";
    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "프로젝트아이디번호";
    private static final String PROPERTY_APP_VERSION = "1.0";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private GoogleCloudMessaging gcm;
    private String regid;
    private String projectNumber;
    private Activity activity;
    public GCMClientManager(Activity activity, String projectNumber) {
        this.activity = activity;
        this.projectNumber = projectNumber;
        this.gcm = GoogleCloudMessaging.getInstance(activity);
    }
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            throw new RuntimeException("Could not get package name: " + e);
        }
    }
    public void registerIfNeeded(final RegistrationCompletedHandler handler) {
        if (checkPlayServices()) {
            regid = getRegistrationId(getContext());
            if (regid.isEmpty()) {
                registerInBackground(handler);
            } else {
                Log.i(TAG, regid);
                handler.onSuccess(regid, false);
            }
        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }
    private void registerInBackground(final RegistrationCompletedHandler handler) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(getContext());
                    }
                    InstanceID instanceID = InstanceID.getInstance(getContext());
                    regid = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                    Log.i(TAG, regid);
                    storeRegistrationId(getContext(), regid);
                } catch (IOException ex) {
                    handler.onFailure("Error :" + ex.getMessage());
                }
                return regid;
            }
            @Override
            protected void onPostExecute(String regId) {
                if (regId != null) {
                    handler.onSuccess(regId, true);
                }
            }
        }.execute(null, null, null);
    }
 
    private String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }
 
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }
 
    private SharedPreferences getGCMPreferences(Context context) {
        return getContext().getSharedPreferences(context.getPackageName(),
                Context.MODE_PRIVATE);
    }
 
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
            }
            return false;
        }
        return true;
    }
 
    private Context getContext() {
        return activity;
    }
 
    private Activity getActivity() {
        return activity;
    }
 
    public static abstract class RegistrationCompletedHandler {
        public abstract void onSuccess(String registrationId, boolean isNewRegistration);
        public void onFailure(String ex) {
            Log.e(TAG, ex);
        }
    }
}



Project > app > src > main > java (우클릭 후 파일 생성)

파일명 : PushNotificationService.java
아래코드 추가
1
2
3
4
5
6
7
8
9
10
11
12
package 패키지명;
 
import android.os.Bundle;
import com.google.android.gms.gcm.GcmListenerService;
 
public class PushNotificationService extends GcmListenerService {
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        //createNotification(mTitle, push_msg);
    }
}



Project > app > src > main > java > MainActivity.java (파일)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package 패키지명;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
 
import java.util.HashMap;
 
public class MainActivity extends AppCompatActivity {
 
    String PROJECT_NUMBER="프로젝트아이디번호";
    String phoneNum = null;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // 휴대폰번호 알아내기
        try{
            TelephonyManager telManager = (TelephonyManager)getSystemService(this.TELEPHONY_SERVICE);
            phoneNum = telManager.getLine1Number();
        }catch(Exception e){
        }
 
        // XML파일 화면에 보여주기
        setContentView(R.layout.activity_main);
 
        GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
        pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
            @Override
            public void onSuccess(String registrationId, boolean isNewRegistration) {
                Log.d("Registration id", registrationId);
 
                if(phoneNum==null){phoneNum="";}
 
                // 담아서 쓰던 전송해서 쓰던...
                HashMap<Object , Object> param = new HashMap<Object , Object>();
 
                if(phoneNum!="") {
                    param.put("regid", registrationId);
                    param.put("phone", phoneNum);
                }
 
                String postData = "HPN="+phoneNum+"&RegId="+registrationId;
 
            }
 
            @Override
            public void onFailure(String ex) {
                super.onFailure(ex);
            }
        });
 
    }
}