Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将活动实例传递给IntentService_Java_Android - Fatal编程技术网

Java 将活动实例传递给IntentService

Java 将活动实例传递给IntentService,java,android,Java,Android,我正在尝试将我的活动的一个实例传递给意图服务。原因是intent服务执行大量后台服务器通信,如果出现网络错误或服务器返回错误,我希望显示弹出消息 当我创建服务时,我使用这个 Intent service = new Intent(this, SyncService.class); Bundle b2 = new Bundle(); b2.putParcelable(StringsConfig.OBJECT_DELIVERABLES, objects); servi

我正在尝试将我的活动的一个实例传递给意图服务。原因是intent服务执行大量后台服务器通信,如果出现网络错误或服务器返回错误,我希望显示弹出消息

当我创建服务时,我使用这个

    Intent service = new Intent(this, SyncService.class);
    Bundle b2 = new Bundle();
    b2.putParcelable(StringsConfig.OBJECT_DELIVERABLES, objects);
    service.putExtras(b2);
    startService(service);
是否有方法将活动实例传递给它。我在SyncService类中还有一个接受活动的方法,但我不知道如何创建SyncService类的实例,通过该方法传递活动,然后启动同步服务


非常感谢您的帮助。

将活动实例传递给Intent服务不是一个好主意。如果长时间运行的后台服务需要显示对话框消息,那么最好将其建模为意图

只要做:

Intent dialogIntent = new Intent(getApplicationContext(), YourDialogActivity.class);
dialogIntent.putStringExtra(Constants.TITLE, "Your Dialog Title");
dialogIntent.putIntExtra(Constants.MESSAGE, R.string.yourErrorMessageId);
startActivity(dialogIntent);

通过这种方式,服务契约更简洁。

IntentService与活动通信的推荐方式是通过BroadcastReceiver。看看这个例子:

在希望IntentService与之通信的活动中,创建一个BroadcastReceiver,用于侦听特定的intent操作(字符串)。这里我的示例称为batchProcessReceiver,并侦听BATCH\u PROCESS\u RECEIVER操作。批处理接收器可以是活动中的公共静态常量

private BroadcastReceiver batchProcessReceiver = new BroadcastReceiver() {
    @Override public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(BATCH_PROCESS_RECEIVER)) {
            // do what you need to do here
        }
    }
};
在您的活动的onResume中:

registerReceiver(batchProcessReceiver, new IntentFilter(BATCH_PROCESS_RECEIVER));
暂停:

unregisterReceiver(batchProcessReceiver);
然后在您的IntentService中的某个点上,您可以

sendBroadcast(new Intent(MyActivity.BATCH_PROCESS_RECEIVER));

触发您想在活动中执行的操作。

那么您建议从后台服务启动对话意图吗?你能做到吗?你打算做一个新的活动只是为了显示一个对话?我认为这并不能回答问题。这不一定是一项不同的活动。它可以是拦截事件的同一活动(添加新的意图操作)。您可以通过发送广播重新使用现有活动。可能,但您的回答中未指定。另外,当您使用这种方法时,如果活动已经在后台,它将启动它(这可能不是您想要的),而不是像我认为您希望的那样通过onNewIntent,它将通过正常的活动生命周期。