从活动的数据发送到服务 [英] Send data from Activity to Service

查看:202
本文介绍了从活动的数据发送到服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从当前的活动将数据发送到一个背景,是在一定的时间运行服务类?我试图设置为 Intent.putExtras(),但我没有得到它在<​​code>服务类

code在活动类,它调用服务

 意图mServiceIntent =新意图(这一点,SchedulerEventService.class);
        mServiceIntent.putExtra(测试,人民日报);
        startService(mServiceIntent);

code在服务类。我TREID摆在 onBind() onStartCommand()。这些方法没有打印的价值。

  @覆盖
公众的IBinder onBind(意向意图){
    //Toast.makeText(this,服务启动,Toast.LENGTH_SHORT).show();    //字符串数据= intent.getDataString();    Toast.makeText(这一点,启动..,Toast.LENGTH_SHORT).show();    Log.d(APP_TAG,intent.getExtras()的getString(测试));
    返回null;
}


解决方案

您code应该onStartCommand。如果你从来没有叫你的活动onBind不会被调用bindService,并使用getStringExtra()而不是getExtras()

  @覆盖
    公众诠释onStartCommand(意向意图,诠释旗帜,INT startId)
    {
       Toast.makeText(这一点,启动..,Toast.LENGTH_SHORT).show();
       Log.d(APP_TAG,intent.getStringExtra(测试));
       返回START_STICKY; //或任何你的旗帜
    }

How can I send data from the current Activity to a background Service class which is running at certain time? I tried to set into Intent.putExtras() but I am not getting it in Service class

Code in Activity class which calls the Service.

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

Code in Service class. I treid to put in onBind() and onStartCommand(). None of these methods prints the value.

@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;
}

解决方案

Your code should be onStartCommand. If you never call bindService on your activity onBind will not be called, and use getStringExtra() instead of 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
    }

这篇关于从活动的数据发送到服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆