Android编程实战--安全卫士(1)

来源:互联网 发布:三国杀网络错误请重试 编辑:程序博客网 时间:2024/05/01 22:57

一. 代码组织结构. 两种方式.


1. 按照业务逻辑 组织代码.  

   
    会议         com.swust.metting
    财务         com.swust.money
    人员管理     com.swust.manage
    

2. 按照代码的类型组织包结构.

   
   界面         com.swust.mobilesafe.activities
   自定义控件   com.swust.mobilesafe.ui
   业务逻辑     com.swust.mobilesafe.engine
   工具类                          .utils
   服务                            .service
   广播接受者                      .receiver
   持久化  .db


3.界面效果

   

    

二.PackageManager 获取应用程序的清单文件的信息


/** * 获取应用程序的版本号 *  * @return */private String getVersion() {PackageManager pm = getPackageManager();try {PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);return packageInfo.versionName;} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();return "";}}

三.使用URL HttpUrlConntion 获取网络信息,通过pull解析器  解析XML 

1.线程类run方法

private class CheckVersionTask implements Runnable {private Message msg = Message.obtain();private long startTime = System.currentTimeMillis();@Overridepublic void run() {// TODO Auto-generated method stubtry {URL url = new URL(getResources().getString(R.string.path));HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");int code = conn.getResponseCode();if (code == 200) {InputStream in = conn.getInputStream();updateinfo = UpdateInfoPaser.getUpdateInfo(in);if (updateinfo == null) {msg.what = PASER_ERROR;} else {msg.what = PASER_SUCCESS;}} else {msg.what = SERVER_ERROR;}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();msg.what = URL_ERROR;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();msg.what = IO_ERROR;}  finally {long endTime = System.currentTimeMillis();long dTime = endTime -startTime;if(dTime<2000){try {Thread.sleep(2000-dTime);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}handler.sendMessage(msg);}}}

2.创建业务逻辑类来解析xml

public class UpdateInfoPaser {/** * 解析更新的xml *  * @param in *            xml 文件流 * @return */public static UpdateInfo getUpdateInfo(InputStream in) {XmlPullParser parser = Xml.newPullParser();try {parser.setInput(in, "UTF-8");int type = parser.getEventType();UpdateInfo info = new UpdateInfo();while (type != XmlPullParser.END_DOCUMENT) {switch (type) {case XmlPullParser.START_TAG:if ("version".equals(parser.getName())) {info.setVersion(parser.nextText());} else if ("description".equals(parser.getName())) {info.setDescription(parser.nextText());} else if ("path".equals(parser.getName())) {info.setApkPath(parser.nextText());}break;}type = parser.next();}in.close();return info;} catch (XmlPullParserException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}}

3.定义类保存解析后的关键数据

public class UpdateInfo {private String version;private String description;private String apkPath;public String getVersion() {return version;}public void setVersion(String version) {this.version = version;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getApkPath() {return apkPath;}public void setApkPath(String apkPath) {this.apkPath = apkPath;}}


四.  Handler+ message 消息机制  

1.消息接收与处理

private Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {switch (msg.what) {case SERVER_ERROR:Toast.makeText(getApplicationContext(), "服务器内部错误", 0).show();loadMainUI();break;case URL_ERROR:Toast.makeText(getApplicationContext(), "服务器连接出错", 0).show();loadMainUI();break;case IO_ERROR:Toast.makeText(getApplicationContext(), "连接服务器异常", 0).show();loadMainUI();break;case PASER_ERROR:Toast.makeText(getApplicationContext(), "解析更新信息失败", 0).show();loadMainUI();break;case PASER_SUCCESS:if (getVersion().equals(updateinfo.getVersion())) {// 版本一致loadMainUI();} else {// 要求版本更新showUpdatedialog();}break;}};};

2.进入主界面并销毁开始界面

private void loadMainUI(){Intent intent = new Intent(this,HomeActivity.class);startActivity(intent);finish();}

3.弹出更新对话框

         /** * 弹出更新提醒对话框 */protected void showUpdatedialog() {// TODO Auto-generated method stubOnClickListener listener = new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubswitch (which) {case DialogInterface.BUTTON_POSITIVE:break;case DialogInterface.BUTTON_NEGATIVE:loadMainUI();break;}}}; new Builder(this).setTitle("是否下载新版本") .setMessage(updateinfo.getDescription()) .setPositiveButton("升级", listener) .setNegativeButton("下次再说", listener) .setCancelable(false) .show();}

五.主界面

1.主界面xml定义

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".SplashActivity" >    <TextView         android:gravity="center"        android:text="主界面"        android:textSize="20sp"        android:layout_width="match_parent"        android:layout_height="60dp"        android:background="#6666ff00"/>    <com.swust.mobilesafe.ui.focusedTextView         android:id="@+id/tv_home_hint"        android:layout_width="wrap_content"        android:layout_height="100dp"        android:gravity="center_vertical"        android:singleLine="true"        android:ellipsize="marquee"        android:text="我是新的手机卫士,我保护您的手机安全,我时刻守护着您的手机,亲爱的主人!"/>    <GridView         android:horizontalSpacing="10dp"        android:verticalSpacing="50dp"        android:numColumns="3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/gv_home">    </GridView></LinearLayout>


2.使用自定义TextView实现文本滚动效果

public class focusedTextView extends TextView {public focusedTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}public focusedTextView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}public focusedTextView(Context context) {super(context);// TODO Auto-generated constructor stub}@Overridepublic boolean isFocused() {// TODO Auto-generated method stubreturn true;}}

3.gridview实现主界面布局

 ( 1)定义grid_home_items .xml  

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:gravity="center_horizontal"    android:orientation="vertical" ><ImageView     android:src="@drawable/safe"    android:layout_width="55dp"    android:layout_height="55dp"    android:id="@+id/iv_item_logo"/><TextView     android:textColor="#000000"    android:textSize="16sp"    android:text="手机防盗"    android:id="@+id/tv_item_name"      android:layout_width="wrap_content"    android:layout_height="wrap_content"/></LinearLayout>

(2)实现home_activity

public class HomeActivity extends Activity {private GridView gv_home;private String[]  names={"手机防盗","通讯卫士","软件管理","进程管理","流量统计","手机杀毒","系统优化","高级工具","手机设置"};private int[] icons = {R.drawable.safe,R.drawable.callmsgsafe,R.drawable.app,R.drawable.taskmanager,R.drawable.netmanager,R.drawable.trojan,R.drawable.sysoptimize,R.drawable.atools,R.drawable.settings};@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_home);gv_home = (GridView) this.findViewById(R.id.gv_home);gv_home.setAdapter(new HomeAdapter());gv_home.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position,long id) {// TODO Auto-generated method stubswitch (position) {case 0:break;case 8:Intent intent = new Intent(HomeActivity.this,SettingActivity.class);startActivity(intent);break;}}});}private class HomeAdapter extends BaseAdapter{@Overridepublic int getCount() {// TODO Auto-generated method stubreturn names.length;}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn 0;}@Overridepublic View getView(int position, View conberView, ViewGroup parent) {// TODO Auto-generated method stubView view = View.inflate(getApplicationContext(), R.layout.grid_home_item, null);ImageView iv_logo = (ImageView) view.findViewById(R.id.iv_item_logo);TextView  tv_name = (TextView) view.findViewById(R.id.tv_item_name);tv_name.setText(names[position]);iv_logo.setImageResource(icons[position]);return view;}}}

六.设置界面

1.仿ios开关按钮

 (1)在drawable文件夹中创建switch_btn.xml文件

<?xml version="1.0" encoding="utf-8"?><selector  xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_checked="true" android:drawable="@drawable/ios7_switch_on" />    <item android:drawable="@drawable/ios7_switch_off" /></selector>

(2)在布局文件中实现

 <ToggleButton             android:id="@+id/tb_setting_update"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:button="@drawable/switch_btn"             android:background="@android:color/transparent"             android:checked="false"             android:text=""              android:textOff=""               android:textOn=""             android:layout_alignParentRight="true"             android:layout_centerVertical="true"             android:layout_marginRight="26dp" />

2.自定义组合控件实现

(1)创建自定义组合空间的布局文件setting_view_layout.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="match_parent"        android:layout_height="50dp">         <TextView             android:id="@+id/tv_setting_title"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignParentLeft="true"             android:layout_centerVertical="true"             android:layout_marginLeft="22dp"             android:text="自动更新设置"             android:textColor="#000000"             android:textSize="20sp" />         <ToggleButton             android:id="@+id/tb_setting_update"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:button="@drawable/switch_btn"             android:background="@android:color/transparent"             android:checked="false"             android:text=""              android:textOff=""               android:textOn=""             android:layout_alignParentRight="true"             android:layout_centerVertical="true"             android:layout_marginRight="26dp" />         <View              android:layout_width="fill_parent"             android:layout_height="1dp"             android:background="#22000000"             android:layout_alignParentBottom="true"            /> </RelativeLayout>

(2)实现自定义组合控件类

public class SettingView extends RelativeLayout {private TextView tv_title;public  ToggleButton tb_update;public SettingView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stubinitView(context);}public SettingView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubinitView(context);TypedArray  array = context.obtainStyledAttributes(attrs, R.styleable.SettingView);String title = array.getString(R.styleable.SettingView_title);setTitle(title);array.recycle();}public SettingView(Context context) {super(context);// TODO Auto-generated constructor stubinitView(context);}private void initView(Context context){View view = View.inflate(context, R.layout.setting_view_layout, this);tv_title = (TextView) view.findViewById(R.id.tv_setting_title);tb_update = (ToggleButton) view.findViewById(R.id.tb_setting_update);}/** * 设置自定义组合控件标题 * @param text */public void setTitle(String text){tv_title.setText(text);}/** * 返回是否被选中 * @return */public boolean ischecked(){return tb_update.isChecked();}public void setchecked(boolean checked){tb_update.setChecked(checked);}}

3.实现主界面布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:swust="http://schemas.android.com/apk/res/com.swust.mobilesafe"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".SplashActivity" >    <TextView         android:gravity="center"        android:text="设置中心"        android:textSize="20sp"        android:layout_width="match_parent"        android:layout_height="60dp"        android:background="#6666ff00"/>    <View         android:layout_width="fill_parent"        android:layout_height="15dp"        android:background="#05000000"/>    <View          android:layout_width="fill_parent"         android:layout_height="1dp"         android:background="#22000000"            />   <com.swust.mobilesafe.ui.SettingView       android:id="@+id/sv_autoupdate"       swust:title="自动更新"        android:layout_width="fill_parent"        android:layout_height="wrap_content"/>    <com.swust.mobilesafe.ui.SettingView       android:id="@+id/sv_sysstart"       swust:title="开机启动"        android:layout_width="fill_parent"        android:layout_height="wrap_content"/></LinearLayout>

4.自定义组合框属性标签设置

(1)在res-> values下建立attrs.xml,定义需要的属性标签类型

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="SettingView">        <attr name="title" format="string"/>    </declare-styleable></resources>

(2)在设置界面布局中定义命名空间

  xmlns:swust="http://schemas.android.com/apk/res/com.swust.mobilesafe"

(3)自定义组合控件类的构造函数中实现标签属性的显示

         /** * 采用xml文件声明的view对象,在初始化的时候会走两个参数的构造方法 * @param context * @param attrs  xml文件里定义的属性都会被封装到attrs里面 */public SettingView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubinitView(context);TypedArray  array = context.obtainStyledAttributes(attrs, R.styleable.SettingView);String title = array.getString(R.styleable.SettingView_title);setTitle(title);array.recycle();}

5.设置界面activity类实现

public class SettingActivity extends Activity {private SettingView sv_autoupdate;private SettingView sv_sysstart;private SharedPreferences sp;//用来保存配置信息@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_setting);sp = getSharedPreferences("config", MODE_PRIVATE);//初始化配置信息sv_autoupdate = (SettingView) findViewById(R.id.sv_autoupdate);sv_sysstart = (SettingView) findViewById(R.id.sv_sysstart);boolean autoupdate = sp.getBoolean("autoupdate", true);//读取数据,如不存在为truesv_autoupdate.setchecked(autoupdate);sv_autoupdate.tb_update.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubEditor editor = sp.edit();if(isChecked){editor.putBoolean("autoupdate", true);}else {editor.putBoolean("autoupdate", false);}editor.commit();}});}}

6.开始界面设置是否进行更新

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_splash);tv_version = (TextView) findViewById(R.id.tv_splash_version);tv_version.setText("版本:" + getVersion());sp = getSharedPreferences("config", MODE_PRIVATE);boolean autoupdate = sp.getBoolean("autoupdate", true);if(autoupdate){new Thread(new CheckVersionTask()).start();}else {handler.postDelayed(new Runnable() {// handler.postDelay() 执行延时的动作@Overridepublic void run() {// TODO Auto-generated method stubloadMainUI();}}, 1500);}}










0 0