android - 将数据从 Activity 发送到 Service

标签 android android-service

如何将数据从当前 Activity 发送到在特定时间运行的后台 Service 类?我试图设置到 Intent.putExtras() 但我没有在 Service 类中得到它

调用 ServiceActivity 类中的代码。

Intent mServiceIntent = new Intent(this, SchedulerEventService.class);
        mServiceIntent.putExtra("test", "Daily");
        startService(mServiceIntent);

Service 类中的代码。我试图放入 onBind()onStartCommand()。这些方法都不会打印值。

@Override
public IBinder onBind(Intent intent) {
    //Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

    //String data = intent.getDataString();

    Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();

    Log.d(APP_TAG,intent.getExtras().getString("test"));


    return null;
}

最佳答案

您的代码应该是onStartCommand。如果您从不在您的 Activity 上调用 bindService,则不会调用 onBind,并使用 getStringExtra() 而不是 getExtras()

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Toast.makeText(this, "Starting..", Toast.LENGTH_SHORT).show();
    Log.d(APP_TAG,intent.getStringExtra("test"));
    return START_STICKY; // or whatever your flag
}

关于android - 将数据从 Activity 发送到 Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234181/

相关文章:

android - Android 上的 FCM 通知可以覆盖之前的通知吗?

android - 从 android 小部件内部启动 VPNService

android - 为什么我不应该使用消息总线而不是加载器和服务?

android - 我应该在应用程序还活着的时候维护一个连接的 GoogleApiClient 吗?

android - 在 AppBarLayout 上投影

android - 创建签名的 apk 时出现此错误

java - 在媒体播放器上实现后台服务

android 服务通知 Activity 完成的最佳方式?

java - Android 通过 SSL 使用 NTLM 失败

android - 无法恢复 Activity : not allowed to start service Intent, 应用程序在后台