【发布时间】:2023-03-27 04:31:01
【问题描述】:
我想要的是当我点击按钮时,立即启动服务。一旦启动服务,立即进入另一个活动。
这是我实现它的代码:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//here I start the service
Intent intent = new Intent(MyActivity.this, UploadService.class);
intent.putExtra(UploadService.ID,id);
startService(intent);
//after start the service,I want to redirect to Activity2.class
Intent intent1 = new Intent(MyActivity.this,Activity2.class);
startActivity(intent1);
}
}
但是当我这样做时,服务没有启动,也没有重定向到Activity2.class,而是重定向到上一个活动。
我在Service.class的onHandleIntent(Intent intent)里面试过intent,问题还是一样
这是我在 UploadService.class 中尝试过的:
@Override
protected void onHandleIntent(Intent intent) {
//other code here
Intent intent1 = new Intent(MyActivity.this,Activity2.class);
startActivity(intent1);
}
但是服务仍然没有启动,intent 到上一个活动(MyActivity.class 意图来自的活动)。
那么如何在启动Service 后立即重定向到另一个activity?
编辑:
我已经在清单中声明了UploadService,如下所示:
<service
android:name=".services.UploadService"
android:enabled="true">
</service>
那么我在这里还缺少什么??
【问题讨论】:
-
如果您从 Service 调用 this,为什么要使用 MyActivity.this 上下文?
-
因为如果只是使用
.this它无法解决..如果我做错了请告诉我正确的方法,愿意学习 -
@ken 更新您的服务清单声明并确保服务类扩展服务。
标签: java android android-intent service