1

我有一个监听 ( 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);
    }

任何想法为什么我的信息没有正确传输?

4

1 回答 1

1

dos() 方法似乎使用与 onReceive 相同范围内的变量,所以我猜测 dos() 中的意图变量实际上是从 onReceive 传入的 Intent。

尝试在发送广播之前添加一些日志以检查意图的操作是否正确,或者只是在 onReceive 方法中创建广播意图并将其命名为 intent2。

于 2013-03-16T15:18:53.163 回答