Tax*_*Noi 6 android background-service
背景:我正在运行一个后台服务(独立于应用程序打开与否)来保持与 Gear2 上基于 Tizen 的应用程序的连接(不是 Android,因此是手动维护)。
每当我的手机应用程序(多个应用程序)有数据要发送到服务时,我需要在服务中获取“连接”对象并调用“发送”。
所以我的问题是:我怎样才能运行服务对象?
如果我可以获得该服务,我的代码将是这样的:
MyConnection connection = runningService.getConnection()
connect.send(message);
Run Code Online (Sandbox Code Playgroud)
谢谢。
如果它只是您需要定期访问的单个对象(例如连接),我可能会将其设置为单例,它由服务创建并可供应用程序的其他组件使用:
class MyConnection {
private static MyConnection inst;
public static void set(........) { <-------- set by service
}
public static getInstance() { return inst; } <------- and accessible to other components
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您需要与您的服务进行更精细和持续的交互,您可能应该将其设置为绑定服务,并手工制作您希望它实现的接口:
创建绑定服务:
class MyConnectionService extends Service {
private final IBinder myBinder = new MyLocalBinder();
@Override
public IBinder onBind(Intent arg0) {
return myBinder;
}
public ConnectionRecord getConnection() {
return myConnection;
}
public class MyLocalBinder extends Binder {
MyConnectionService getService() {
return MyConnectionService.this;
}
}
}
Run Code Online (Sandbox Code Playgroud)
并从另一个组件绑定到它,例如一个活动:
public class MyActivity extends Activity {
MyConnectionService serviceConnector;
boolean isBound = false;
private ServiceConnection serviceConnector = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MyLocalBinder binder = (MyLocalBinder) service;
serviceConnector = binder.getService(); //<--------- from here on can access service!
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
serviceConnector = null;
isBound = false;
}
};
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
请注意,在 onServiceConnected() 完成后,您将拥有一个可用于与服务通信的serviceConnector 对象,这正是我们的目标。
您不能拥有一个服务的多个实例。所以你只需要通过startService()向它发送命令。
| 归档时间: |
|
| 查看次数: |
8310 次 |
| 最近记录: |