在Worker类内部调用BroadcastReceiver类

时间:2019-05-27 13:09:18

标签: android android-broadcast android-workmanager

根据我的要求,我想在Worker类调用BroadcastReceiver类中进行调用,任何人都可以提出一些建议。

// BroadcastReceiver sample class 
public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("??????","Working fine");
    }
}


// workers class 
class WorkSample(context: Context, workerParams: WorkerParameters) :  Worker(context, workerParams) {
    override fun doWork(): Result {

       // BroadcastReceiver class
         NetworkChangeReceiver()

         return Result.success()
     }

 }


//Activity  
button.setOnClickListener {
     // request of workmanager 
     val constraints  = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()

     val OneTimeWorkRequest = OneTimeWorkRequest.Builder(WorkSample::class.java).setConstraints(constraints).build()
     WorkManager.getInstance().enqueue(OneTimeWorkRequest)
}

1 个答案:

答案 0 :(得分:1)

您可以在doWork()方法内部

进行调用
override fun doWork(): Result {
     val i = Intent(applicationContext, NetworkChangeReceiver::class.java)
     applicationContext.sendBroadcast(i)

     return Result.success()
}