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

首先,在如今的项目中使用的主要是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. InputStreamReader 和 OutputStreamWriter类使用方法简单介绍,及演示。

    InputStreamReader 和 OutputStreamWriter类使用方法简单介绍. 一.InputStreamReader类 InputStreamReader 将字节流转换为字符流.是 ...

  2. 怎么样MyEclipse配置Tomcat?

    1.下载tomcat免安装版.tomcat路径不包含空格 http://download.csdn.net/detail/u014112584/7549191 2.windows -preferenc ...

  3. DevExpress控件中LayoutControl的使用

    原文:DevExpress控件中LayoutControl的使用 C#开发中,软件布局设计,主要用TableLayoutPanel能很好地支持缩放功能,对自身的Label.TextBox等控件支持的很 ...

  4. unrecognized selector sent to instance 0x10b34e810

    一个错误: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLEr ...

  5. oracle 优化or 更换in、exists、union all几个字眼,测试没有问题!

    oracle 优化or 更换in.exists.union几个字眼.测试没有问题! 根据实际情况选择相应的语句是.假设指数,or全表扫描,in 和not in 应慎用.否则会导致全表扫描.  sele ...

  6. android Animation动画的xml使用

    在Android应用程序,使用动画效果,能带给用户更好的感觉,做动画能够通过XML或Android代码来实现. Animation动画效果的实现能够通过两种方式进行实现,一种是tweened anim ...

  7. Sql Server远程查询db 表中的数据,以本地

    step 1: sp_configure 'show advanced options', 1; RECONFIGURE; sp_configure 'Ad Hoc Distributed Queri ...

  8. C# 6.0 (C# vNext) 的新功能:Exception-Handling Improvements

    于 C# 6.0 包裹在异常处理的新功能,有两个方面的改进: 异步处理(async and await)能力 catch block 总结使用.于 C# 5.0 释放 async and await, ...

  9. js多个物体运动问题2

    问题1 http://www.cnblogs.com/huaci/p/3854216.html 在上一讲问题1,我们可以整理出2点: 1,定时器作为运动物体的属性 2,startMove方法,参数要传 ...

  10. 【Linux】lvm基础操作

    新增两块硬盘,来进行实验: [root@jp ~]# fdisk -l Disk /dev/sda: 107.3 GB, 107374182400 bytes 255 heads, 63 sector ...