MainActivity
...더보기
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
|
package com.example.boostcoursepractice;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "SMS 수신 권한 있음.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "SMS 수신 권한 없음.", Toast.LENGTH_LONG).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS)) {
Toast.makeText(this, "SMS 권한 설명 필요함.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "SMS 수신 권한을 사용자가 승인함", Toast.LENGTH_LONG).show();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "SMS 수신 권한을 사용자가 거부함", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "SMS 수신 권한을 부여받지 못함", Toast.LENGTH_LONG).show();
}
}
}
}
}
|
cs |
SmsActivity
...더보기
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
|
package com.example.boostcoursepractice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SmsActivity extends AppCompatActivity {
EditText editText1;
EditText editText2;
EditText editText3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
Intent passedIntent = getIntent() ;
processCommand(passedIntent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processCommand(intent);
}
private void processCommand(Intent intent)
{
if(intent != null)
{
String sender = intent.getStringExtra("sender");
String contents = intent.getStringExtra("contents");
String receivedDate = intent.getStringExtra("receivedDate");
editText1.setText(sender);
editText2.setText(contents);
editText3.setText(receivedDate);
}
}
}
|
cs |
SmsReceiver
...더보기
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
|
package com.example.boostcoursepractice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm") ;
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.d(TAG, "onReceive() 호출 됨");
Bundle bundle = intent.getExtras();
SmsMessage[] messages = parseSmsMessage(bundle);
if (messages.length > 0) {
String sender = messages[0].getOriginatingAddress();
Log.d(TAG, "sender : " + sender);
String contents = messages[0].getMessageBody().toString();
Log.d(TAG, "contents : " + contents);
Date receivedDate = new Date(messages[0].getTimestampMillis());
Log.d(TAG, "received date : " + receivedDate);
sendToActivity(context, sender, contents, receivedDate);
}
}
private void sendToActivity(Context context, String sender, String contents, Date receiveDate) {
Intent intent = new Intent(context, SmsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP) ;
intent.putExtra("sender", sender);
intent.putExtra("contents", contents);
intent.putExtra("receivedDate", format.format(receiveDate));
context.startActivity(intent);
}
private SmsMessage[] parseSmsMessage(Bundle bundle) {
Object[] objs = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[objs.length];
for (int i = 0; i < objs.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) objs[i], format);
} else {
messages[i] = SmsMessage.createFromPdu((byte[]) objs[i]);
}
}
return messages;
}
}
|
cs |
manifests
...더보기
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
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.boostcoursepractice">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SmsActivity"></activity>
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
|
cs |
우선 메세지리시버를 만들면 다음과 같이 manifests에
<uses-permission android:name="android.permission.RECEIVE_SMS" />
권한을 부여해야 한다. 또한 receiver태그 안에
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
을 넣어줌으로써 SMS관련된 것만 받겠다고 인텐트 필터설정을 해줘야 한다.
리시버가 실행되면 onReceive라는 함수가 실행된다. 여기서는 리시버가 메세지를 받아 onReceive라는 함수가 호출되면
메세지의 정보를 인자로 넘겨 인텐트에 넣어 SmsActivity를 실행하게끔 구현해 놓았다.
위험권한은 MainAcitivity에 구현되어 있는데 그냥 위에꺼를 이해하고 필요할 때 갖다가 쓰면 된다.
'2019 summer 부스트코스 에이스(안드로이드 프로그래밍) > 3. 화면 여러 개 만들기' 카테고리의 다른 글
3-4-1 서비스 (0) | 2019.08.02 |
---|---|
3-3-3 액티비티 수명주기 (0) | 2019.08.02 |
3-2-2 부가데이터 (0) | 2019.08.01 |
3-2-1 인텐트 (0) | 2019.07.31 |
3-1-1 화면 구성과 화면 간 전환 (0) | 2019.07.31 |