android - 如何从服务获取数据到 Activity

标签 android

在我的应用中,我有一个 Activity 和一个服务...... 该服务将广播从 GPS 数据收集的消息... Activity 应该接收广播消息并更新 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("\n");
                out.close();
            } catch (IOException e) {
                Log.e(getClass().getName(), "Exception appending to log file", e);
                DebugLog.logException(e);
            }
        }
    }
}

当我使用此代码时,它无法正常工作... 我在单独的文件中使用 ServiceReceiver 类工作正常.... 请告诉我...!!

最佳答案

在我的服务类中我写了这个

private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

在 Activity 端,我们必须接收这个广播消息

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

通过这种方式,您可以向 Activity 发送消息。 这里 mMessageReceiver 是该类中的类,您将执行任何您想要的操作....

在我的代码中我这样做了......

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("Status");
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));
            tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
            tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                    .toString()));
            tvProvider.setText(lastKnownLoc.getProvider());
        }
        tvStatus.setText(message);
        // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
};

关于android - 如何从服务获取数据到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125241/

相关文章:

android - 无法初始化 OpenGL 渲染器库

android - 模拟 Chrome 自定义标签回退

java - 水平 EditText 一次滚动一个字符

Android 项目从 Eclipse 中消失

android - map Android V2 : java. lang.noclassdefounderror : com. google.android.gms.R$styleable

android - Android 环境中的 "scrim"是什么?

android - 如何暂停父 Activity 直到子 Activity 完成

android - 具有两个不同对象的不同布局的 ListView

java - LongClick 事件也会触发 Click 事件

android - 如何将Image的选定区域设置为ImageView