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

17. 12. 1.

C#으로 네이트온 팀룸 OPEN API를 이용하기(알림)

네이트온 팀룸 api를 c#으로 이용하기
using System;
using System.IO;
using System.Net;
using System.Text;

namespace TeamRoomTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Webhook URL
                string webHookUrl = "https://teamroom.nate.com/api/webhook/6fc73b8a/MDNieeQGWvEGnqQXO4wugRra";
                // Send Message
                string sendMessage = "테스트입니당~";
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(string.Format("content={0}", System.Web.HttpUtility.UrlEncode(sendMessage)));
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(webHookUrl);
                req.Timeout = 5000;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = data.Length;
                Stream dataStream = req.GetRequestStream();
                dataStream.Write(data, 0, data.Length);
                dataStream.Close();
                req.GetResponse();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

※ Webhook url 은 네이트온의 팀룸을 열면 팀룸메뉴 -> 오픈 API 이용하기 -> 새로 연결하기 또는 편집으로 들어가면 확인 가능하다.

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.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    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

아래코드 추가
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
아래코드 추가
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 (파일)

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);
            }
        });

    }
}

14. 1. 10.

안드로이드 Classic ASP PUSH 서버

push.asp 파일
<%
 ' 안드로이드 ASP 푸시 요청
 PushServerURL = "https://android.googleapis.com/gcm/send"

'  브라우저APIkey
 ApplicationAPIKey = "AIzaSyBi0pn1ckaJhRL9kK3mbwsHzk7x0fdE_Z8"

 ' regId(받을사람이 지급받은 registration_ids - 여러명일 경우 배열로 받아처리하면 될 듯 최대 1000)
 RegId = "APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9po8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR"

 ' 알림명
 tickerText = "알림테스트"
 ' 알림 제목
 contentTitle = "테스트 제목"
 ' 알림 내용
 message = "헬로~~~ 테스트입니다.~~~"

 postJSONData = "" & _
    "{" & _
    "  ""registration_ids"" : [ """ & RegId & """ ]" & _
    ", ""data"": {" & _
    "                 ""tickerText"" : """ & tickerText & """" & _
    "               , ""contentTitle"" : """ & contentTitle & """" & _
    "               , ""message"" : """ & message & """" & _
    "            }" & _
    "}"

 Set httpObj = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
 httpObj.open "POST" , PushServerURL, False
 httpObj.SetRequestHeader "Content-Type", "application/json"
 httpObj.SetRequestHeader "Authorization", "key=" & ApplicationAPIKey
 httpObj.Send postJSONData
 httpObj.WaitForResponse

 If httpObj.Status = "200" Then
  response.Write("전송성공 : " & httpObj.ResponseText)
 Else
  response.Write("전송실패 : " & httpObj.ResponseText)
 End If

%>


참고:
html
<form method="post" action="push.asp">
    tickerText :
    <input type="text" name="tickerText" value="알림테스트" /><br>
    contentTitle :
    <input type="text" name="contentTitle" value="테스트 제목" /><br>
    message :
    <textarea name="message">헬로~~~ 테스트입니다.~~~</textarea><br>
    RegId :
    <input type="text" name="RegId" value="APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9po8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR" /><br>
    <input type="text" name="RegId" value="APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9pp8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR" /><br>
    <input type="text" name="RegId" value="APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9pd8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR" /><br>
    <input type="submit" value="전송요청" />
</form>
asp
<%
 tickerText = request.Form("tickerText")
 contentTitle = request.Form("contentTitle")
 message = request.Form("message")
 RegId_Count = request.Form("RegId").Count
 RegId = ""
 For i = 1 To RegId_Count
  if i<>1 then RegId = RegId & ","
  RegId = RegId & """" & request.Form("RegId")(i) & """"
 Next


 postJSONData = "" & _
    "{" & _
    "  ""registration_ids"" : [ " & RegId & " ]" & _
    ", ""data"": {" & _
    "                 ""tickerText"" : """ & tickerText & """" & _
    "               , ""contentTitle"" : """ & contentTitle & """" & _
    "               , ""message"" : """ & message & """" & _
    "            }" & _
    "}"

%>

13. 8. 10.

안드로이드 C#.NET PUSH 서버

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

<!DOCTYPE html>
<html>
<head>
    <title>푸쉬 전송 TEST</title>
</head>
<body>
<asp:Literal ID="SendResult" runat="server" />
</body>
</html>


push.aspx.cs 파일
using System;
using System.Net.Security;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;

public partial class mobile_push : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {


        // 브라우저APIkey
        string BrowserAPIKey = Request.QueryString["ApiKey"];
        // BrowserAPIKey  = "AIzaSyBi0pn1ckaJhRL9kK3mbwsHzk7x0fdE_Z8";

        // regId(받을사람이 지급받은 registration_ids - 여러명일 경우 배열로 받아처리하면 될 듯 최대 1000)
        string RegId = Request.QueryString["RegId"];
        // RegId = "APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9po8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR";

        // 알림명
        string tickerText = Request.QueryString["Ticker"];
        // tickerText = "알림테스트";

        // 알림 제목
        string contentTitle = Request.QueryString["Title"];
        // contentTitle = "알림제목";

        // 알림 내용
        string message = Request.QueryString["Msg"];
        // message = "안녕하세요~~~푸쉬입니다.";

        string postData = "";
        postData += "{";
        postData += "  \"registration_ids\": [ \"" + RegId + "\" ]";
        postData += ", \"data\": {";
        postData += "                 \"tickerText\":\"" + tickerText + "\"";
        postData += "               , \"contentTitle\":\"" + contentTitle + "\"";
        postData += "               , \"message\": \"" + message + "\"";
        postData += "            }";
        postData += "}";

        string response = SendGCMNotification(BrowserAPIKey, postData);

        SendResult.Text = response;

    }



    private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
    {
        ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
        //  MESSAGE CONTENT
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        //  CREATE REQUEST
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        Request.Method = "POST";
        Request.KeepAlive = false;
        Request.ContentType = postDataContentType;
        Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        //  SEND MESSAGE
        try
        {
            WebResponse Response = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                var text = "Unauthorized - need new token";
                Console.Write(text);
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                var text = "Response from web service isn't OK";
                Console.Write(text);
            }

            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string responseLine = Reader.ReadToEnd();
            Reader.Close();

            return responseLine;
        }
        catch (Exception e)
        {

        }
        return "Error";

    }

    public static bool ValidateServerCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }
}