简体   繁体   English

从JobIntentService调用活动方法

[英]Calling an acitivty method from a JobIntentService

I would like to call a non-static method in the for-loop inside the onHandleWork. 我想在onHandleWork内部的for循环中调用一个非静态方法。 How can I achieve that? 我该如何实现?

@Override
protected void onHandleWork(@NonNull Intent intent) {
    Log.d(TAG, "onHandleWork");

    String input = intent.getStringExtra("inputExtra");


    for (int i = 0; i < 10; i++) {
        Log.d(TAG, input + " - " + i);

        new MainActivity.method();

        if (isStopped()) return;

        SystemClock.sleep(1000);
    }
}

You should broadcast a message that the activity is listening instead. 您应该广播一条消息,表明该活动正在监听。

To achieve that, use a broadcastreceiver on the activity and send It from the job service with context.sendBroadcast(intent) 为此,请在活动上使用广播接收器,并使用context.sendBroadcast(intent)从作业服务将其发送

You can make your activity listening by declaring a broadcastreceiver programatically or in the AndroidManifest.xml file. 您可以通过以编程方式或在AndroidManifest.xml文件中声明一个广播接收器来使您的活动监听。 Note that If you declare it programatically, the activity Will only receive the broadcast If It is opened. 请注意,如果以编程方式声明它,则活动仅在打开时才接收广播。 If you use the manifest approach, when you activity is not opened and you send a broadcast, the sustém os going to start your activity 如果您使用清单方法,则在未打开活动并发送广播的情况下,将开始活动

Receiving Broadcasts: https://developer.android.com/guide/components/broadcasts.html#manifest-declared-receivers 接收广播: https : //developer.android.com/guide/components/broadcasts.html#manifest-declared-receivers

Sending Broadcasts: https://developer.android.com/guide/components/broadcasts.html#sending-broadcasts 发送广播: https : //developer.android.com/guide/components/broadcasts.html#sending-broadcasts

Docs: https://developer.android.com/reference/android/content/BroadcastReceiver 文件: https//developer.android.com/reference/android/content/BroadcastReceiver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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