简体   繁体   中英

Run and get event from Broadcast Receiver even when app is killed

I want to make application like TrueCaller. For that i need to get event of incoming call. For that i make Broadcast Receiver and it works fine till app is going to be killed.

So i want to make run my Broadcast receiver even if app is killed.

Previously i used Service for achieve this but in After Android O Service is not working. I thought that i can archive it by using WorkManager but i couldn't understand how to do it. So i want Service alternative or right way to archive this.

Please help me to do it.

Thanks in advance.

CallEventBroadcastReceiver.java

public class CallEventBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
  TelephonyManager telephonyManager = (TelephonyManager) 
context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String phoneNumber) {
        super.onCallStateChanged(state, phoneNumber);
        try {
            if (state == TelephonyManager.CALL_STATE_RINGING) {
                Log.e("phoneNumber", phoneNumber);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
    }, PhoneStateListener.LISTEN_CALL_STATE);
  }
}

Try something like this. Unfortunately, I can offer you a possible solution for your issue only in Kotlin .

private lateinit var workManager: WorkManager

override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
        val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE)
        state?.let { it ->
            if (it == TelephonyManager.EXTRA_STATE_RINGING) {
                val incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
                incomingNumber.let { number ->
                            val data = Data.Builder()
                                .putString("phoneNumber", number)
                                .build()
                            workManager = WorkManager.getInstance(context)
                            val notificationBuilder = OneTimeWorkRequest.Builder(NotifyWorker::class.java)
                                .setInputData(data)
                                .build()
                            workManager.enqueue(notificationBuilder)
                }
            }
       }
}

And the NotifyWorker class:

class NotifyWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    companion object {
        const val CHANNEL_ID = "NotificationChannel"
        const val CHANNEL_NAME = "Notification"
    }

    private val mContext = context

    override fun doWork(): Result {
        triggerNotification()
        return Result.success()
    }

    private fun triggerNotification() {
        val notificationManager =
            mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

        val notificationIntent = Intent(mContext, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(mContext, 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        val notification = NotificationCompat.Builder(mContext, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_phone_call)
            .setContentTitle("incoming call")
            .setContentText(inputData.getString("phoneNumber"))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setCategory(NotificationCompat.CATEGORY_CALL)
            .setFullScreenIntent(pendingIntent, true)
            .setAutoCancel(true)

        notification.setContentIntent(pendingIntent)
        notificationManager.notify(1, notification.build())
    }
}

Add the receiver in your AndroidManifest file.

<receiver
            android:name=".receiver.IncomingCallReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.READ_CALL_LOG" />
            </intent-filter>
</receiver>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM