[챕터 2-5-2] 리시버
2020. 2. 17. 20:28ㆍAndroid/Android 챕터 2-5
반응형
결과화면
에뮬레이터 우측의 ... 를 클릭 후
수신자번호와 SMS 메시지내용을 작성 후 SEND MESSAGE 버튼 클릭
메시지가 전송완료 시, 수신화면
프로젝트명 : MyReceiver
SmsReceiver
AndroidManifest.xml
더보기
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.minokuma.myreceiver">
<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">
<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>
SmsReceiver.java
더보기
package org.minokuma.myreceiver;
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;
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
@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[] smsMessages = parseSmsMessage(bundle);
if (smsMessages != null && smsMessages.length > 0){
String sender = smsMessages[0].getOriginatingAddress();
String contents = smsMessages[0].getMessageBody();
Log.d(TAG, "sender : " + sender + ", contents : " + contents);
}
}
private SmsMessage[] parseSmsMessage(Bundle bundle){
Object[] objs = (Object[]) bundle.get("pdus");
SmsMessage[] smsMessages = new SmsMessage[objs.length];
int smsCount = objs.length;
for(int i = 0; i < smsCount; i++){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
String format = bundle.getString("format");
smsMessages[i] = SmsMessage.createFromPdu((byte[]) objs[i], format);
} else {
smsMessages[i] = SmsMessage.createFromPdu((byte[]) objs[i]);
}
}
return smsMessages;
}
}
AndroidManifest.xml
더보기
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.minokuma.myreceiver">
<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">
<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>
build.gradle
더보기
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "org.minokuma.myreceiver"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
allprojects {
repositories {
maven {
url 'https://jitpack.io'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
}
Sync Now 클릭
MainActivity.java
더보기
package org.minokuma.myreceiver;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.pedro.library.AutoPermissions;
import com.pedro.library.AutoPermissionsListener;
public class MainActivity extends AppCompatActivity implements AutoPermissionsListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoPermissions.Companion.loadAllPermissions(this,101);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
AutoPermissions.Companion.parsePermissions(this, requestCode, permissions, this);
}
@Override
public void onDenied(int requestCode, String[] permissions) {
showToast("권한 거부 개수 : " + permissions.length);
}
@Override
public void onGranted(int requestCode, String[] permissions) {
showToast("권한 허가 개수 : " + permissions.length);
}
public void showToast(String data){
Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
}
}
가상 에뮬레이터 실행 후 ... 클릭
SEND MESSAGE 버튼 클릭하면,
로그캣의 No Filters 클릭
SmsActivity
SmsReceiver.java
더보기
package org.minokuma.myreceiver;
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;
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
@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[] smsMessages = parseSmsMessage(bundle);
if (smsMessages != null && smsMessages.length > 0){
String sender = smsMessages[0].getOriginatingAddress();
String contents = smsMessages[0].getMessageBody();
Log.d(TAG, "sender : " + sender + ", contents : " + contents);
sendToActivity(context, sender, contents);
}
}
public void sendToActivity(Context context, String sender, String contents){
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);
context.startActivity(intent);
}
private SmsMessage[] parseSmsMessage(Bundle bundle){
Object[] objs = (Object[]) bundle.get("pdus");
SmsMessage[] smsMessages = new SmsMessage[objs.length];
int smsCount = objs.length;
for(int i = 0; i < smsCount; i++){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
String format = bundle.getString("format");
smsMessages[i] = SmsMessage.createFromPdu((byte[]) objs[i], format);
} else {
smsMessages[i] = SmsMessage.createFromPdu((byte[]) objs[i]);
}
}
return smsMessages;
}
}
SmsActivity.java
더보기
package org.minokuma.myreceiver;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SmsActivity extends AppCompatActivity {
TextView textView2;
TextView textView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
Intent intent = getIntent();
processIntent(intent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
public void processIntent(Intent intent){
}
}
SmsActivity.java
더보기
package org.minokuma.myreceiver;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SmsActivity extends AppCompatActivity {
TextView textView2;
TextView textView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
Intent intent = getIntent();
processIntent(intent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
public void processIntent(Intent intent){
if (intent != null){
String sender = intent.getStringExtra("sender");
String contents = intent.getStringExtra("contents");
textView2.setText(sender);
textView3.setText(contents);
}
}
}
반응형
'Android > Android 챕터 2-5' 카테고리의 다른 글
[챕터 2-5-1] 서비스와 수신자 (0) | 2020.02.17 |
---|