4

I am creating a app which can detetct incomming sms to android phone but app is not working in background.

Here is my mainactivity.java in which i am asking for the permission from user to allow access to read sms.

package com.example.times;

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.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final int READ_SMS_PERMISSION=0;

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED)
        {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS))
            {
//                do nothing
            }
            else
            {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, READ_SMS_PERMISSION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
    {
        switch(requestCode)
        {
            case READ_SMS_PERMISSION:
            {
                if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                {
                    Toast.makeText(this, "Thankyou for granting access", Toast.LENGTH_LONG).show();


                }
                else
                {
                    Toast.makeText(this, "No problem", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

Here is myreciver.java in which i am detecting incomming sms and making toast of that msg.

When app is opened then it is working properly but when i exit the app it is not detecting any sms.

package com.example.times;

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;

public class MyReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
    private static final String TAG="SmsBroadcastReceiver";

    String msg, phoneNo ="";


    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
//        throw new UnsupportedOperationException("Not yet implemented");

        Log.i(TAG, "Intent Received: " +intent.getAction());


        if (intent.getAction()==SMS_RECEIVED)
        {
            Bundle dataBundle = intent.getExtras();
            if (dataBundle!=null)
            {
                Object[] mypdu=(Object[])dataBundle.get("pdus");
                final SmsMessage[] message = new SmsMessage[mypdu.length];

                for (int i =0; i<mypdu.length; i++)
                {
                    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
                    {
                        String format= dataBundle.getString("format");
                        message[i] = SmsMessage.createFromPdu((byte[])mypdu[i],format);

                    }
                    else
                    {
                        message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i]);
                    }

                    msg =message[i].getMessageBody();
                    phoneNo= message[i].getOriginatingAddress();
                }
                Toast.makeText(context, "Message: " +msg +"\nNumber: " +phoneNo, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Telll me if i am doing something wrong.

kartik chauhan
  • 151
  • 2
  • 16
  • How exactly are you determining that "it is not detecting any sms"? Are you just going by the `Toast`? Have you checked to see if `onReceive()` is running at all? Is that all your Receiver is supposed to do, or have you trimmed out something else? Are you testing this on an emulator, or on a physical device? If the latter, which specific device? – Mike M. Apr 10 '20 at 08:36
  • have you added the receiver in your AndroidManifest? – Ali Jibran Apr 10 '20 at 08:43
  • i mean to say my app is not working in background – kartik chauhan Apr 10 '20 at 09:15
  • Yeah, you mentioned that. We need more details. – Mike M. Apr 10 '20 at 09:17
  • what detail you need ? i'll give it to you – kartik chauhan Apr 10 '20 at 09:17
  • Please refer to [my first comment here](https://stackoverflow.com/questions/61136595/broadcast-receiver-not-working-in-background#comment108157063_61136595). – Mike M. Apr 10 '20 at 09:18
  • I am running it on physical device redmi 5a android -oreo. – kartik chauhan Apr 11 '20 at 02:47
  • yes i ahave added receiver in my androidmanifest file .When app is minimized or opened then it is showing toast of incomming msg . but when app is closed it is not showing any toast. – kartik chauhan Apr 11 '20 at 02:49
  • 1
    That manufacturer's devices often have security restrictions, in addition to the normal permissions, that prevent most third-party apps from doing certain things, without the user having explicitly allowed it. You'll need to locate the settings for those, and make sure your app is allowed. I've never used such a device, so I can't tell you where to go specifically, but check these posts: https://stackoverflow.com/q/30748107, https://stackoverflow.com/q/37927565, https://stackoverflow.com/a/35770734, https://stackoverflow.com/q/48166206, https://stackoverflow.com/q/55258440 – Mike M. Apr 11 '20 at 04:08
  • Thankyou very much sir. – kartik chauhan Apr 11 '20 at 04:55
  • 1
    I figure it out , It was my device problem, it is not allowing app to run in background. Thanks for the helo sir . – kartik chauhan Apr 11 '20 at 05:03

1 Answers1

-1

Make sure you have these in your Android Mainfest.xml

<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

And the following

<receiver
    android:name=
        "com.example.times.MyReceiver"
    android:enabled="true"
    android:exported="true">
</receiver>

EDIT
You need an Intent Service to read sms while your app is closed or in background.
Intent Service - Run in Background

Steps:

  • Create Intent Service
  • Add it Manifest
  • Call it from your Broadcast Receiver onReceive() method via Intent
Ali Jibran
  • 343
  • 6
  • 15
  • Sir thanks for the help but what i am saying is , i want my app to run in background . It is working when the app is open but when the app is closed it is not working. – kartik chauhan Apr 10 '20 at 09:17
  • you need intent services. You are half way there. Just add intent service and your good to go. Check this link out https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks – Ali Jibran Apr 10 '20 at 09:30
  • i have tried this also but it is not working when app is closed. – kartik chauhan Apr 11 '20 at 03:25
  • if you are above android P, then you need WorkManagers. Check this out. https://developer.android.com/topic/libraries/architecture/workmanager#java – Ali Jibran Apr 11 '20 at 08:30