【问题标题】:How to start service and redirect to another activity in a same time?如何同时启动服务并重定向到另一个活动?
【发布时间】: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.classonHandleIntent(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


【解决方案1】:

确保您已在 manifest.xml 中注册您的服务类。 尝试将您的服务类名称从“服务”更改为其他名称。由于 Service.java 类是 System 类。

尝试像下面这样启动服务

startService(new Intent(context, MyService.class));

编辑

更多说明首先检查您的应用程序是否正在运行。如果您的应用程序没有运行,请调用此代码。

Intent i = new Intent(context,SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
context.startActivity(i); 

如果运行则使用此代码

Intent i = new Intent(context,SecondActivity.class);    
context.startActivity(i); 

【讨论】:

  • 我已经在manifest中声明了,Service只是写在这里,实际不是Service.class
  • 我需要 putExtra 到意图,如果 startService 使用你的解决方案,我怎么能 putExtra?
  • startService(new Intent(context, MyService.class).putExtra(Service.ID,id));试试这个
  • 但是在启动服务后如何将另一个意图转移到另一个?你的回答似乎没有提到这个
  • 你检查过..我在serviceonStart的编辑部分使用你的代码,但它不起作用,仍然和我的问题中所说的一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多