1.编写全局Application,便于管理系统启动退出时的Activity,Service等管理
public class ChatApplication extends Application { private List<Activity> activitys = new LinkedList<Activity>(); private List<Service> services = new LinkedList<Service>(); @Override public void onCreate() { super.onCreate(); } public void addActivity(Activity activity) { activitys.add(activity); } public void removeActivity(Activity activity) { activitys.remove(activity); } public void addService(Service service) { services.add(service); } public void removeService(Service service) { services.remove(service); } public void closeApplication() { closeActivitys(); closeServices(); } private void closeActivitys() { ListIterator<Activity> iterator = activitys.listIterator(); while (iterator.hasNext()) { Activity activity = iterator.next(); if (activity != null) { activity.finish(); } } } private void closeServices() { ListIterator<Service> iterator = services.listIterator(); while (iterator.hasNext()) { Service service = iterator.next(); if (service != null) { stopService(new Intent(this, service.getClass())); } } } }
2. 编写AndroidManifest.xml
<application android:name="com.cbooy.chat.ChatApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.cbooy.chat.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
3. 编写BaseActivity和BaseService
public abstract class BaseActivity extends FragmentActivity { @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); ((ChatApplication) getApplication()).addActivity(this); } @Override protected void onDestroy() { super.onDestroy(); ((ChatApplication) getApplication()).removeActivity(this); } }
public abstract class BaseService extends Service { @Override public void onCreate() { super.onCreate(); ((ChatApplication)getApplication()).addService(this); } @Override public void onDestroy() { super.onDestroy(); ((ChatApplication)getApplication()).removeService(this); } }
4. 编写普通Activity和Service分别继承自BaseActivity和BaseService
public class LogoActivity extends BaseActivity
这只是一个架子,以后可以在Application中放一些全局的信息,可以方便管理和调用
时间: 2024-10-23 16:24:51