Tuesday, 29 September 2020

Showing ToastAndroid when app is closed with react-native and Headless JS

I've been trying to integrate BroadcastReceiver with my react-native app. I want to show the ToastAndroid whenever someone calls me. It works great when the app is running (either in foreground and background) but when I kill the app it doesn't trigger ToastAndroid anymore.

I've seen a video (YT link) of someone doing it in native code and it works even when the app is killed.

How can I accomplish it with react-native?

My Service code:

public class CallService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
        return new HeadlessJsTaskConfig(
            "Call",
            Arguments.fromBundle(extras),
            5000,
            true
            );
    }
return null;
}
}

My Receiver code:

public final class CallReceiver extends BroadcastReceiver {

@Override
public final void onReceive(Context context, Intent intent) {
    Intent callIntent = new Intent(context, CallService.class);

    if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
        String phoneState = intent.getStringExtra("state");
        if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            String phoneNumber = intent.getStringExtra("incoming_number");
            callIntent.putExtra("number", phoneNumber);
        } 
    }

    context.startService(callIntent);
    HeadlessJsTaskService.acquireWakeLockNow(context);
}
}

And JS code:

const Call = async (data) => {
  console.log('It works!', data);
  ToastAndroid.show('TEST ' + data.number, ToastAndroid.SHORT);
};
AppRegistry.registerHeadlessTask('Call', () => Call);


from Showing ToastAndroid when app is closed with react-native and Headless JS

No comments:

Post a Comment