仿360一鍵清理實現(一),仿360一鍵清理
---------------------------------------------------------------------
編譯環境:Android 4.0
測試環境:Android 4.2.2模擬器
螢幕解析度:480*800
作者:瘋狂小強
注意:
1.資源採集於網上,如有侵權請及時聯絡,以便處理。
2.代碼僅用於學習交流,請勿商業化。
--------------------------------------------------------------------
先上部分:
“一鍵清理”是一個案頭表徵圖,點擊表徵圖後,顯示一個視圖,進行清理動畫,之後顯示清理了幾個進程,釋放了多少M記憶體,點擊“設定過濾名單”啟動另外一個Activity編輯過濾名單。
AndroidManifest.xml如下:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tang.demo360" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/> <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".CleanActivity" android:theme="@style/MTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> </intent-filter> </activity> <service android:name=".CleanService"> </service> <activity android:name=".SetWhiteListActivity"></activity> </application></manifest>
1.建立捷徑
主介面就是一個按鈕,單擊後,會發出一個廣播com.android.launcher.action.INSTALL_SHORTCUT建立一個捷徑,這需要許可權
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
圖一 圖二
private void createShortcut(){ Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); // 捷徑的名字 String name = getResources().getString(R.string.app_name); shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,name); //不允許重複建立 shortcut.putExtra("duplicate", false); Intent shortcutIntent = new Intent(); ComponentName componentName = new ComponentName(getPackageName(), "com.tang.demo360.CleanActivity"); shortcutIntent.setComponent(componentName); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); ShortcutIconResource iconRes=null; //捷徑的表徵圖 iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.shortcut_process_clear_shortcut_icon); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); sendBroadcast(shortcut); Log.i("AAA", "sendBroadcast : INSTALL_SHORTCUT");}
建立出來的這個捷徑不是開啟圖一介面,而是開啟圖二的。
從createShortcut()方法代碼上看
ComponentName componentName = new ComponentName(getPackageName(), "com.tang.demo360.CleanActivity");shortcutIntent.setComponent(componentName);
開啟了com.tang.demo360.CleanActivity這個Activity。但事實上只做了這些還不夠,我們必須為CleanActivity在manifest中配置Action:
<action android:name="android.intent.action.MAIN" />這兩者配合使用就可以直接啟動CleanActivity了。
2.確定開啟CleanActivity的位置
由我們知道:捷徑所在的位置不同CleanActivity的位置也是不同的,點擊案頭捷徑啟動Activity的時候,我們打“ActivityManager”的logcat會發現如下資訊:
其中:bnds=[510,282][679,399]好象是個座標,到Launcher的源碼上一看發現:
public void onClick(View v){........Object tag = v.getTag(); if (tag instanceof ShortcutInfo) { // Open shortcut final Intent intent = ((ShortcutInfo) tag).intent; int[] pos = new int[2]; v.getLocationOnScreen(pos); intent.setSourceBounds(new Rect(pos[0], pos[1], pos[0] + v.getWidth(), pos[1] + v.getHeight())); boolean success = startActivitySafely(intent, tag);......}點擊捷徑的時候的確是吧捷徑的位置放在一個Rect中傳出去了。
位置得到了接下來就只要把Activity的一些style改一下,然後把這個位置資料用上,就可以得到上面的效果了
<style name="MTheme" parent="@android:style/Theme"> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowIsFloating">true</item> <item name="android:backgroundDimAmount">0</item> </style>
android:backgroundDimAmount 調節背景灰階
android:windowIsFloating 懸浮視窗,表示浮在螢幕上的,如果在這裡使用了,整個layout就會在 螢幕中心,相當於浮在螢幕上。
Rect rect = getIntent().getSourceBounds();rootView = new CleanView(this,rect);setContentView(rootView);WindowManager.LayoutParams lp = getWindow().getAttributes();WindowManager windowManager = getWindowManager();int w = windowManager.getDefaultDisplay().getWidth();int h = windowManager.getDefaultDisplay().getHeight();lp.x = lp.x+(rect.left-w/2)+Value.WIDTH/2;lp.y = lp.y+(rect.top-h/2)+Value.HEIGHT/2;getWindow().setAttributes(lp);
由於使用懸浮窗後座標原點也在螢幕中心,和我們所得到的Rect中的參數的左邊原點不同,所以需要做位置關係轉化
lp.x = lp.x+(rect.left-w/2)+Value.WIDTH/2;
lp.y = lp.y+(rect.top-h/2)+Value.HEIGHT/2;
3.CleanView布局的實現
為了實現上面的效果,將CleanView分成兩部分
part1.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/shortcut_process_clear_cover"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/shortcut_process_clear_fg" /> <com.tang.demo360.view.LevelView android:id="@+id/text0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textColor="#ffffff" android:text="10%" android:background="@drawable/task_killer"/></RelativeLayout>
part2.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:orientation="vertical" android:gravity="center"> <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清理進程0個" /> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="釋放記憶體0M" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="設定過濾名單" android:background="@drawable/shortcut_process_clear_wlist"/></LinearLayout>
再根據捷徑所處的位置判斷先把哪部分加入到父容器中
view = new LinearLayout(context);view.setOrientation(LinearLayout.HORIZONTAL);view.setBackgroundResource(R.drawable.shortcut_process_clear_bg);WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);int screenWidth = windowManager.getDefaultDisplay().getWidth();if(Value.WIDTH+rect.left+50>screenWidth){view.addView(view2);view.addView(view1);}else{view.addView(view1);view.addView(view2);}addView(view);
4.CleanView動畫實現
出現方式:由無到有
退出方式:由有到無
清理過程動畫:part1.xml ImageView不斷旋轉,速度由慢變快再變慢最後消失。
水面動畫:先由未清理所佔記憶體的百分比高度降低到0然後升至當前所佔記憶體百分比的高度
前三個比較容易不做介紹,對於水面動畫,在CleanView中有
public void updateView(Object [] parm){text1.setText("清理進程"+(Integer)parm[0]+"個");DecimalFormat decimalFormat=new DecimalFormat("0.0");String temp=decimalFormat.format(parm[1]);text2.setText("釋放記憶體"+temp+"M");setLevelAnimation((Integer)parm[2]);}public void setLevelAnimation(int level){ClipDrawable clip = (ClipDrawable) text0.getBackground();text0.setText(level+"%");clip.setLevel(level*100);}
有2個方法負責快速更新以便達到動畫效果。
水面的背景
<?xml version="1.0" encoding="utf-8"?> <clip xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/shortcut_process_clear_level" android:clipOrientation="vertical" android:gravity="bottom"> </clip>
使用ClipDrawable代表從其它位元影像上截取一個圖片片段setLevel方法設定截取百分比,我在主線程中使用Timer來快速更新這個數值
timer = new Timer();
timer.schedule(task, 500, 1);
task = new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif(isDown){level = (level-Value.V)>=0?(level-Value.V):0;if(level ==0){isDown = false;}}else{level = (level+Value.V)<=newlevel?(level+Value.V):newlevel;}parm[2] =level/100;handler.sendEmptyMessage(Value.UPDATE_VIEW);}};
這樣只要在主線程中接受Value.UPDATE_VIEW這個Message然後調用updateView()方法就可以目的動畫效果。
5.我們來殺進程吧
對於這個我在網上查了一些資料寫了一個工具類
CleanUtil.java
package com.tang.util;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.lang.reflect.Method;import java.util.List;import android.app.Activity;import android.app.ActivityManager;import android.content.Context;import android.util.Log;public class CleanUtil {//關閉當前啟動並執行進程public Object [] killRunnintAppInfo(Context context) {MSaveList mSaveList = new MSaveList(context.getSharedPreferences("demo360", Activity.MODE_PRIVATE));List<String> list = mSaveList.load();ActivityManager mActivityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);List<ActivityManager.RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses();int appSize = getRunningTasksSize(context);long memory = getUesdMemory(context);for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess){if(amProcess.processName.equals("com.tang.demo360")||amProcess.processName.startsWith("system")){Log.d("AAA", "跳過不殺的進程:" + amProcess.processName);continue;}else {if(isInWhiteList(amProcess.processName,list)){Log.d("AAA", "跳過不殺的進程:" + amProcess.processName);}else{mActivityManager.killBackgroundProcesses(amProcess.processName);Log.d("AAA", "殺掉的進程:"+amProcess.processName);}}}appSize = Math.abs(appSize -getRunningTasksSize(context));memory = Math.abs(memory -getUesdMemory(context));return getRecycleMemoryInfo(context,appSize,memory);}//強制關閉進程private void forceKillApp(ActivityManager am, String packageName) {Method forceStopPackage = null;try {forceStopPackage = am.getClass().getDeclaredMethod("forceStopPackage", String.class);forceStopPackage.setAccessible(true); forceStopPackage.invoke(am, packageName);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }/** * 將要傳出去的資料 * 殺了多少進程 * 釋放多少M記憶體 * 當前記憶體百分比 * @param context * @param appSize * @param memory * @return */private Object [] getRecycleMemoryInfo(Context context,int appSize,long memory) { Object[] pram=new Object[]{0,0,0};; if(memory>=0) { pram[0] = appSize; pram[1] = (memory/1024.0); pram[2] = getUesdMemoryRate(context); } return pram; } private int getRunningTasksSize(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); return am.getRunningAppProcesses().size(); } /** * 得到裝置的所有RAM * @return 返回所有記憶體大小,單位:kb */private int getAllMemory() {String filePath = "/proc/meminfo";int ram = 0;FileReader fr = null;BufferedReader localBufferedReader = null;try {fr = new FileReader(filePath);localBufferedReader = new BufferedReader(fr, 8192);String line = localBufferedReader.readLine();int a = line.length() - 3;int b = line.indexOf(' ');String str = line.substring(b, a);while (str.substring(0, 1).equals(" ")) {str = str.substring(1, str.length());}ram = Integer.parseInt(str);} catch (IOException e) {e.printStackTrace();} finally {try {fr.close();localBufferedReader.close();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}return ram;}/** * 得到裝置的可用RAM * @return 返回所有記憶體大小,單位:kb */private long getAvailMemory(Context context) {ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();am.getMemoryInfo(mi);return mi.availMem / 1024;}/** * 得到裝置的已用RAM * @return 返回所有記憶體大小,單位:kb */private long getUesdMemory(Context context) {return getAllMemory() - getAvailMemory(context);}public int getUesdMemoryRate(Context context){return (int) (getUesdMemory(context)*100/getAvailMemory(context));}/** * 判斷是否在白名單之內 * @param pkg * @param list * @return */private boolean isInWhiteList(String pkg,List<String> list){boolean inOrNot = false;if(list!=null){for(int i=0;i<list.size();i++){if(pkg.equals(list.get(i))){inOrNot = true;break;}}}return inOrNot;}}在啟動CleanActivity的時候,在onCreate中啟動了CleanService,熱這個實現了Runnable介面
public class CleanService extends Service implements Runnable{.....@Overridepublic void run() {// TODO Auto-generated method stubhandler.sendEmptyMessage(Value.BEGIN_CLEAN);Object [] pram = cleanUtil.killRunnintAppInfo(this);Message message = new Message();message.obj = pram;message.what = Value.UPDATE;handler.sendMessage(message);}@Overridepublic void onCreate() {// TODO Auto-generated method stubif(CleanActivity.local!=null){handler = CleanActivity.local.getHandler();new Thread(this).start();cleanUtil = new CleanUtil();}super.onCreate();}....}將殺進程的工作放在後台進行。
當然殺進程也是需要許可權的:
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
第一部分就這樣了,第二部分分析白名單處理
由於技術水平有限,寫文章的水平更是有限,如有什麼錯誤,歡迎大牛指正。
360一鍵清理緩衝在哪,看到別人的電腦都有,在開始隔壁好像360軟體管家一樣的表徵圖
哦哦 你說的應該是360軟體小助手吧? 安裝最新版本的360安全衛士就有了
為何用360清理垃圾後一鍵清理系統垃圾又清理了一堆?
360清理時把一些零時的檔案清理掉而已·一鍵清理的話就是把疑似沒用的刪掉,例如你長期沒用到的東西刪掉,但那東西是有用的。所以最好不要用一鍵清理