gpt4 book ai didi

android - 从服务向 Activity 发送额外的 Intent

转载 作者:行者123 更新时间:2023-11-30 03:43:02 25 4
gpt4 key购买 nike

我有一个监听 (ON_BATTERY_CHANGE) 的服务,然后 onReceive 服务向我的 MainActivity 发送广播。问题是我无法以某种方式让它们从服务到我的主要 Activity 。代码:主要 Activity :

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);
}

知道为什么我的信息没有正确传输吗?

最佳答案

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

尝试在发送广播之前添加一些日志记录以检查 Intent 的 Action 是否正确,或者简单地在 onReceive 方法中创建广播 Intent 并将其命名为 intent2。

关于android - 从服务向 Activity 发送额外的 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15450216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com