为什么要创建Activity基类以及Activity基类中一般有哪些方法

来源:互联网 发布:js 地址栏汉字转码 编辑:程序博客网 时间:2024/04/28 07:51
首先,在现在的项目中使用的主要是afinal框架,而且这个框架确实比较不错,省去了不少工作量,在编写Activity的过程中,基本都是直接继承自FinalActivity类,这样可以使用这个类给我们封装好的不少的方法,但是随着项目慢慢推进,这种直接继承框架类的一些缺点也开始慢慢的显现出来。最主要的就是扩展性受到了一些限制,比如对于Activity,我们一般进行控件的初始化操作,为了使代码风格更加的简介明了,我一般都是在一个单独的initView()方法中实现对控件的初始化,然后在onCreate中直接调用这个方法实现控件的初始化。除此之外,在很多的涉及到网络连接的Activity中需要对网络情况进行检测,如果网络状况出现问题,就弹出一个对话框提醒用户进行网络的设置或者是检查。像是这种的需求,我们最好能抽成单独的方法,这样我们就不需要在每个Activity中都写大量的代码进行设置。但是由于我们是直接集成自FinalActivity,所以一个实现方案就是直接修改我们的FinalActivity的源代码,增加这些公共的方法,但是这样就修改了外部框架的源代码,增加了代码之间的耦合度,当我们在另外的项目中需要使用这个框架的时候,就需要再改源代码,所以说这样的方式可以解决问题,但并不是最好的解决方案。

另外一种解决方案就是我们另外写一个Activity的基类BaseActivity,这个类也是继承自FinalActivity,而且在这个基类里面我们可以实现一些公共的方法,这样其他的Activity继承自我们这个BaseActivity基类,既可以使用FinalActivity里面封装好的方法,也可以使用我们在BaseActivity里面扩展的一些公共的方法。如果我们再抽象一层的话,我们可以把这些公共的方法抽象到一个接口里面,然后我们的BaseActivity实现这个接口,这样也可以实现程序的扩展。

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

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

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Activity的支持类接口,主要定义了Activity中常用的功能 
  3.  *  
  4.  * @Package com.example.myallutils 
  5.  *  
  6.  *          TODO 
  7.  * @author ZhaoKaiQiang 
  8.  *  
  9.  * @time 2014年5月7日 
  10.  */  
  11. public interface IBaseActivity {  
  12.     /** 
  13.      * 获取Application对象 
  14.      *  
  15.      * @return 
  16.      */  
  17.     public abstract Application getApplication();  
  18.       
  19.     /** 
  20.      * 开启服务 
  21.      */  
  22.     public abstract void startService();  
  23.   
  24.     /** 
  25.      * 停止服务 
  26.      */  
  27.     public abstract void stopService();  
  28.   
  29.     /** 
  30.      * 判断是否有网络连接,若没有,则弹出网络设置对话框,返回false 
  31.      *  
  32.      * @return 
  33.      */  
  34.     public abstract boolean validateInternet();  
  35.   
  36.     /** 
  37.      *  
  38.      * 判断是否有网络连接,没有返回false 
  39.      *  
  40.      */  
  41.     public abstract boolean hasInternetConnected();  
  42.   
  43.     /** 
  44.      * 退出应用 
  45.      */  
  46.     public abstract void isExit();  
  47.   
  48.     /** 
  49.      * 判断GPS是否已经开启. 
  50.      *  
  51.      * @return 
  52.      */  
  53.     public abstract boolean hasLocationGPS();  
  54.   
  55.     /** 
  56.      * 判断基站是否已经开启. 
  57.      */  
  58.     public abstract boolean hasLocationNetWork();  
  59.   
  60.     /** 
  61.      * 检查内存卡. 
  62.      */  
  63.     public abstract void checkMemoryCard();  
  64.   
  65.     /** 
  66.      * 获取进度条. 
  67.      *  
  68.      * @return 
  69.      */  
  70.     public abstract ProgressDialog getProgressDialog();  
  71.   
  72.     /** 
  73.      * 返回当前Activity上下文. 
  74.      */  
  75.     public abstract Context getContext();  
  76.   
  77.     /** 
  78.      * 获取当前登录用户的SharedPreferences配置. 
  79.      */  
  80.     public SharedPreferences getLoginUserSharedPre();  
  81.   
  82.     /** 
  83.      * 用户是否在线(当前网络是否重连成功) 
  84.      */  
  85.     public boolean getUserOnlineState();  
  86.   
  87.     /** 
  88.      * 设置用户在线状态 true 在线 false 不在线 
  89.      *  
  90.      * @param isOnline 
  91.      */  
  92.     public void setUserOnlineState(boolean isOnline);  
  93.   
  94.     /** 
  95.      *  
  96.      * 发出Notification的method. 
  97.      *  
  98.      * @param iconId 
  99.      *            图标 
  100.      * @param contentTitle 
  101.      *            标题 
  102.      * @param contentText 
  103.      *            内容 
  104.      * @param activity 
  105.      */  
  106.     public void PushNotification(int iconId, String contentTitle,  
  107.             String contentText, Class<?> activity, String from);  
  108. }  


下面是对这个接口的实现,是所有Activity的基类


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Activity的基类,实现了IActivitySupport接口 
  3.  *  
  4.  * @Package com.example.myallutils 
  5.  *  
  6.  *          TODO 
  7.  * @author ZhaoKaiQiang 
  8.  *  
  9.  * @time 2014年5月7日 
  10.  */  
  11. public abstract class BaseActivity extends FinalActivity implements  
  12.         IBaseActivity {  
  13.   
  14.     protected Context mContext = null;  
  15.     protected SharedPreferences preferences;  
  16.     protected MyApplication myApplication;  
  17.     protected ProgressDialog pg = null;  
  18.     protected NotificationManager notificationManager;  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         mContext = this;  
  24.         preferences = getSharedPreferences("TAG"0);  
  25.         notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  26.         pg = new ProgressDialog(mContext);  
  27.         myApplication = (MyApplication) getApplication();  
  28.   
  29.     }  
  30.   
  31.     /** 
  32.      * 初始化页面布局 
  33.      */  
  34.     abstract void iniView();  
  35.   
  36.     @Override  
  37.     protected void onStart() {  
  38.         super.onStart();  
  39.     }  
  40.   
  41.     @Override  
  42.     protected void onResume() {  
  43.         super.onResume();  
  44.     }  
  45.   
  46.     @Override  
  47.     protected void onPause() {  
  48.         super.onPause();  
  49.     }  
  50.   
  51.     @Override  
  52.     protected void onStop() {  
  53.         super.onStop();  
  54.     }  
  55.   
  56.     @Override  
  57.     public void onDestroy() {  
  58.         super.onDestroy();  
  59.     }  
  60.   
  61.     @Override  
  62.     public ProgressDialog getProgressDialog() {  
  63.         return pg;  
  64.     }  
  65.   
  66.     /** 
  67.      * 在这里开启所有需要开启的服务 
  68.      */  
  69.     @Override  
  70.     public void startService() {  
  71.   
  72.     }  
  73.   
  74.     /** 
  75.      * 在这里关闭所有需要开启的服务 
  76.      */  
  77.     @Override  
  78.     public void stopService() {  
  79.   
  80.     }  
  81.   
  82.     /** 
  83.      * 停止服务并结束所有的Activity退出应用 
  84.      */  
  85.     @Override  
  86.     public void isExit() {  
  87.         new AlertDialog.Builder(mContext).setTitle("确定退出吗?")  
  88.                 .setNeutralButton("确定"new DialogInterface.OnClickListener() {  
  89.                     @Override  
  90.                     public void onClick(DialogInterface dialog, int which) {  
  91.                         stopService();  
  92.                         myApplication.exit();  
  93.                     }  
  94.                 })  
  95.                 .setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  96.                     @Override  
  97.                     public void onClick(DialogInterface dialog, int which) {  
  98.                         dialog.cancel();  
  99.                     }  
  100.                 }).show();  
  101.     }  
  102.   
  103.     /** 
  104.      * 判断是否有网络连接,没有返回false 
  105.      */  
  106.     @Override  
  107.     public boolean hasInternetConnected() {  
  108.         ConnectivityManager manager = (ConnectivityManager) mContext  
  109.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  110.         if (manager != null) {  
  111.             NetworkInfo network = manager.getActiveNetworkInfo();  
  112.             if (network != null && network.isConnectedOrConnecting()) {  
  113.                 return true;  
  114.             }  
  115.         }  
  116.         return false;  
  117.     }  
  118.   
  119.     /** 
  120.      * 判断是否有网络连接,若没有,则弹出网络设置对话框,返回false 
  121.      */  
  122.     @Override  
  123.     public boolean validateInternet() {  
  124.         ConnectivityManager manager = (ConnectivityManager) mContext  
  125.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  126.         if (manager == null) {  
  127.             openWirelessSet();  
  128.             return false;  
  129.         } else {  
  130.             NetworkInfo[] info = manager.getAllNetworkInfo();  
  131.             if (info != null) {  
  132.                 for (int i = 0; i < info.length; i++) {  
  133.                     if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
  134.                         return true;  
  135.                     }  
  136.                 }  
  137.             }  
  138.         }  
  139.         openWirelessSet();  
  140.         return false;  
  141.     }  
  142.   
  143.     /** 
  144.      * 判断GPS定位服务是否开启 
  145.      */  
  146.     @Override  
  147.     public boolean hasLocationGPS() {  
  148.         LocationManager manager = (LocationManager) mContext  
  149.                 .getSystemService(Context.LOCATION_SERVICE);  
  150.         if (manager  
  151.                 .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {  
  152.             return true;  
  153.         } else {  
  154.             return false;  
  155.         }  
  156.     }  
  157.   
  158.     /** 
  159.      * 判断基站定位是否开启 
  160.      */  
  161.     @Override  
  162.     public boolean hasLocationNetWork() {  
  163.         LocationManager manager = (LocationManager) mContext  
  164.                 .getSystemService(Context.LOCATION_SERVICE);  
  165.         if (manager  
  166.                 .isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {  
  167.             return true;  
  168.         } else {  
  169.             return false;  
  170.         }  
  171.     }  
  172.   
  173.     /** 
  174.      * 检查内存卡可读 
  175.      */  
  176.     @Override  
  177.     public void checkMemoryCard() {  
  178.         if (!Environment.MEDIA_MOUNTED.equals(Environment  
  179.                 .getExternalStorageState())) {  
  180.             new AlertDialog.Builder(mContext)  
  181.                     .setTitle("检测内存卡")  
  182.                     .setMessage("请检查内存卡")  
  183.                     .setPositiveButton("设置",  
  184.                             new DialogInterface.OnClickListener() {  
  185.                                 @Override  
  186.                                 public void onClick(DialogInterface dialog,  
  187.                                         int which) {  
  188.                                     dialog.cancel();  
  189.                                     Intent intent = new Intent(  
  190.                                             Settings.ACTION_SETTINGS);  
  191.                                     mContext.startActivity(intent);  
  192.                                 }  
  193.                             })  
  194.                     .setNegativeButton("退出",  
  195.                             new DialogInterface.OnClickListener() {  
  196.                                 @Override  
  197.                                 public void onClick(DialogInterface dialog,  
  198.                                         int which) {  
  199.                                     dialog.cancel();  
  200.   
  201.                                 }  
  202.                             }).create().show();  
  203.         }  
  204.     }  
  205.   
  206.     /** 
  207.      * 打开网络设置对话框 
  208.      */  
  209.     public void openWirelessSet() {  
  210.         AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);  
  211.         dialogBuilder  
  212.                 .setTitle("网络设置")  
  213.                 .setMessage("检查网络")  
  214.                 .setPositiveButton("网络设置",  
  215.                         new DialogInterface.OnClickListener() {  
  216.                             @Override  
  217.                             public void onClick(DialogInterface dialog,  
  218.                                     int which) {  
  219.                                 dialog.cancel();  
  220.                                 Intent intent = new Intent(  
  221.                                         Settings.ACTION_WIRELESS_SETTINGS);  
  222.                                 mContext.startActivity(intent);  
  223.                             }  
  224.                         })  
  225.                 .setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  226.                     @Override  
  227.                     public void onClick(DialogInterface dialog, int whichButton) {  
  228.                         dialog.cancel();  
  229.                     }  
  230.                 });  
  231.         dialogBuilder.show();  
  232.     }  
  233.   
  234.     /** 
  235.      * 关闭键盘 
  236.      */  
  237.     public void closeInput() {  
  238.         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
  239.         if (inputMethodManager != null && this.getCurrentFocus() != null) {  
  240.             inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()  
  241.                     .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  
  242.         }  
  243.     }  
  244.   
  245.     /** 
  246.      *  
  247.      * 发出Notification 
  248.      *  
  249.      * @param iconId 
  250.      *            图标 
  251.      * @param contentTitle 
  252.      *            标题 
  253.      * @param contentText 
  254.      *            你内容 
  255.      * @param activity 
  256.      */  
  257.     @SuppressWarnings("deprecation")  
  258.     public void PushNotification(int iconId, String contentTitle,  
  259.             String contentText, Class<?> activity, String to) {  
  260.   
  261.         // 创建新的Intent,作为点击Notification留言条时, 会运行的Activity  
  262.         Intent notifyIntent = new Intent(this, activity);  
  263.         notifyIntent.putExtra("to", to);  
  264.         // 创建PendingIntent作为设置递延运行的Activity  
  265.         PendingIntent appIntent = PendingIntent.getActivity(mContext, 0,  
  266.                 notifyIntent, 0);  
  267.         /* 创建Notication,并设置相关参数 */  
  268.         Notification myNoti = new Notification();  
  269.         // 点击自动消失  
  270.         myNoti.flags = Notification.FLAG_AUTO_CANCEL;  
  271.         /* 设置statusbar显示的icon */  
  272.         myNoti.icon = iconId;  
  273.         /* 设置statusbar显示的文字信息 */  
  274.         myNoti.tickerText = contentTitle;  
  275.         /* 设置notification发生时同时发出默认声音 */  
  276.         myNoti.defaults = Notification.DEFAULT_SOUND;  
  277.         /* 设置Notification留言条的参数 */  
  278.         myNoti.setLatestEventInfo(mContext, contentTitle, contentText,  
  279.                 appIntent);  
  280.         /* 送出Notification */  
  281.         notificationManager.notify(0, myNoti);  
  282.     }  
  283.   
  284.     /** 
  285.      * 返回上下文对象 
  286.      */  
  287.     @Override  
  288.     public Context getContext() {  
  289.         return mContext;  
  290.     }  
  291.   
  292.     /** 
  293.      * 返回登录用户的SharedPreferences对象 
  294.      */  
  295.     @Override  
  296.     public SharedPreferences getLoginUserSharedPre() {  
  297.         return preferences;  
  298.     }  
  299.   
  300.     /** 
  301.      * 获取用户在线状态 
  302.      */  
  303.     @Override  
  304.     public boolean getUserOnlineState() {  
  305.         return false;  
  306.     }  
  307.   
  308.     /** 
  309.      * 设置用户在线状态 
  310.      */  
  311.     @Override  
  312.     public void setUserOnlineState(boolean isOnline) {  
  313.   
  314.     }  
  315.   
  316. }  

在我们定义的Activity中就可以这样使用


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *  
  3.  * @Package com.example.myallutils 
  4.  *  
  5.  *          TODO 
  6.  * @author ZhaoKaiQiang 
  7.  *  
  8.  * @time 2014年5月6日 
  9.  */  
  10. public class MainActivity extends BaseActivity {  
  11.   
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.activity_main);  
  16.         iniView();   
  17.     }  
  18.   
  19.     @Override  
  20.     void iniView() {  
  21.         mContext = this;  
  22.         validateInternet();  
  23.         PushNotification(R.drawable.ic_launcher, "测试""内容测试", OtherActivity.class,  
  24.                 "嘻嘻");  
  25.     }  
  26.   
  27. }  

经过几层抽象,我们可以看到,代码的扩展性和耦合性确实得到了一定的改善,这篇文章只针对菜鸟,如果有牛人有幸可以看到这篇文章,还希望可以指教一二!
0 0
原创粉丝点击