gpt4 book ai didi

java - onStartCommand 未与 startService 一起调用

转载 作者:行者123 更新时间:2023-12-02 10:01:43 25 4
gpt4 key购买 nike

我想从我的 Activity 类(class)中启动一项服务。问题是,onStartCommand 永远不会被调用。我在那里放置了断点,但它从未被击中。我的例子非常简单,我不明白为什么它不起作用。

MainActivity.java:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent serviceIntent = new Intent(TestService.class.getName());
serviceIntent.putExtra("UserID", "123456");
serviceIntent.setPackage(this.getPackageName());
startService(serviceIntent);
}
}

如果我删除 serviceIntent.setPackage(this.getPackageName()); 我收到以下错误:

java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=package.TestService (has extras) }

这就是为什么我添加它来消除这个错误。但它仍然不起作用。

TestService.java:

public class TestService extends Service {
public TestService() {
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}

AndroidManifest.xml:

<application
...
<service
android:name=".TestService"
android:enabled="true"
android:exported="true"></service>
...
</application>

最佳答案

请尝试一下

Add in Activity class

Intent serviceIntent = new Intent(MainActivity.this, TestService.class);
serviceIntent.putExtra("UserID", "123456");
startService(serviceIntent);

关于java - onStartCommand 未与 startService 一起调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55570604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com