在我的应用中,我想通过POST每隔十秒将传感器数据发送到网络服务器。
我这样做是为了启动/停止正在调用IntentService的AlarmMananger
的活动。
问题是:目标网址是在活动中生成的,并没有到达IntentService。
的活动:
public class MyActivity extends AppCompatActivity {
...
@Override
protected void onResume() {
super.onResume();
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
String targetURL = "www.google.de";
alarmIntent.putExtra("targetURL", targetURL);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pendingIntent);
}
...
}
广播接收器:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String targetURL = intent.getStringExtra("targetURL");
Intent newintent = new Intent(context, SendPostRequest_Service.class);
newintent.putExtra("targetURL", targetURL);
context.startService(newintent);
}
}
意图服务:
public class SendPostRequest_Service extends IntentService implements SensorEventListener{
...
public SendPostRequest_Service() {
super(SendPostRequest_Service.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
String targetURL = intent.getStringExtra("targetURL");
// Problem: targetURL = null
//read sensors, send POST-Request via okhttp <- working
}
...
}
你有什么建议吗?
答案 0 :(得分:0)
您需要在Control Text Color
中使用唤醒锁,然后在BroadcastReceiver
中将其释放。否则,系统可能会在Service
有机会运行之前返回睡眠状态。 Service
对此特别有用。如果您想了解更多详情,请参阅此文章:http://hiqes.com/android-alarm-ins-outs/
答案 1 :(得分:0)
将您的代码放入测试项目中。我能够让它工作的唯一方法是改变将额外添加到意图的顺序。使用以下更新MyActivty。对于G. Blake Meike来说,似乎有一份意图的副本。
@Override
protected void onResume() {
super.onResume();
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
String targetURL = "www.google.de";
alarmIntent.putExtra("targetURL", targetURL);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pendingIntent);
}