Android Launcher結構分析

Launcher是系統啓動後第一個啓動的程序,是其它應用程序的入口,也就是我們的手機程序的桌面程序;

一、Launcher的定義及構成:

<1>通過查看官方提供的Launcher源碼可以知道其實Launcher也是一個Activity,不過它的intent-fliter有點特殊;

[html] view plain copy
  1. <activity  
  2.             Android:name="Launcher"  
  3.             android:launchMode="singleTask"  
  4.             android:clearTaskOnLaunch="true"  
  5.             android:stateNotNeeded="true"  
  6.             android:theme="@android:style/Theme.Wallpaper.NoTitleBar"  
  7.             android:screenOrientation="nosensor"  
  8.             android:windowSoftInputMode="stateUnspecified|adjustPan">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.HOME"/>  
  12.                 <category android:name="android.intent.category.DEFAULT" />  
  13.                 <category android:name="android.intent.category.MONKEY" />  
  14.             </intent-filter>  
  15.         </activity>  

Launcher的intent-filter中,action爲intent.action.MAIN,表示該Activity是程序的主入口,但是它的category是category.HOME,和一般的app不一樣,category.HOME則標識了這個Activity是一個Launcher,其實就是對應的按下HOME鍵所跳轉到的Activity,也就是我們的桌面;

下面我們再來看一下一個普通的App的程序主入口Activity的配置:

<action android:name="android.intent.action.MAIN" /> 表示該類是程序主入口;
<category android:name="android.intent.category.LAUNCHER" /> 

category.LAUNCHER表示該Activity在Launcher上可見,所以這一個Activity會被添加到Launcher;


<2>Launcher構成:
       HomeScreen(WorkSpace+HotSeats), Shortcut(快捷方式), LiveFolder(文件夾), AppWidget(窗口小部件), WallPaper(壁紙);  AllAppList:

      下面我們就來分別研究探討這四個元素


1、Shortcut
         在Launcher的配置文件裏面有這樣一個廣播接收者用於監聽添加快捷方式,查看InstallShortcutReceiver的源碼:

     

[html] view plain copy
  1. public class InstallShortcutReceiver extends BroadcastReceiver {  
  2.     private static final String ACTION_INSTALL_SHORTCUT =  
  3.             "com.android.launcher.action.INSTALL_SHORTCUT";  
  4.   
  5.     private final int[] mCoordinates = new int[2];  
  6.   
  7.     public void onReceive(Context context, Intent data) {  
  8.         if (!ACTION_INSTALL_SHORTCUT.equals(data.getAction())) {  
  9.             return;  
  10.         }  
  11.         int screen = Launcher.getScreen();  
  12.         if (!installShortcut(context, data, screen)) {  
  13.             // The target screen is full, let's try the other screens  
  14.             for (int i = 0; i < Launcher.SCREEN_COUNT; i++) {  
  15.                 if (i != screen && installShortcut(context, data, i)) break;  
  16.             }  
  17.         }  
  18.     }  
  19. }  

從上面的核心代碼可以看出,在BroadcastReceiver接收到INSTALL_SHORTCUT廣播之後,會嘗試在當前屏添加快捷方式,如果當前屏滿了,則會嘗試將快捷方式添加到其它屏;因此,當我們想主動添加一個快捷方式到屏幕的時候,其實就很簡單了,發送一個廣播,並且設置它的Action爲INSTALL_SHORTCUT即可;但是,需要注意的是如果僅僅設置Action是不夠的,因爲僅僅這樣做會重複添加快捷方式,如果想不重複添加,還得做一些設置,詳情參考這裏 http://www.linuxidc.com/Linux/2015-03/114623.htm  ;




2、LiveFolder

          在Launcher.Java文件中,找到添加LiveFolder的入口

[java] view plain copy
  1. // Insert extra item to handle inserting folder  
  2.                  Bundle bundle = new Bundle();  
  3.   
  4.                  ArrayList<String> shortcutNames = new ArrayList<String>();  
  5.                  shortcutNames.add(res.getString(R.string.group_folder));  
  6.                  bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);  
  7.   
  8.                  ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();  
  9.                  shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, R.drawable.ic_launcher_folder));  
  10.                  bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);  
  11.   
  12.                  Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);  
  13.                  pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));  
  14.                  pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_live_folder));  
  15.                  pickIntent.putExtras(bundle);  
  16.   
  17.                  startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);  

當我們長按桌面之後,選擇添加文件夾,則會執行上面這段代碼,在這裏會先創建好一個空文件夾;


[java] view plain copy
  1.     void addLiveFolder(Intent intent) { // RESULT_PICK_LIVE_FOLDER  
  2.         // Handle case where user selected "Folder"  
  3.         String folderName = getResources().getString(R.string.group_folder);  
  4.         String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);  
  5.   
  6.         if (folderName != null && folderName.equals(shortcutName)) {  
  7.             addFolder(!mDesktopLocked);  
  8.         } else {  
  9.             startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);  
  10.         }  
  11.     }  
  12.   
  13. 完成添加  
  14.   
  15.     private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,  
  16.             boolean insertAtFirst) { // REQUEST_CREATE_LIVE_FOLDER  
  17.         cellInfo.screen = mWorkspace.getCurrentScreen();  
  18.         if (!findSingleSlot(cellInfo)) return;  
  19.   
  20.         final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);  
  21.   
  22.         if (!mRestoring) {  
  23.             sModel.addDesktopItem(info);  
  24.   
  25.             final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,  
  26.                 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);  
  27.             mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 11, insertAtFirst);  
  28.         } else if (sModel.isDesktopLoaded()) {  
  29.             sModel.addDesktopItem(info);  
  30.         }  
  31.     }  


3、AppWidget:AppWidgetProvider用來在HOME頁面顯示插件

實現步驟:

  1. 爲AppWidget提供一個元佈局文件AppWigdetProvider_Provider.xml,用來顯示Widget的界面。
  2. 創建一個類繼承自AppWidgetProvider,並覆寫裏面的相關的方法並且註冊到配置文件。
  3. 爲WidgetProvider創建一個引用的佈局文件。

>>1、在res/xml/文件夾下創建AppWigdetProvider_Provider.xml文件

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"  
  3.   android:initialLayout="@layout/main"  <!-- android:initialLayout 設置引用的佈局文件 -->  
  4.   android:minHeight="50dip"  
  5.   android:minWidth="50dip"  
  6.   android:updatePeriodMillis="5000" > <!-- 設置更新時間,單位爲毫秒 -->  
  7. </appwidget-provider>  


>>2、修改MainActivity繼承自AppWidgetProvider並覆寫裏面的一些方法,實際上AppWidgetProvider就是一個BroadcastReceiver;

[java] view plain copy
  1. public class MainActivity extends AppWidgetProvider {  
  2.   
  3.     @Override  
  4.     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
  5.         super.onUpdate(context, appWidgetManager, appWidgetIds);  
  6.         Timer timer = new Timer();  
  7.         timer.scheduleAtFixedRate(new LYTimeTask(context, appWidgetManager), 150000);  
  8.     }  
  9.   
  10.     private class LYTimeTask extends TimerTask {  
  11.         RemoteViews remoteViews;  
  12.         AppWidgetManager appWidgetManager;  
  13.         ComponentName widget;  
  14.   
  15.         @Override  
  16.         public void run() {  
  17.             Date date = new Date();  
  18.             Calendar calendar = new GregorianCalendar(20130724);  
  19.             long days = (calendar.getTimeInMillis() - date.getTime()) / 1000 / 86400;  
  20.             remoteViews.setTextViewText(R.id.worldcup, "還剩下" + days + "天");  
  21.             appWidgetManager.updateAppWidget(widget, remoteViews);  
  22.         }  
  23.   
  24.         public LYTimeTask(Context context, AppWidgetManager appWidgetManger) {  
  25.             super();  
  26.             this.appWidgetManager = appWidgetManger;  
  27.             remoteViews = new RemoteViews(context.getPackageName(), R.layout.activity_main);  
  28.             widget = new ComponentName(context, MainActivity.class);  
  29.         }  
  30.     };  
  31. }  

>>3、爲Widget創建一個顯示用的佈局文件:main.xml

          
[html] view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.   android:layout_width="match_parent"  
  3.   android:layout_height="match_parent"  
  4.   android:background="@drawable/worldcup"  
  5.   android:orientation="vertical" >  
  6.   <TextView  
  7.     android:id="@+id/babybirthday"  
  8.     android:layout_width="fill_parent"  
  9.     android:layout_height="wrap_content"  
  10.     android:text="@string/message"  
  11.     android:textSize="12px"  
  12.     android:textColor="#ff0000" />  
  13. </LinearLayout>  

>>4、修改程序自動生成的清單文件。在AndroidManifest.xml中,聲明上述的AppWidgetProvider的子類是一個Receiver,並且:

(1)、該Receiver的intent-filter的Action必須包含“Android.appwidget.action.APPWIDGET_UPDATE”;

(2)、該Receiver的meta-data爲“android.appwidget.provider”,並用一個xml文件來描述佈局屬性。

[html] view plain copy
  1. <application  
  2.   android:allowBackup="true"  
  3.   android:icon="@drawable/ic_launcher"  
  4.   android:label="@string/app_name"  
  5.   android:theme="@style/AppTheme" >  
  6.   <receiver  
  7.     android:name=".MainActivity"  
  8.     android:label="@string/app_name" >  
  9.     <intent-filter>   
  10.       <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /><!--廣播接收過濾器-->  
  11.     </intent-filter>  
  12.   
  13.     <meta-data  
  14.       android:name="android.appwidget.provider"  
  15.       android:resource="@xml/AppWigdetProvider_Provider" /><!--AppWidgetProvider引用的Provider文件-->  
  16.   </receiver>  
  17. </application>  

運行程序:進入WIDGETS頁面,可將Widget添加到HOME頁

在AppWidgetProvider類中,還有其它相關的方法

[java] view plain copy
  1. public class WidgetProvider extends AppWidgetProvider {  
  2.   
  3.     // 每接收一次廣播消息就調用一次,使用頻繁  
  4.     public void onReceive(Context context, Intent intent) {  
  5.         super.onReceive(context, intent);  
  6.     }  
  7.   
  8.     // 每次更新都調用一次該方法,使用頻繁  
  9.     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
  10.         super.onUpdate(context, appWidgetManager, appWidgetIds);  
  11.     }  
  12.    
  13.     // 每刪除一個就調用一次  
  14.     public void onDeleted(Context context, int[] appWidgetIds) {  
  15.         super.onDeleted(context, appWidgetIds);  
  16.     }  
  17.    
  18.     // 當該Widget第一次添加到桌面是調用該方法,可添加多次但只第一次調用  
  19.     public void onEnabled(Context context) {  
  20.         super.onEnabled(context);  
  21.     }  
  22.    
  23.     // 當最後一個該Widget刪除是調用該方法,注意是最後一個  
  24.     public void onDisabled(Context context) {  
  25.         super.onDisabled(context);  
  26.     }  
  27. }  

 AppWidget本質上是一個AppWidgetHostView;




AppWidgetProvider definition
meta-data resource to provider.xml
provider xml to layout.xml
create AppWidgetInfo transact();

Launcher和AppWidget交互流程如下:

  1. Launcher 啓動,開始監聽
  2. Service send a broadcast
  3. myApp 接收到廣播,執行onUpdate方法
  4. onUpdate方法回傳RemoteViews給Service
  5. Service改變Host,updateAppWidget
  6. Launcher監聽到,更新Appwidget
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章