我有一个服务在不断检查新的任务。如果有新的任务,我想刷新活动UI以显示该信息。 我找到了这个https://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/示例。这是一个好方法吗?还有其他示例吗?
谢谢。
我有一个服务在不断检查新的任务。如果有新的任务,我想刷新活动UI以显示该信息。 我找到了这个https://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/示例。这是一个好方法吗?还有其他示例吗?
谢谢。
public class AndroidBmService extends Service implements BmService {
private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates
private SensorManager sensorManager;
private SensorEventListener pressureListener;
private ObservableEmitter<Float> pressureObserver;
private Observable<Float> pressureObservable;
public class LocalBinder extends Binder {
public AndroidBmService getService() {
return AndroidBmService.this;
}
}
private IBinder binder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
logMsg("Service bound");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(pressureSensor != null)
sensorManager.registerListener(pressureListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if(pressureObserver != null) {
float lastPressure = event.values[0];
float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
pressureObserver.onNext(lastPressureAltitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, pressureSensor, PRESSURE_RATE);
}
@Override
public Observable<Float> observePressure() {
if(pressureObservable == null) {
pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
pressureObservable = pressureObservable.share();
}
return pressureObservable;
}
@Override
public void onDestroy() {
if(pressureListener != null)
sensorManager.unregisterListener(pressureListener);
}
}
一个与服务绑定并接收气压高度更新的Activity:
public class TestActivity extends AppCompatActivity {
private ContentTestBinding binding;
private ServiceConnection serviceConnection;
private AndroidBmService service;
private Disposable disposable;
@Override
protected void onDestroy() {
if(disposable != null)
disposable.dispose();
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.content_test);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
logMsg("BlueMAX service bound");
service = ((AndroidBmService.LocalBinder)iBinder).getService();
disposable = service.observePressure()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(altitude ->
binding.altitude.setText(
String.format(Locale.US,
"Pressure Altitude %d feet",
altitude.intValue())));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
logMsg("Service disconnected");
}
};
bindService(new Intent(
this, AndroidBmService.class),
serviceConnection, BIND_AUTO_CREATE);
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.controlj.mfgtest.TestActivity">
<TextView
tools:text="Pressure"
android:id="@+id/altitude"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
如果服务需要在后台运行且没有绑定的Activity,也可以从Application类中使用OnCreate()
和Context#startService()
启动。
我的原始答案(来自2013年):
在您的服务中:(以下示例中使用COPA作为服务)。
使用LocalBroadcastManager。 在服务的onCreate中设置广播:
broadcaster = LocalBroadcastManager.getInstance(this);
当您想要通知UI某些事情时:
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.copa);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
// do something here.
}
};
}
并在 onStart 中注册它:
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(COPAService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
onStart()
或onResume()
方法中向服务发送适当的请求。通常情况下,如果Activity要求Service执行某些操作,但在接收结果之前退出了,则可以合理地假设不再需要结果。同样,在启动Activity时,它应该假定Service没有正在处理的未完成请求。 - Clyde对我来说最简单的解决方案是发送广播,在Activity的oncreate中我注册并定义了广播,如下所示(updateUIReciver被定义为一个类实例):
IntentFilter filter = new IntentFilter();
filter.addAction("com.hello.action");
updateUIReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//UI update here
}
};
registerReceiver(updateUIReciver,filter);
然后你可以像这样从服务中发送意图:
Intent local = new Intent();
local.setAction("com.hello.action");
this.sendBroadcast(local);
不要忘记在Activity onDestroy()方法中取消注册该监听器:
unregisterReceiver(updateUIReciver);
我会使用绑定服务来完成这个任务,并通过在我的活动中实现一个监听器与其通信。所以,如果您的应用程序实现了myServiceListener,您可以在绑定服务后将其注册为监听器,在绑定服务后从您的绑定服务中调用listener.onUpdateUI,然后在那里更新您的UI!
Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
//process results or update UI
}
}
Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);
Clyde的解决方案是可行的,但它是一种广播方式,我相信直接调用方法将会更有效率。我可能错了,但我认为广播更适合应用程序间通信。
我假设你已经知道如何将服务与活动绑定。 我做的处理这种问题的代码类似于以下代码:
class MyService extends Service {
MyFragment mMyFragment = null;
MyFragment mMyOtherFragment = null;
private void networkLoop() {
...
//received new data for list.
if(myFragment != null)
myFragment.updateList();
}
...
//received new data for textView
if(myFragment !=null)
myFragment.updateText();
...
//received new data for textView
if(myOtherFragment !=null)
myOtherFragment.updateSomething();
...
}
}
class MyFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=null;
}
public void updateList() {
runOnUiThread(new Runnable() {
public void run() {
//Update the list.
}
});
}
public void updateText() {
//as above
}
}
class MyOtherFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=null;
}
public void updateSomething() {//etc... }
}
我省略了线程安全的部分,这是必要的。在检查、使用或更改服务上的片段引用时,请务必使用锁或类似的东西。
Service
上的数据,并在Activity
上每秒更新一次您的视图。Service
上有一个String
要发送到Activity
上的TextView
,应该像这样:public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
您的活动:
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
Android
的环境下,如果是列表,尝试创建一个适配器或使用sqllite/realm数据库来持久化数据。 - Murtaza Khursheed Hussain这个Fragment "观察" LiveData(即SyncLogLiveData)并在LiveData更改时执行动作。
LiveData由Service更新。
我也可以以同样的方式从Fragment更新LiveData,但这里不展示。
类 SyncLogLiveData
public class SyncLogLiveData extends LiveData<SpannableStringBuilder> {
private static SyncLogLiveData sInstance;
private final static SpannableStringBuilder log = new SpannableStringBuilder("");
@MainThread
public static SyncLogLiveData get() {
if (sInstance == null) {
sInstance = new SyncLogLiveData();
}
return sInstance;
}
private SyncLogLiveData() {
}
public void appendLog(String text) {
log.append(text);
postValue(log);
}
public void appendLog(Spanned text) {
log.append(text);
postValue(log);
}
}
在类SyncService
中
这行代码将会更新LiveData的内容。
SyncLogLiveData.get().appendLog(message);
LiveData
的 setValue(...)
或 postValue(...)
方法。SyncLogLiveData.get().setValue(message);
类 SyncFragment
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
//...
// Create the observer which updates the UI.
final Observer<SpannableStringBuilder> ETAObserver = new Observer<SpannableStringBuilder>() {
@Override
public void onChanged(@Nullable final SpannableStringBuilder spannableLog) {
// Update the UI, in this case, a TextView.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
textViewLog.setText(spannableLog);
}
});
}
};
// Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer.
SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver);
//...
}
在活动中,它的工作方式相同,但对于.observe(...)
,您可以改用此方法
SyncLogLiveData.get().observe(this, ETAObserver);
SyncLogLiveData.get().getValue();
希望这能对某人有所帮助。在这个答案中还没有提到LiveData。