[JAVA] Foreground Service & SMS Broadcast Example

2021. 2. 19. 17:36Android

*Foreground Service Example

 

https://androidwave.com/foreground-service-android-example/

 

Foreground Service Android Example - AndroidWave

In this Post, I'll explain about foreground service android, How does work? What are the advantages and implementation? At last, I will prepare a foreground service sample app.

androidwave.com

해당 예제를 베이스삼아 Foreground Service가 도는 상태에서 SMS Broadcast 를 받는 예제를 만들어보겠다.

 

manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <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/Theme.MyApplication">

        <service
            android:name=".fgService"
            android:enabled="true"
            android:exported="true"></service>

        <receiver
            android:name=".fgService$MyReciver"
            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>

* <uses-permission android:name="android.permission.RECEIVE_SMS"/>은 SMS Message를 받기 위한 Permission이다.

* Foreground Service안에 생성한 Broadcast를 SMS Received intent-filter를 특정하여 manifest에 등록해야 한다.

 

MainActivity.class

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStartService = findViewById(R.id.btn_Start);
        btnStopService = findViewById(R.id.btn_Stop);

        // Request the permission immediately here for the first time run
        requestPermissions(Manifest.permission.RECEIVE_SMS, PERMISSIONS_REQUEST_RECEIVE_SMS);

    }

    private void requestPermissions(String permission, int requestCode) {
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                Toast.makeText(this, "Granting permission is necessary!", Toast.LENGTH_LONG).show();

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        requestCode);

                // requestCode is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }
}

 

*SMS Receive 를 받기 위해서는 SMS 권한을 받아야한다. (request Permission) 

-> 안받으면 사용자가 수동으로 Application 권한에 들어가서 권한을 받지 않는 한 SMS 는 못받는다.

 

fgService.class

    public static class MyReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            Toast myToast = Toast.makeText(context.getApplicationContext(),"문자가 도착했습니다!",Toast.LENGTH_LONG);
            myToast.show();

            mp = MediaPlayer.create(context,R.raw.do_sound);
            mp.start();
        }
    }

    public void fgService(){

    }

    @Override
    public void onCreate() {
        super.onCreate();

        IntentFilter filter = new IntentFilter();
        mReciver = new MyReciver();
        registerReceiver(mReciver,filter);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReciver);
    }

 

*Foreground Service 안에서 onCreate되었을떄 Receive를 등록해주고, onDestroy 될때 Receive를 해제시켜줘야한다

 

sound file

sol_sound.wav
0.24MB
do_sound.wav
0.20MB

 

*해당 프로젝트에 대한 풀 코드

github.com/Bsoyoung/fg_SMSReceiver/tree/3a42483557bff62115e0cbdea091978488ea4cd3

 

Bsoyoung/fg_SMSReceiver

initial commit(foreground service). Contribute to Bsoyoung/fg_SMSReceiver development by creating an account on GitHub.

github.com