今天,它可以被视为只是基本完成了其首个商业项目,在发展过程中,风格,然而随着工作经验的积累。最终開始慢慢的了解到抽象思想在面向对象编程中的重要性,这一篇简单的介绍一下我的一点收获。

首先,在如今的项目中使用的主要是afinal框架,并且这个框架确实比較不错,省去了不少工作量。在编写Activity的过程中,基本都是直接继承自FinalActivity类,这样能够使用这个类给我们封装好的不少的方法,可是随着项目慢慢推进,这样的直接继承框架类的一些缺点也開始慢慢的显现出来。最基本的就是扩展性受到了一些限制,比方对于Activity,我们一般进行控件的初始化操作。为了使代码风格更加的简单介绍明了,我一般都是在一个单独的initView()方法中实现对控件的初始化,然后在onCreate中直接调用这种方法实现控件的初始化。除此之外,在非常多的涉及到网络连接的Activity中须要对网络情况进行检測,假设网络状况出现故障,就弹出一个对话框提醒用户进行网络的设置或者是检查。

像是这样的的需求,我们最好能抽成单独的方法,这样我们就不须要在每一个Activity中都写大量的代码进行设置。

可是因为我们是直接集成自FinalActivity,所以一个实现方案就是直接改动我们的FinalActivity的源码,添加这些公共的方法。可是这样就改动了外部框架的源码,添加了代码之间的耦合度,当我们在另外的项目中须要使用这个框架的时候,就须要再改源码。所以说这样的方式能够解决这个问题,但并非最好的解决方式。

第二种解决方式就是我们另外写一个Activity的基类BaseActivity,这个类也是继承自FinalActivity,并且在这个基类里面我们能够实现一些公共的方法。这样其它的Activity继承自我们这个BaseActivity基类。既能够使用FinalActivity里面封装好的方法。也能够使用我们在BaseActivity里面扩展的一些公共的方法。假设我们再抽象一层的话。我们能够把这些公共的方法抽象到一个接口里面。然后我们的BaseActivity实现这个接口,这样也能够实现程序的扩展。

以下贴一些我整理的一些代码

首先是抽象出来的一个Activity的接口

/**
* Activity的支持类接口,主要定义了Activity中经常使用的功能
*
* @Package com.example.myallutils
*
* TODO
* @author ZhaoKaiQiang
*
* @time 2014年5月7日
*/
public interface IBaseActivity {
/**
* 获取Application对象
*
* @return
*/
public abstract Application getApplication(); /**
* 开启服务
*/
public abstract void startService(); /**
* 停止服务
*/
public abstract void stopService(); /**
* 推断是否有网络连接,若没有,则弹出网络设置对话框。返回false
*
* @return
*/
public abstract boolean validateInternet(); /**
*
* 推断是否有网络连接,没有返回false
*
*/
public abstract boolean hasInternetConnected(); /**
* 退出应用
*/
public abstract void isExit(); /**
* 推断GPS是否已经开启.
*
* @return
*/
public abstract boolean hasLocationGPS(); /**
* 推断基站是否已经开启.
*/
public abstract boolean hasLocationNetWork(); /**
* 检查内存卡.
*/
public abstract void checkMemoryCard(); /**
* 获取进度条.
*
* @return
*/
public abstract ProgressDialog getProgressDialog(); /**
* 返回当前Activity上下文.
*/
public abstract Context getContext(); /**
* 获取当前登录用户的SharedPreferences配置.
*/
public SharedPreferences getLoginUserSharedPre(); /**
* 用户是否在线(当前网络是否重连成功)
*/
public boolean getUserOnlineState(); /**
* 设置用户在线状态 true 在线 false 不在线
*
* @param isOnline
*/
public void setUserOnlineState(boolean isOnline); /**
*
* 发出Notification的method.
*
* @param iconId
* 图标
* @param contentTitle
* 标题
* @param contentText
* 内容
* @param activity
*/
public void PushNotification(int iconId, String contentTitle,
String contentText, Class<?> activity, String from);
}

以下是对这个接口的实现,是全部Activity的基类

/**
* Activity的基类。实现了IActivitySupport接口
*
* @Package com.example.myallutils
*
* TODO
* @author ZhaoKaiQiang
*
* @time 2014年5月7日
*/
public abstract class BaseActivity extends FinalActivity implements
IBaseActivity { protected Context mContext = null;
protected SharedPreferences preferences;
protected MyApplication myApplication;
protected ProgressDialog pg = null;
protected NotificationManager notificationManager; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
preferences = getSharedPreferences("TAG", 0);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
pg = new ProgressDialog(mContext);
myApplication = (MyApplication) getApplication(); } /**
* 初始化页面布局
*/
abstract void iniView(); @Override
protected void onStart() {
super.onStart();
} @Override
protected void onResume() {
super.onResume();
} @Override
protected void onPause() {
super.onPause();
} @Override
protected void onStop() {
super.onStop();
} @Override
public void onDestroy() {
super.onDestroy();
} @Override
public ProgressDialog getProgressDialog() {
return pg;
} /**
* 在这里开启全部须要开启的服务
*/
@Override
public void startService() { } /**
* 在这里关闭全部须要开启的服务
*/
@Override
public void stopService() { } /**
* 停止服务并结束全部的Activity退出应用
*/
@Override
public void isExit() {
new AlertDialog.Builder(mContext).setTitle("确定退出吗?")
.setNeutralButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stopService();
myApplication.exit();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
} /**
* 推断是否有网络连接,没有返回false
*/
@Override
public boolean hasInternetConnected() {
ConnectivityManager manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager != null) {
NetworkInfo network = manager.getActiveNetworkInfo();
if (network != null && network.isConnectedOrConnecting()) {
return true;
}
}
return false;
} /**
* 推断是否有网络连接,若没有。则弹出网络设置对话框。返回false
*/
@Override
public boolean validateInternet() {
ConnectivityManager manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null) {
openWirelessSet();
return false;
} else {
NetworkInfo[] info = manager.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
openWirelessSet();
return false;
} /**
* 推断GPS定位服务是否开启
*/
@Override
public boolean hasLocationGPS() {
LocationManager manager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
if (manager
.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
return true;
} else {
return false;
}
} /**
* 推断基站定位是否开启
*/
@Override
public boolean hasLocationNetWork() {
LocationManager manager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
if (manager
.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {
return true;
} else {
return false;
}
} /**
* 检查内存卡可读
*/
@Override
public void checkMemoryCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
new AlertDialog.Builder(mContext)
.setTitle("检測内存卡")
.setMessage("请检查内存卡")
.setPositiveButton("设置",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
Intent intent = new Intent(
Settings.ACTION_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("退出",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel(); }
}).create().show();
}
} /**
* 打开网络设置对话框
*/
public void openWirelessSet() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder
.setTitle("网络设置")
.setMessage("检查网络")
.setPositiveButton("网络设置",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
Intent intent = new Intent(
Settings.ACTION_WIRELESS_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
dialogBuilder.show();
} /**
* 关闭键盘
*/
public void closeInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null && this.getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
} /**
*
* 发出Notification
*
* @param iconId
* 图标
* @param contentTitle
* 标题
* @param contentText
* 你内容
* @param activity
*/
@SuppressWarnings("deprecation")
public void PushNotification(int iconId, String contentTitle,
String contentText, Class<?> activity, String to) { // 创建新的Intent。作为点击Notification留言条时, 会执行的Activity
Intent notifyIntent = new Intent(this, activity);
notifyIntent.putExtra("to", to);
// 创建PendingIntent作为设置递延执行的Activity
PendingIntent appIntent = PendingIntent.getActivity(mContext, 0,
notifyIntent, 0);
/* 创建Notication,并设置相关參数 */
Notification myNoti = new Notification();
// 点击自己主动消失
myNoti.flags = Notification.FLAG_AUTO_CANCEL;
/* 设置statusbar显示的icon */
myNoti.icon = iconId;
/* 设置statusbar显示的文字信息 */
myNoti.tickerText = contentTitle;
/* 设置notification发生时同一时候发出默认声音 */
myNoti.defaults = Notification.DEFAULT_SOUND;
/* 设置Notification留言条的參数 */
myNoti.setLatestEventInfo(mContext, contentTitle, contentText,
appIntent);
/* 送出Notification */
notificationManager.notify(0, myNoti);
} /**
* 返回上下文对象
*/
@Override
public Context getContext() {
return mContext;
} /**
* 返回登录用户的SharedPreferences对象
*/
@Override
public SharedPreferences getLoginUserSharedPre() {
return preferences;
} /**
* 获取用户在线状态
*/
@Override
public boolean getUserOnlineState() {
return false;
} /**
* 设置用户在线状态
*/
@Override
public void setUserOnlineState(boolean isOnline) { } }

在我们定义的Activity中就能够这样使用

/**
*
* @Package com.example.myallutils
*
* TODO
* @author ZhaoKaiQiang
*
* @time 2014年5月6日
*/
public class MainActivity extends BaseActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iniView();
} @Override
void iniView() {
mContext = this;
validateInternet();
PushNotification(R.drawable.ic_launcher, "測试", "内容測试", OtherActivity.class,
"嘻嘻");
} }

经过几层抽象。我们能够看到,代码的扩展性和耦合性确实得到了一定的改善。这篇文章仅仅针对菜鸟,假设有牛人有幸能够看到这篇文章。还希望能够不吝赐教一二!

版权声明:本文博客原创文章。博客,未经同意,不得转载。

【Android先进】我们为什么要创建Activity基类Activity什么是一般的基类方法的更多相关文章

  1. android 在基类activity中注册BroadcastReceiver,子activity类实现响应

    android app 一般都会定义自己的BaseActivity, 如果各子Activity都需要接收广播但对广播的处理又不同时,可以考虑在BaseActivity中注册BroadcastRecei ...

  2. Delphi 继承基类的窗体,并显示基类的控件操作。

    1.  先建一个普通的窗体,until1 2.  先把类实现基类, 并需要实现基类需要继承的方法, 可以先不用再方法中写实现代码. TForm4 = class(TfrmmtAReportPeriod ...

  3. 我的Android 4 学习系列之创建应用程序和Activity:Manifest、Application、Activity

    目录 介绍Android应用程序组件,以及使用这些组件构建的各种Android应用程序 Android应用程序的生命周期 如何创建应用程序Manifest 如何使用外部资源提供对位置.语言和硬件配置的 ...

  4. 【Android进阶】为什么要创建Activity基类以及Activity基类中一般有哪些方法

    现在也算是刚刚基本完成了自己的第一个商业项目,在开发的过程中,参考了不少人的代码风格,然而随着工作经验的积累,终于开始慢慢的了解到抽象思想在面向对象编程中的重要性,这一篇简单的介绍一下我的一点收获. ...

  5. guxh的python笔记七:抽象基类

    1,鸭子类型和白鹅类型 1.1,白鹅类型 白鹅类型对接口有明确定义,比如不可变序列(Sequence),需要实现__contains__,__iter__,__len__,__getitem__,__ ...

  6. 【Python】【元编程】【从协议到抽象基类】

    """class Vector2d: typecode = 'd' def __init__(self,x,y): self.__x = float(x) self.__ ...

  7. 虚析构函数? vptr? 指针偏移?多态数组? delete 基类指针 内存泄漏?崩溃?

    五条基本规则: 1.如果基类已经插入了vptr, 则派生类将继承和重用该vptr.vptr(一般在对象内存模型的顶部)必须随着对象类型的变化而不断地改变它的指向,以保证其值和当前对象的实际类型是一致的 ...

  8. OOP2(虚函数/抽象基类/访问控制与继承)

    通常情况下,如果我们不适用某个函数,则无需为该函数提供定义.但我们必须为每个虚函数都提供定义而不管它是否被用到了,这因为连编译器也无法确定到底会适用哪个虚函数 对虚函数的调用可能在运行时才被解析: 当 ...

  9. OOP1(定义基类和派生类)

    面向对象程序设计基于三个基本概念:数据抽象,继承和动态绑定 数据抽象是一种依赖于接口和实现分离的编程技术.继承和动态绑定对程序的编号有两方面的影响:一是我们可以更容易地定义与其它类相似但不完全相同的类 ...

随机推荐

  1. Chromium Graphics: GPUclient的原理和实现分析之间的同步机制-Part II

    摘要:Part I探析GPUclient之间的同步问题,以及Chromium的GL扩展同步点机制的基本原理.本文将源码的角度剖析同步点(SyncPoint)机制的实现方式. 同步点机制的实现主要涉及到 ...

  2. t持久化与集群部署开发详解

    Quartz.net持久化与集群部署开发详解 序言 我前边有几篇文章有介绍过quartz的基本使用语法与类库.但是他的执行计划都是被写在本地的xml文件中.无法做集群部署,我让它看起来脆弱不堪,那是我 ...

  3. Net Memory Profiler 分析.Net程序内存泄露

    Net Memory Profiler 分析.Net程序内存泄露 Haozes's Tech Space 人類的全部才能無非是時間和耐心的混合物 使用.Net Memory Profiler 分析.N ...

  4. android数据访问模式:档、SharedPreferences

    android数据访问模式:档.SharedPreferences.SQLite 数据库.Content provider 文件流: 使用java IO流对文件进行读写操作,文件权限默认. 指定文件权 ...

  5. Python爬虫(一)

    花了四天的时间用python写了个简单的爬虫程序.整个过程分为两个部分:工具的安装和程序的实现 本文并没有讲程序的详细实现遇到的问题,而是对着手前一些前期的准备 第一部分(工具的安装) 开发工具的下载 ...

  6. TFS(Team Foundation Server)简介和新手入门

    在两部分的文章.我会介绍Team Foundation Server一些核心功能,着重于产品的日常应用是如何将这些功能结合使用. 作为一个软件开发.在我的职业生涯,.我常常用于支持软件开发过程中大量的 ...

  7. Agile/CMMI/Scrum

    Agile/CMMI/Scrum 一.背景介绍 在朋友(aehyok)的建议下,初步去了解Visual Studio Online,简称VS Online(即原来的 Team Foundation S ...

  8. ebay的api开发技术说明,有点乱

    使用eBay API的基本步骤引入 开始eBay API,例如,以下基本步骤需要: 1.    注册开发者账号: https://developer.ebay.com/join/Default.asp ...

  9. Vbox创建COM对象失败

    近期在使用vbox时出现下面错误:创建COM对象失败,应用程序将被中断 在CMD里面输入下面命令: C:\Users\Administrator>d: D:\>cd D:\Program ...

  10. win7下go web之revel

    win7下go web之revel安装   接着上回记录的win7下go环境搭建,go的开发,现在除了sublime外,LiteIDE比较推荐,下载链接 下载安装后直接打开,需要配置下go环境(本机使 ...