我有一个监听 ( ON_BATTERY_CHANGE
) 的服务,然后 onReceive 服务向 My MainActivity 发送一个广播。问题是我无法将它们从服务中转移到我的主要活动中。代码:主要活动:
public class MainActivity extends Activity
private BroadcastReceiver batteryReceiverService;
private TextView text2;
....
protected void onCreate(Bundle savedInstanceState) {
text2=(TextView)findViewById(R.id.TV_text2);
batteryReceiverService = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
text2.setText("left: "+intent.getStringExtra("H")+" hours "+intent.getStringExtra("M")+" minute(s)");
Log.e("text2","text2 HHH " +intent.getStringExtra("H")); //log shows 0
Log.e("text2","text2 MMM " +intent.getStringExtra("H")); // log shows 0
}
};
registerReceiver(batteryReceiverService, new IntentFilter(UltimateBatterySaverService.BROADCAST_ACTION));
....
@Override
protected void onDestroy() {
unregisterReceiver(batteryReceiverService);
super.onDestroy();
}
服务:
public class UltimateBatterySaverService extends Service {
private Intent intent;
static final String BROADCAST_ACTION = "lt.whitegroup.ultimatebatterysaver";
private BroadcastReceiver batteryLevelReceiver;
....
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
@Override
public void onDestroy() {
unregisterReceiver(batteryLevelReceiver);
super.onDestroy();
}
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryLevelReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
// Receiving data, calculating and etc
averageChargingH=timeAllInHours;
averageChargingM=timeAllInMinutes;
// to put extras and send broadcast
does();
......
public void does(){
String strLong = Long.toString(averageChargingH);
String strLong2 = Long.toString(averageChargingM);
Log.e("cccccc","strLong h "+strLong); // getting good value not 0(everything ok)
Log.e("cccccc","strLong2 m"+strLong2); // getting good value not 0(everything ok)
intent.putExtra("H", strLong);
intent.putExtra("M", strLong2);
sendBroadcast(intent);
}
任何想法为什么我的信息没有正确传输?