[英]How can I use an application class in order to start a service and use it in my activities?
I have a service, two activities and an extended application. 我有一项服务,两项活动和一个扩展的应用程序。 So my concern is, that if I implement the application in an activity it gets lost after I switch to the next activity.
所以我担心的是,如果我在一个活动中实现该应用程序,那么在切换到下一个活动后它就会丢失。 The idea is to use a service object in both of these activities with the help of my application class.
这个想法是在我的应用程序类的帮助下,在这两个活动中都使用服务对象。 So how do I have to implement it to have the same application class in both of my activities?
那么,如何在两个活动中都实现相同的应用程序类呢?
public class AppController extends Application {
boolean bound = false;
private static AppController mInstance;
private LocalService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((LocalService.LocalBinder) service).getService();
System.out.println("Connected!!!!");
bound = true;
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
bound = false;
}
};
public static synchronized AppController getInstance() {
return mInstance;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
public void startService(){
//start your service
}
public void stopService(){
//stop service
}
public LocalService getService(){
return mBoundService;
}
}
The answer is to implement it in an application class like this 答案是在这样的应用程序类中实现它
public class AppController extends Application {
boolean bound = false;
private static AppController mInstance;
private LocalService mBoundService;
/**
* The Background Service, which is started to communicate with multiple activities
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((LocalService.LocalBinder) service).getService();
System.out.println("Connected!!!!");
bound = true;
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
bound = false;
}
};
public static synchronized AppController getInstance() {
return mInstance;
}
/**
* With the start of app controller, the Service starts too
*/
public void onCreate() {
startService(new Intent(this, LocalService.class));
doBindService();
super.onCreate();
}
public void startService(){
}
void doBindService() {
bindService(new Intent(this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
}
public void stopService(){
//stop service
}
public LocalService getService(){
return mBoundService;
}
public void test(){
System.out.println("Test");
}
}
With a BroadCastReceiver you can then communicate with the activities. 然后,您可以使用BroadCastReceiver与活动进行通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.