我正在尝试将值从服务传递到活动。这是我的工作:
在我的服务中,我有:
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);
...
}
当我调试程序时,我总是得到c
的值为-1,而我从MyServive
传递值2。知道什么是错的吗?