5

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

Activity中调用Service.

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

课堂上的代码Service。我很想输入onBind()and 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;
}
4

2 回答 2

4

你的代码应该是onStartCommand. 如果您从不调用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
}
于 2013-03-05T21:22:39.790 回答
1

如果你想传递可以放入 Intent 的原始数据类型,我建议使用 IntentService。要启动 IntentService,请输入您的活动:

startService(new Intent(this, YourService.class).putExtra("test", "Hello work");

然后创建一个扩展 IntentService 类的服务类:

public class YourService extends IntentService {

String stringPassedToThisService;

public YourService() {
    super("Test the service");
}

@Override
protected void onHandleIntent(Intent intent) {

    stringPassedToThisService = intent.getStringExtra("test");

    if (stringPassedToThisService != null) {
        Log.d("String passed from activity", stringPassedToThisService);
    // DO SOMETHING WITH THE STRING PASSED
    }
}
于 2013-03-05T21:48:15.750 回答