1

I use the code below to make the phone vibrate when I receive a SMS with a specific text. But the phone vibrate only if the app is running. How can I make the phone vibrate even when the app is closed ?

Manifest Permission

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

SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver {

    private static final String TAG = "SmdReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle myBundle = intent.getExtras();

        if (myBundle != null) {
            Object[] pdus = (Object[]) myBundle.get("pdus");

            for (int i = 0; i < pdus.length; i++) {
                SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
                String body = message.getMessageBody();
                if (body == "test") {
                    Log.d(TAG, "vibrate"); // is print in the console
                    Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        v.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
                    } else {
                        v.vibrate(duration); //deprecated in API 26
                    }
                }
            }
        }
    }
}
tguichaoua
  • 123
  • 1
  • 8
  • I tried to start a `Intent Service` and call `vibrate` from it, but it doesn't work. I think vibrate simply not work if the app is closed. The [doc](https://developer.android.com/reference/android/os/Vibrator) : "If your process exits, any vibration you started will stop." – tguichaoua Oct 17 '20 at 09:47
  • I add a empty service that run in background with `startForeground` and it's work. – tguichaoua Oct 17 '20 at 10:16

1 Answers1

1

Android tend to kill background apps, especially customization like MIUI. To avoid this you need, for example, to attach the worker process to a permanent notification. So that the system won't kill the app.

There are other ways to keep the app running like services and background processing.

For more details follow Background Execution Limits.

And this is another question for something similar.

simone viozzi
  • 440
  • 5
  • 18