android服务中的数据,android – 如何从服务到活动获取数据

在我的应用程序中,我有一项活动和服务……

该服务将广播从GPS数据收集的消息……

活动应该接收广播消息并更新UI …

我的代码

public class LocationPollerDemo extends Activity {

private static final int PERIOD = 10000; // 30 minutes

private PendingIntent pi = null;

private AlarmManager mgr = null;

private double lati;

private double longi;

private ServiceReceiver serviceReceiver;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

mgr = (AlarmManager) getSystemService(ALARM_SERVICE);

Intent i = new Intent(this, LocationPoller.class);

i.putExtra(LocationPoller.EXTRA_INTENT, new Intent(this, ServiceReceiver.class));

i.putExtra(LocationPoller.EXTRA_PROVIDER, LocationManager.GPS_PROVIDER);

pi = PendingIntent.getBroadcast(this, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

DebugLog.logTrace("On Create Demo");

Toast.makeText(this, "Location polling every 30 minutes begun", Toast.LENGTH_LONG).show();

serviceReceiver = new ServiceReceiver();

IntentFilter filter = new IntentFilter("me");

this.registerReceiver(serviceReceiver, filter);

}

class ServiceReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

File log = new File(Environment.getExternalStorageDirectory(), "Location2.txt");

DebugLog.logTrace(Environment.getExternalStorageDirectory().getAbsolutePath());

try {

BufferedWriter out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), log.exists()));

out.write(new Date().toString());

out.write(" : ");

Bundle b = intent.getExtras();

Location loc = (Location) b.get(LocationPoller.EXTRA_LOCATION);

String msg;

if (loc == null) {

loc = (Location) b.get(LocationPoller.EXTRA_LASTKNOWN);

if (loc == null) {

msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR);

} else {

msg = "TIMEOUT, lastKnown=" + loc.toString();

}

} else {

msg = loc.toString();

}

if (msg == null) {

msg = "Invalid broadcast received!";

}

out.write(msg);

out.write("

");

out.close();

} catch (IOException e) {

Log.e(getClass().getName(), "Exception appending to log file", e);

DebugLog.logException(e);

}

}

}

}

当我使用此代码时,它无法正常工作……

我在单独的文件中使用ServiceReceiver类工作正常….

请告诉我…!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值