練手小項目(5)安全衛士_軟體管理器,練手安全衛士

來源:互聯網
上載者:User

練手小項目(5)安全衛士_軟體管理器,練手安全衛士

還是繼續複習我的安卓基礎吧,畢竟基礎才是最重要的

這一篇文章將會用到複雜的listview,和擷取系統軟體資訊,還有給Listview加動畫效果. 

先看看布局吧,源碼在後面提供下載,只是一個包,因為我是拿測試專案在示範。

① 布局的建立


布局很簡單 我直接貼源碼吧 因為怕有些手機裝的APP過多,所以加入了一個progressbar

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <TextView            android:id="@+id/tv_avail_rom"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="記憶體可用:"            android:textColor="#000000" />        <TextView            android:id="@+id/tv_avail_sd"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:text="SD卡可用:"            android:textColor="#000000" />    </RelativeLayout>    <FrameLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent" >        <LinearLayout            android:id="@+id/ll_loading"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:gravity="center"            android:orientation="vertical"            android:visibility="invisible" >            <ProgressBar                android:layout_width="wrap_content"                android:layout_height="wrap_content" />            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="正在載入程式資訊..." />        </LinearLayout>        <ListView            android:overScrollMode="never"            android:fastScrollEnabled="true"            android:id="@+id/lv_app_manager"            android:layout_width="fill_parent"            android:layout_height="fill_parent" >        </ListView>                <TextView             android:id="@+id/tv_status"             android:layout_width="fill_parent"                android:layout_height="wrap_content"            android:text="使用者程式:6個"            android:textColor="#ffffff"            android:background="#ff888888"            />    </FrameLayout></LinearLayout>



②建立擷取系統軟體資訊類要得到系統軟體資訊,首先要通過一個類,PackageManager,裡面可以獲得很多東西 一 、PackageManager的介紹主要是管理應用程式包,通過它就可以擷取應用程式資訊。
二、利用PackageManager得到我們需要的軟體資訊
package com.example.Darkbutton.Appmanager;import java.util.ArrayList;import java.util.List;import android.content.Context;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.graphics.drawable.Drawable;/** * @author xiaoxin007 * 2014-12-6下午8:18:58 * TODO 業務方法,提供手機裡面安裝的所有的應用程式資訊 */public class AppInfoProvider {/** * 擷取所有的安裝的應用程式資訊。 * @param context 上下文 * @return */public static List<AppInfo> getAppInfos(Context context){//1.獲得一個包管理器PackageManager pm = context.getPackageManager();//2.所有的安裝在系統上的應用程式套件組合資訊。List<PackageInfo> packInfos = pm.getInstalledPackages(0);//3.建立一個實體類 儲存東西List<AppInfo> appInfos = new ArrayList<AppInfo>();//4.遍曆for(PackageInfo packInfo : packInfos){AppInfo appInfo = new AppInfo();//packInfo  相當於一個應用程式apk包的資訊清單檔String packname = packInfo.packageName;Drawable icon = packInfo.applicationInfo.loadIcon(pm);String name = packInfo.applicationInfo.loadLabel(pm).toString();int flags = packInfo.applicationInfo.flags;//應用程式資訊的標記 相當於使用者提交的答卷if((flags&ApplicationInfo.FLAG_SYSTEM)==0){//使用者程式appInfo.setUserApp(true);}else{//系統程式appInfo.setUserApp(false);}if((flags&ApplicationInfo.FLAG_EXTERNAL_STORAGE)==0){//手機的記憶體appInfo.setInRom(true);}else{//手機外存放裝置appInfo.setInRom(false);}appInfo.setPackname(packname);appInfo.setIcon(icon);appInfo.setName(name);appInfos.add(appInfo);}return appInfos;}}

三、建立一個實體類
package com.example.Darkbutton.Appmanager;import android.graphics.drawable.Drawable;/** * @author xiaoxin007 * 2014-12-6下午5:37:47 * TODO 應用程式資訊的業務bean */public class AppInfo {private Drawable icon;private String name;private String packname;private boolean inRom;private boolean userApp;public Drawable getIcon() {return icon;}public void setIcon(Drawable icon) {this.icon = icon;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPackname() {return packname;}public void setPackname(String packname) {this.packname = packname;}public boolean isInRom() {return inRom;}public void setInRom(boolean inRom) {this.inRom = inRom;}public boolean isUserApp() {return userApp;}public void setUserApp(boolean userApp) {this.userApp = userApp;}@Overridepublic String toString() {return "AppInfo [name=" + name + ", packname=" + packname + ", inRom="+ inRom + ", userApp=" + userApp + "]";}}

③ 主介面的商務邏輯其實主要邏輯也無非是初始化組件,初始化資料,然後給listview 填充資料,最難的也就是adapter裡面的邏輯0.擷取某個目錄的空間大小
/** * 擷取某個目錄的可用空間 *  * @param path * @return */private long getAvailSpace(String path) {StatFs statf = new StatFs(path);statf.getBlockCount();// 擷取分區的個數long size = statf.getBlockSize();// 擷取分區的大小long count = statf.getAvailableBlocks();// 擷取可用的區塊的個數return size * count;}


一,初始化組件
/** * 初始化組件 */private void initView() {tv_status = (TextView) findViewById(R.id.tv_status);tv_avail_rom = (TextView) findViewById(R.id.tv_avail_rom);tv_avail_sd = (TextView) findViewById(R.id.tv_avail_sd);lv_app_manager = (ListView) findViewById(R.id.lv_app_manager);ll_loading = (LinearLayout) findViewById(R.id.ll_loading);}

二,初始化資料
/** * 初始化資料 */private void initData() {sdsize = getAvailSpace(Environment.getExternalStorageDirectory().getAbsolutePath());romsize = getAvailSpace(Environment.getDataDirectory().getAbsolutePath());tv_avail_sd.setText("SD卡可用空間:" + Formatter.formatFileSize(this, sdsize));tv_avail_rom.setText("記憶體可用空間:"+ Formatter.formatFileSize(this, romsize));}
三,給listview加入動畫
/** * listview動畫 */private void initAnim() {AnimationSet set = new AnimationSet(false); Animation animation =  new TranslateAnimation(1, 13, 10, 50);  //ScaleAnimation 控制尺寸伸縮的動畫效果  animation.setDuration(300);  set.addAnimation(animation); LayoutAnimationController controller = new LayoutAnimationController(set, 1);lv_app_manager.setLayoutAnimation(controller);   //ListView 設定動畫效果  }
四,給Listview填充資料
/** * 給Listview填充資料 */private void fillDataToListView() {//1.使用者體驗,加入progressbarll_loading.setVisibility(View.VISIBLE);//2.耗時操作加入線程以免GGnew Thread() {public void run() {//3.調用 類,擷取到軟體資訊appInfos = AppInfoProvider.getAppInfos(AppManagerActivity.this);//4.因為要把系統,使用者軟體分開,所以單獨建立兩個資料存放區userAppInfos = new ArrayList<AppInfo>();systemAppInfos = new ArrayList<AppInfo>();//5.遍曆 填充進數組for (AppInfo info : appInfos) {if (info.isUserApp()) {userAppInfos.add(info);} else {systemAppInfos.add(info);}}// 載入listview的資料配接器 因為線上程之中,所以使用runOnUiThread 可以在ui更新runOnUiThread(new Runnable() {@Overridepublic void run() {if (adapter == null) {adapter = new AppManagerAdapter();lv_app_manager.setAdapter(adapter);} else {adapter.notifyDataSetChanged();}ll_loading.setVisibility(View.INVISIBLE);}});};}.start();}

5.複雜的listview布局是怎麼來的
private class AppManagerAdapter extends BaseAdapter {// 控制listview有多少個條目 第一個1 代表是顯示 使用者應用 第二個1代表系統應用@Overridepublic int getCount() {return userAppInfos.size() + 1 + systemAppInfos.size() + 1;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {AppInfo appInfo;if (position == 0) {// 顯示的是用程式有多少個的小標籤TextView tv = new TextView(getApplicationContext());tv.setTextColor(Color.WHITE);tv.setBackgroundColor(Color.GRAY);tv.setText("使用者程式:" + userAppInfos.size() + "個");return tv;} else if (position == (userAppInfos.size() + 1)) {TextView tv = new TextView(getApplicationContext());tv.setTextColor(Color.WHITE);tv.setBackgroundColor(Color.GRAY);tv.setText("系統程式:" + systemAppInfos.size() + "個");return tv;} else if (position <= userAppInfos.size()) {// 使用者程式int newposition = position - 1;// 因為多了一個textview的文本佔用了位置appInfo = userAppInfos.get(newposition);} else {// 系統程式int newposition = position - 1 - userAppInfos.size() - 1;appInfo = systemAppInfos.get(newposition);}View view;ViewHolder holder;// if(position<userAppInfos.size()){//這些位置是留個使用者程式顯示的。// appInfo = userAppInfos.get(position);// }else{//這些位置是留個系統程式的。// int newposition = position - userAppInfos.size();// appInfo = systemAppInfos.get(newposition);// }if (convertView != null && convertView instanceof RelativeLayout) {// 不僅需要檢查是否為空白,還要判斷是否是合適的類型去複用view = convertView;holder = (ViewHolder) view.getTag();} else {view = View.inflate(getApplicationContext(),R.layout.list_item_appinfo, null);holder = new ViewHolder();holder.iv_icon = (ImageView) view.findViewById(R.id.iv_app_icon);holder.tv_location = (TextView) view.findViewById(R.id.tv_app_location);holder.tv_name = (TextView) view.findViewById(R.id.tv_app_name);view.setTag(holder);}holder.iv_icon.setImageDrawable(appInfo.getIcon());holder.tv_name.setText(appInfo.getName());if (appInfo.isInRom()) {holder.tv_location.setText("手機記憶體");} else {holder.tv_location.setText("外部儲存");}return view;}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return 0;}}

④ 軟體管理的功能實現


當點擊 listview條目的時候,會出現一個popwindow 有卸載 有分享,有啟動 
/** * 設定listview的點擊事件 */lv_app_manager.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {//設定點擊第一個條目的時候不顯示,因為不是軟體if (position == 0) {return;//以此類推} else if (position == (userAppInfos.size() + 1)) {return;} else if (position <= userAppInfos.size()) {// 使用者程式int newposition = position - 1;appInfo = userAppInfos.get(newposition);} else {// 系統程式int newposition = position - 1 - userAppInfos.size() - 1;appInfo = systemAppInfos.get(newposition);}// System.out.println(appInfo.getPackname());dismissPopupWindow();//填充一個popwindowView contentView = View.inflate(getApplicationContext(),R.layout.popup_app_item, null);ll_start = (LinearLayout) contentView.findViewById(R.id.ll_start);ll_share = (LinearLayout) contentView.findViewById(R.id.ll_share);ll_uninstall = (LinearLayout) contentView.findViewById(R.id.ll_uninstall);//啟動的監聽ll_start.setOnClickListener(AppManagerActivity.this);//分享的監聽ll_share.setOnClickListener(AppManagerActivity.this);//卸載的監聽ll_uninstall.setOnClickListener(AppManagerActivity.this);popupWindow = new PopupWindow(contentView, -2, -2);// 動畫效果的播放必須要求表單有背景顏色。// 透明顏色也是顏色popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));int[] location = new int[2];view.getLocationInWindow(location);// 在代碼裡面設定的寬高值 都是像素。---》dipint dip = 60;int px = DensityUtil.dip2px(getApplicationContext(), dip);System.out.println("px=" + px);popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP,px, location[1]);ScaleAnimation sa = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f,Animation.RELATIVE_TO_SELF, 0,Animation.RELATIVE_TO_SELF, 0.5f);sa.setDuration(300);AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);aa.setDuration(300);AnimationSet set = new AnimationSet(false);set.addAnimation(aa);set.addAnimation(sa);contentView.startAnimation(set);}});}

 具體功能的實現 一,點擊事件的處理
/** * 布局對應的點擊事件 */@Overridepublic void onClick(View v) {dismissPopupWindow();switch (v.getId()) {case R.id.ll_share:shareApplication();break;case R.id.ll_start:startApplication();break;case R.id.ll_uninstall:if (appInfo.isUserApp()) {uninstallAppliation();}else{Toast.makeText(this, "系統應用只有擷取root許可權才可以卸載", 0).show();//Runtime.getRuntime().exec("");}break;}}

二,用簡訊實現分享功能
/** * 分享一個應用程式 */private void shareApplication() {// Intent { act=android.intent.action.SEND typ=text/plain flg=0x3000000 cmp=com.android.mms/.ui.ComposeMessageActivity (has extras) } from pid 256Intent intent = new Intent();intent.setAction("android.intent.action.SEND");intent.addCategory(Intent.CATEGORY_DEFAULT);intent.setType("text/plain");intent.putExtra(Intent.EXTRA_TEXT, "推薦您使用一款軟體,名稱叫:"+appInfo.getName());startActivity(intent);}

三 ,卸載應用
/** * 卸載應用 */private void uninstallAppliation() {// <action android:name="android.intent.action.VIEW" />// <action android:name="android.intent.action.DELETE" />// <category android:name="android.intent.category.DEFAULT" />// <data android:scheme="package" />Intent intent = new Intent();intent.setAction("android.intent.action.VIEW");intent.setAction("android.intent.action.DELETE");intent.addCategory("android.intent.category.DEFAULT");intent.setData(Uri.parse("package:" + appInfo.getPackname()));startActivityForResult(intent, 0);}

四 ,開啟一個應用程式
/** * 開啟一個應用程式 */private void startApplication() {// 查詢這個應用程式的入口activity。 把他開啟起來。PackageManager pm = getPackageManager();// Intent intent = new Intent();// intent.setAction("android.intent.action.MAIN");// intent.addCategory("android.intent.category.LAUNCHER");// //查詢出來了所有的手機上具有啟動能力的activity。// List<ResolveInfo> infos = pm.queryIntentActivities(intent,// PackageManager.GET_INTENT_FILTERS);Intent intent = pm.getLaunchIntentForPackage(appInfo.getPackname());if (intent != null) {startActivity(intent);} else {Toast.makeText(this, "不能啟動當前應用", 0).show();}}

點擊下載源碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.