zoukankan      html  css  js  c++  java
  • 【Android进阶】为什么要创建Activity基类以及Activity基类中一般有哪些方法

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

    首先,在现在的项目中使用的主要是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,
    				"嘻嘻");
    	}
    
    }

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



  • 相关阅读:
    SpringCloud初体验:四、API GateWay 服务网关
    SpringCloud初体验:三、Feign 服务间调用(FeignClient)、负载均衡(Ribbon)、容错/降级处理(Hystrix)
    SpringCloud初体验:二、Config 统一配置管理中心
    SpringCloud初体验:一、Eureka 服务的注册与发现
    PHP 通过实现 Iterator(迭代器)接口来读取大文件文本
    SpringCloud初体验:前言
    springboot利用MockMvc测试controller控制器
    vue通过(NGINX)部署在子目录或者二级目录实践
    PHP 设计模式 原型模式(Prototype)之深/浅拷贝
    PHPstorm配置PHPunit对composer引入的php代码进行单元测试
  • 原文地址:https://www.cnblogs.com/oversea201405/p/3749545.html
Copyright © 2011-2022 走看看