3

I have a service in which I have:

Intent intent = new Intent(ClipboardWatcherService.this, DeliDict.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("searchTerm", searchTerm);
startActivity(intent);

and in my activity:

    @Override
    public void onStart()
    {
            super.onStart();

            Intent intent = getIntent();
            String clipboardSearchTerm = intent.getStringExtra("searchTerm");
            ...
    }

But intent.getStringExtra() always returns null.

NOTE: Because I'm calling StartActivity() from my Service (that's outside an activity class) I have to define Intent.FLAG_ACTIVITY_NEW_TASK causing only ONE instance of my activity be alive at a time. So I have to go inside onStart() since onCreate() is called only once. Basically I've been looking for a reliable way to send data from my Service to the activity for a whole day but in vain. can you suggest something?

4

1 回答 1

2

如果您需要将一些值从Service传递给任何Activity类,您应该使用BroadcastReceiver.

Step1) 您需要先将该BroadcastReceiver注册到该 Activity。为此,您需要为此定义Action

public static final String YOUR_ACTION_STRING = "com.test.android.service.receiver";

现在注册接收方

registerReceiver(receiver, new IntentFilter("YOUR_ACTION_STRING"));

并在此处接收值

private BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
      Bundle bundle = intent.getExtras();
      if (bundle != null) {
        String clipboardSearchTerm = intent.getString("searchTerm");

      }
    }
  };

第 2 步)从服务中,您需要广播消息。

   Intent intent=new Intent();
   intent.setAction("YOUR_ACTION_STRING");
   intent.putExtra("searchTerm", searchTerm);
   sendBroadcast(intent);//Broadcast your message to registered Activity
于 2013-10-27T01:46:27.170 回答