티스토리 뷰

안드로이드/프로그래밍

SMS, 소켓

에어버스 2015. 1. 27. 00:02

특정번호를 받은 문자를 소켓을 통해 MFC 서버로 전송하고 서버로부터 되돌려 받는다.
클라이언트 : ClientTest - SMS_SOCKET.zip

Layout.xml

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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:text="" >
    </EditText>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="입력완료" >
    </Button>

    <TextView
        android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:singleLine="false"
        android:text="..." >
    </TextView>

</LinearLayout>
 

Manifest.xml

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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kr.co.company.clienttest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="kr.co.company.clienttest.ClientTest"
            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>

클라이언트
ClientText.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package kr.co.company.clienttest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ClientTest extends Activity {
    private Socket socket;
    BufferedReader socket_in;
    BufferedWriter socket_out;

    EditText input;
    Button button;
    TextView output;
    String data;
    static int PORT = 9998;
    int song = 123;
    private final String _SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.enableDefaults();
        try {
            socket = new Socket("서버 도메인명이나 IP", PORT); // 폰에 연결해서 실행할때 이것 사용
            //socket = new Socket("192.168.100.254", PORT);
            // MFC 로 한글 수신잘됨.
            socket_in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "euc-kr")); 
            // MFC로 한글 전송 잘됨.
            socket_out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "euc-kr")); 
        } catch (IOException e) {
            output.setText("서버 연결 오류");
            e.printStackTrace();

        }
        input = (EditText) findViewById(R.id.input);
        button = (Button) findViewById(R.id.button);
        output = (TextView) findViewById(R.id.output);
        
        // 이벤트 등록, 문자오면 받을 리시버(이벤트 처리기) 등록
        IntentFilter f = new IntentFilter();
       f.addAction(_SMS_RECEIVED);
 // SMS 말고도 사용자 정의 이벤트도 가능
        registerReceiver(SMSRecv, new IntentFilter(f));
        
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String data = input.getText().toString();
                        
                if (data != null) { // SEND
                    Log.w("NETWORK"" " + data);
                    try {
                        socket_out.write("1" + data); // MFC 로 전송 잘됨.
                        socket_out.flush();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread worker = new Thread() {
            public void run() {
                int b = 0;
                char[] a = new char[1024];
                try {
                    while (true) {                         
                        b = socket_in.read(a); // RECIEVE
                        final String c = new String(a);
                        
                        output.post(new Runnable() {
                            public void run() {
                                output.setText("수신:"+c);
                            }
                        });
                    }
                } catch (Exception e) {
                    output.setText("수신 오류");    
                }
            }
        };
        worker.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    BroadcastReceiver SMSRecv = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String strAction = intent.getAction();
            if(strAction == _SMS_RECEIVED){
                Bundle bundle = intent.getExtras();
                if(bundle == null)
                    return;
                Object[] pdusObj = (Object[])bundle.get("pdus");
                if(pdusObj == null)
                    return;
                String MsgBody = "";
                SmsMessage[] smsMsg = new SmsMessage[pdusObj.length];
                for(int i=0; i<pdusObj.length; i++){
                    smsMsg[i] = SmsMessage.createFromPdu((byte[])pdusObj[i]);
                    MsgBody += smsMsg[i].getMessageBody(); // 문자
                }
                String origNumber = smsMsg[0].getOriginatingAddress(); // 발신자번호
                boolean b = origNumber.equals("발신자번호");  // 예:01011112222
                if(b)
                {
                    if (MsgBody != null) { // SEND
                        try {
                            socket_out.write("1" + MsgBody); // MFC 로 전송 잘됨. 안드로이드는 1로 시작
                            socket_out.flush();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    //Toast.makeText(context, "SEND:"+MsgBody, 0).show(); 
                    Log.d("SENDSMS:", MsgBody);
                }
            }
        }
    };
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
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