android - 在服务中调用 getIntent 方法

标签 android service android-intent

我必须将参数从 MyActivity.class 传递给 TestService.class。 MyActivity 是一个 Activity 类,而 TestService 是我为发送消息而制作的一个服务。我必须将参数从 Activity 传递给服务,但是当我在服务类中调用 Intent i = getIntent(); 时,我收到一个错误 getIntent() is undefined .

那么,如何将参数从我的 Activity 发送到 Service?

最佳答案

像这样开始你的服务;

 Intent ir=new Intent(this, Service.class); 
 ir.putExtra("data", data); 
 this.startService(ir); 

您附加您的数据作为额外的 Intent 。

然后从服务中检索数据;

data=(String) intent.getExtras().get("data"); 

因此,您可以从 onHandleIntent 或 onStartCommand Intent 参数访问您的参数。 (取决于您正在运行的服务类型)例如;

服务

protected void onStartCommand (Intent intent, int flags, int startId) {
    data=(String) intent.getExtras().get("data"); 
}

public int onStartCommand (Intent intent, int flags, int startId)

IntentService

protected void onHandleIntent(Intent intent) {
    data=(String) intent.getExtras().get("data"); 
}

protected abstract void onHandleIntent (Intent intent)

关于android - 在服务中调用 getIntent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11949248/

相关文章:

android - 如何实现注销功能

android - 未找到 JNI_OnLoad 跳过 init > 应用程序关闭

android - NDK12b : Different ELF produced by clang vs gcc using the standalone toolchain and the same build scripts

android - 了解前台服务生命周期

javascript - 使用 WMI 查找服务的依赖项,然后区分依赖的服务和依赖的驱动程序

service - Zend Framework 2 覆盖现有服务?

android - Android中有什么方法可以获取设备虚拟键盘的高度

C++代码交叉编译到ARM,运行时崩溃

java - Putextra 不断发送第一个输入的数据

android - 为什么我不能在 Android N+ 中附加文件?