0

我正在尝试将服务中的值传递给活动。这是我所做的:

在我的服务中,我有:

public class MyService extends Service {
  ...
  private long b;
  public static final String BROADCAST_ACTION = "test";
  private final Handler handler = new Handler();
  Intent intentDisp;
  ...
  @Override
  public void onCreate() {
    ...
    b = 0;
    intentDisp = new Intent(BROADCAST_ACTION);
    ...
  }

  @Override
  public int onStartCommand( Intent intent, int flags, int startId ) {
    handler.removeCallbacks(sendUpdatesToUI);
    handler.postDelayed(sendUpdatesToUI, 1000); // 1 second  
    ...
  }

  private Runnable sendUpdatesToUI = new Runnable() {
  public void run() {
     b = (long) 2.0;
     intentDisp.putExtra("connected", b);
     sendBroadcast(intentDisp);             
     handler.postDelayed(this, 2000); // 5 seconds
  }
};

在我的主要活动中,我有:

public class MainActivity extends Activity implements OnClickListener {
  ...
  private Intent intentDisp1;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    ...
    intentDisp1 = new Intent(this, MyService.class);
  }

  private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        updateUI(intent);       
    }
  };

  @Override
  public void onResume() {
    super.onResume();       
    startService(intentDisp1);
    registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
  }

  @Override
  protected void onPause() {
   super.onPause();
   unregisterReceiver(broadcastReceiver);
   stopService(intentDisp1); 
  }

  private void updateUI(Intent intent) {
  long c = intentDisp1.getLongExtra("connected",-1);
      ...
  }

当我调试程序时,我总是得到 -1 的值,c而我从MyServive. 知道有什么问题吗?

4

0 回答 0