为什么我不能将数据从服务发送到活动?

时间:2013-09-14 19:58:51

标签: android

这个代码在服务中我尝试将数据从服务发送到活动,但它不起作用,

public void onStart(Intent intent, int startId) {

// TODO Auto-generated method stub

  super.onStart(intent, startId);
  Toast.makeText(this, "onstart()",Toast.LENGTH_SHORT).show();

  String message = intent.getStringExtra("msg");
  int ID = intent.getExtras().getInt("id");
  Toast.makeText(getApplication(), message, Toast.LENGTH_LONG).show();
  NotificationManager notificationmanager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

  Intent notificationintent = new Intent(this, Details.class);

  notificationintent.putExtra("ID", ID);

  PendingIntent pendingintent = PendingIntent.getActivity(this,ID, notificationintent,0);

  int icon = R.drawable.ic_launcher;
  String tickerText = "you have a massege";
  long when = System.currentTimeMillis();
  Notification notification = new Notification(icon, tickerText, when);

  String contentTitle = "Title";
  String contentText = message;
  notification.setLatestEventInfo(this, contentTitle, contentText, pendingintent);
  notification.defaults = notification.DEFAULT_SOUND;

  notificationmanager.notify(ID, notification);

这是活动

Intent i = new Intent();
int num = i.getExtras().getInt("ID");
number.setText(num); // number is textview 

2 个答案:

答案 0 :(得分:2)

更改您的活动代码 -

  int num = getIntent().getIntExtra("ID", 0);

  number.setText(String.valueOf(num)); // number is textview 

答案 1 :(得分:0)

我不知道你可以直接从服务到活动进行沟通。请记住,服务可能独立于任何活动而运行。您可以通过startService调用从活动到服务进行通信,传递意图。

为了与活动进行通信,活动必须绑定到服务: http://developer.android.com/guide/components/bound-services.html

另一个选项是服务可以发送广播,活动可以通过传递给广播接收器的处理程序获取消息。