这是一个广泛的代码示例。
启动时,Activity 将实例呈现给 Application。我们的应用程序将存储主 Activity 的实例(或者换句话说,Activity 的接口)
看GuiServiceBridgeItf gsb
片段应用程序类
public class MyApplication extends Application{
private static mYApplication mSingleton;
public GuiServiceBridgeItf gsb = null;
@Override
public void onCreate() {
super.onCreate();
mSingleton = this;
}
public mYApplication getApp(){
return mSingleton;
}
....
}
GuiServiceBridgeItf接口
public interface GuiServiceBridgeItf {
public void onEventReceived(String str);
/** Notify activity about service run */
public void imHere();
....
}
这是我们实现相同接口的服务GuiServiceBridgeItf
。
MyService
运行 2 个线程:
一个线程运行一些逻辑(在我们的例子中,每秒通知 CPU 上的 Activity)
第二个通知主 Activity 如果 Service 运行(最好将此任务提供给 Activity 以询问 Service 是否运行)
public class MyService extends Service implements GuiServiceBridgeItf {
....
private RunnerThread runner = null;
private CheckAliveThread checkalive = null;
private MyApplication mMyApp = null;
public void onCreate() {
super.onCreate();
mMyApp = (MyApplication)getApplicationContext();
}
public int onStartCommand(Intent intent, int flags, int startId) {
GuiServiceBridgeItf gui2ServiceTalker = this;
checkalive = new CheckAliveThread();
checkalive.init(mMyApp);
checkalive.start();
runner = new RunnerThread(this.getApplicationContext(), gui2ServiceTalker);
runner.start();
...
return START_STICKY;
}
public void onDestroy() {
super.onDestroy();
...
runner.doDestroy();
runner = null;
checkalive.doDestroy();
checkalive = null;
stopSelf();
}
private boolean isInstanceActive(){
if(mMyApp.gsb == null){
return false;
}
return true;
}
public void imHere() {}
public void onEventReceived(String str) {
if(isInstanceActive()){
mMyApp.gsb.onEventReceived(str);
}
}
...
}
这里的主要方法是:boolean isInstanceActive()
返回true
或false
开启
Activity状态。换句话说,如果我们关闭 Activity,我们会从 Application 中注销它的实例。因为onDestroy
main Activity 中的方法会重置MyApplication.gsb
。
另一方面,当我们重新启动新的 Activity 时,我们再次将其注册到 Application,(见下文)
public class LauncherUI extends Activity implements GuiServiceBridgeItf{
....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// register Activity to Application
GuiServiceBridgeItf gts = this;
mApplicationApp = (MyApplication)mContext.getApplicationContext();
mApplicationApp .gsb = gts;
....
}
....
@Override
protected void onDestroy() {
super.onDestroy();
....
// Unregister Activity to prevent to Service to talk with
mMyApplication.gsb = null;
}
}
Service 通过使用他的 Thread 验证 Activity注册到 Application 并因此继续通知新生Activity 有关 CPU 更改。现在 Activity 可以将按钮名称更新为“停止服务”并执行其他操作