我有一个活动,它填充框架布局和 MapFragment 。地图标记应该每隔几分钟更新一次,所以我想我可以使用服务来生成http请求。
问题是,这项服务(尚未实施)如何能够传达或更新我的MapFragment UI以及一些主要活动的用户界面?
答案 0 :(得分:0)
您可以通过注册广播接收器来更新您的活动/片段。
答案 1 :(得分:0)
您可以通过服务接收活动的更新,请参阅此计数器示例以获取帮助。
<强> CounterUpdates.java 强>
package yourPackage;
public class CounterUpdates {
private static CounterUpdates mInstance;
private ICounterUpdates mListener;
private CounterUpdates() {}
public static CounterUpdates getInstance() {
if(mInstance == null) {
mInstance = new CounterUpdates();
}
return mInstance;
}
public void setListener(ICounterUpdates listener) {
mListener = listener;
}
public void onCountUpdate(int count) {
if(mListener != null) {
mListener.onCountUpdate(count);
}
}
// Definition of location updates interface
public interface ICounterUpdates {
public void onCountUpdate(int count);
}
}
<强> CounterService.java 强>
package yourPackage;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class CounterService extends Service {
private Handler mHandler = new Handler();
private int mCount = 0;
private static final int INTERVAL = 500;
private Runnable mRunnableCounter = new Runnable() {
@Override
public void run() {
deliverResults(++mCount);
mHandler.postDelayed(this, INTERVAL);
}
};
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
startCounterThread();
return START_STICKY;
}
private void startCounterThread() {
mCount = 0;
mHandler.postDelayed(mRunnableCounter, INTERVAL);
}
private void stopCounterThread() {
mHandler.removeCallbacks(mRunnableCounter);
}
public static void deliverResults(int count) {
CounterUpdates.getInstance().onCountUpdate(count);
}
@Override
public void onDestroy() {
super.onDestroy();
stopCounterThread();
}
@Override
public IBinder onBind(final Intent intent) {
return null;
}
}
AndroidManifest.xml (注册您的服务)
<service android:name="yourPackage.CounterService" />
启动服务使用此代码:
startService(new Intent(this, CounterService.class));
<强> YourActivity.java 强>
public class YourActivity extends Activity implements CounterUpdates.ICounterUpdates {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
CounterUpdates.getInstance().setListener(this);
}
@Override
public void onCountUpdate(int count) {
((TextView) findViewById(R.id.textView)).setText("Count: " + count);
}
}
我希望它能奏效,祝你好运:)