This article will sort out the series of articles "android hands-on teach you how to develop launcher" on www.bangchui.org. This article briefly introduces the implementation of the basic functions of lancher. After reading this article, I will have a deep understanding of lancher.
1. Simplest launcher instance
Launcher is the android desktop application. Is the launcher application of android2.3:
Next, we will develop our own launcher to replace the default launcher of the system.
How can we make our application a launcher?
Next, we will create a project called myhome. The specific steps are omitted. After the project is created, the entire directory structure is shown as follows:
Now our androidmanifest. xml file is like this:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.bangchui.myhome" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MyHome" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
Note that <intent-filter>
</Intent-filter>.
Next we will add the following two lines in it:
<category android:name="android.intent.category.HOME" /><category android:name="android.intent.category.DEFAULT" />
The androidmanifest. xml file is as follows:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.bangchui.myhome" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MyHome" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest>
At this time, we can't see anything special about running the program. When you press the Home Key (press home on the simulator to bring up the desktop application), the program
We can see that the myhome and launcher we developed appear together.
Restart the simulator and we can see that our program can be run as home.
OK. Step 1: Use our application as home.
To make our application home, you only need to add the following in androidmanifest. xml:
<category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" />
2. List Installed applications
Listing installed applications is an essential feature of launcher. The following describes how to list applications. After the program is run, it looks as follows:
1. modify main. xml and add a gridview to display the Application List.
The modification is as follows:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <GridView android:layout_width="match_parent" android:id="@+id/apps_list" android:numColumns="4" android:layout_height="wrap_content"> </GridView></LinearLayout>
2. query the installed APK through the packagemanager API
Let's write a method called loadapps to put the list of live applications in the private list <resolveinfo> mapps;, as follows:
private void loadApps() { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mApps = getPackageManager().queryIntentActivities(mainIntent, 0); }
3. Implement the adapter used to display the gridview to display the list of applications.
The code for the entire activity is as follows:
package org.bangchui.myhome; import java.util.List; import android.app.Activity; import android.content.Intent; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class MyHome extends Activity { GridView mGrid; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); loadApps(); setContentView(R.layout.main); mGrid = (GridView) findViewById(R.id.apps_list); mGrid.setAdapter(new AppsAdapter()); } private List<ResolveInfo> mApps; private void loadApps() { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mApps = getPackageManager().queryIntentActivities(mainIntent, 0); } public class AppsAdapter extends BaseAdapter { public AppsAdapter() { } public View getView(int position, View convertView, ViewGroup parent) { ImageView i; if (convertView == null) { i = new ImageView(MyHome.this); i.setScaleType(ImageView.ScaleType.FIT_CENTER); i.setLayoutParams(new GridView.LayoutParams(50, 50)); } else { i = (ImageView) convertView; } ResolveInfo info = mApps.get(position); i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager())); return i; } public final int getCount() { return mApps.size(); } public final Object getItem(int position) { return mApps.get(position); } public final long getItemId(int position) { return position; } } }
3. Start the installed Application
1. Listen to the onitemclick event of the gridview
Set a listener to notify us of a callback function when a certain item of the gridview is clicked.
We call mgrid. setonitemclicklistener (listener); set a listener.
Listener in mgrid. setonitemclicklistener (listener) is an interface of the type android. widget. adapterview. onitemclicklistener, as shown in:
Next we will use a new Android. widget. adapterview. onitemclicklistener type object as the parameter. We directly use the auto-completion feature of merge de to define onitemclicklistener:
private OnItemClickListener listener = new OnItemClickListener() {@Override public void onItemClick(AdapterView<?> parent, View view, int position,long id) {}};
The onitemclicklistener interface has a method called onitemclick, which we can implement. Below I will give a brief description of several onitemclick parameters:
Parent omitted
View clicked View
Position position of the clicked item
ID of the clicked item
2. Start the activity of the clicked Application
Generally, we can know which project is clicked based on position. Now we extract the corresponding application data (mainly the main activity) based on the project to be clicked, and then start the activity. Use the following code:
@ Override public void onitemclick (adapterview <?> Parent, view, int position, long ID) {resolveinfo info = mapps. get (position); // The package name of the application string PKG = info. activityinfo. packagename; // main activity class of the application string CLS = info. activityinfo. name; componentname componet = new componentname (PKG, CLS); intent I = new intent (); I. setcomponent (componet); startactivity (I );}
For example, when we click the calculator, the calculator is started, for example:
The entire class code is as follows:
Package Org. bangchui. myhome; import Java. util. list; import android. app. activity; import android. content. componentname; import android. content. intent; import android. content. PM. resolveinfo; import android. OS. bundle; import android. view. view; import android. view. viewgroup; import android. widget. adapterview; import android. widget. baseadapter; import android. widget. gridview; import android. widget. imageview; import Android. widget. adapterview. onitemclicklistener; public class myhome extends activity {private list <resolveinfo> mapps; gridview mgrid; private onitemclicklistener listener = new onitemclicklistener () {@ override public void onitemclick (adapterview <?> Parent, view, int position, long ID) {resolveinfo info = mapps. get (position); // The package name of the application string PKG = info. activityinfo. packagename; // main activity class of the application string CLS = info. activityinfo. name; componentname componet = new componentname (PKG, CLS); intent I = new intent (); I. setcomponent (componet); startactivity (I) ;};/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); loadapps (); setcontentview (R. layout. main); mgrid = (gridview) findviewbyid (R. id. performance_list); mgrid. setadapter (new external adapter (); mgrid. setonitemclicklistener (listener);} private void loadapps () {intent mainintent = new intent (intent. action_main, null); mainintent. addcategory (intent. category_launcher); mapps = getpackagemanager (). queryintentactivities (mainintent, 0);} public class extends adapter extends baseadapter {public extends adapter () {} public view getview (INT position, view convertview, viewgroup parent) {imageview I; if (convertview = NULL) {I = new imageview (myhome. this); I. setscaletype (imageview. scaletype. fit_center); I. setlayoutparams (New gridview. layoutparams (50, 50);} else {I = (imageview) convertview;} resolveinfo info = mapps. get (position); I. setimagedrawable (info. activityinfo. loadicon (getpackagemanager (); return I;} public final int getcount () {return mapps. size ();} public final object getitem (INT position) {return mapps. get (position) ;}public final long getitemid (INT position) {return position ;}}}
4. Display Widgets
To achieve this effect, click "add widget" to bring up the widget list. Then, select a widget and display it on the interface, as shown below:
1. Get widget Information
Obtaining widgets is actually very simple. We only need to send a request to the system, the system will open the widget list, and then we can select one. The Code is as follows:
void addWidget() { int appWidgetId = mAppWidgetHost.allocateAppWidgetId(); Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK); pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // start the pick activity startActivityForResult(pickIntent, [b]REQUEST_PICK_APPWIDGET[/b]); }
2. Add the widget view to layout.
When a widget is selected, the activity is notified through onactivityresult. The widget information is contained in intent data. For details, see the code comment.
@ Override protected void onactivityresult (INT requestcode, int resultcode, intent data) {// The pattern used here is that a user picks a specific application, // which, depending on the target, might need to create the actual // target. // For example, the user wocould pick_shortcut for "music playlist", and // We // launch over to the music app to actually create_shortcut. if (resultcode = Result _ OK) {Switch (requestcode) {Case request_pick_appwidget: addappwidget (data); break; Case request_create_appwidget: completeaddappwidget (data); break ;}} void addappwidget (intent data) {// todo: Catch bad widget exception when sent int appwidgetid = data. getintextra (appwidgetmanager. extra_appwidget_id,-1); appwidgetproviderinfo appwidget = mappwidgetmanager. getappwidgetinfo (appwidgetid); // wi If DGET contains the setting information that is not empty, start the widget setting interface if (appwidget. Configure! = NULL) {// launch over to configure widget, if needed intent = new intent (appwidgetmanager. action_appwidget_configure); intent. setcomponent (appwidget. configure); intent. putextra (appwidgetmanager. outputs, appwidgetid); outputs (intent, request_create_appwidget);} else {// The widget contains the setting information empty and adds the widget directly to layout. // otherwise just add it onactivityresult (request_create_appwidget, activity. result_ OK, data) ;}} void startactivityforresultsafely (intent, int requestcode) {try {startactivityforresult (intent, requestcode);} catch (activitynotfoundexception e) {toast. maketext (this, "activity_not_found", toast. length_short ). show ();} catch (securityexception e) {toast. maketext (this, "activity_not_found", toast. length_short ). show () ;}}/*** add widget information to layout ** @ Param data contains widget information */private void completeaddappwidget (intent data) {bundle extras = data. getextras (); int appwidgetid = extras. getint (appwidgetmanager. extra_appwidget_id,-1); log. D (TAG, "dumping extras content =" + Extras. tostring (); appwidgetproviderinfo appwidgetinfo = mappwidgetmanager. getappwidgetinfo (appwidgetid); // perform actual inflation because we're re live synchronized (mlock) {// get the view mhostview = mappwidgethost of the display widget. createview (this, appwidgetid, appwidgetinfo); mhostview. setappwidget (appwidgetid, appwidgetinfo); // Add the obtained view to layoutparams Lp = new linearlayout in the early layout. layoutparams (appwidgetinfo. minwidth, appwidgetinfo. minheight); mainlayout. addview (mhostview, LP); mhostview. requestlayout ();}}
5. Display and set Wallpaper
The display wallpaper is also an essential function of launcher. Let's take a look at how to display the wallpaper with the launcher we developed.
Create a project named showwallpaper. The procedure is omitted.
1. Show Wallpaper
To display a wallpaper in our activity is very simple (including dynamic wallpaper), we only need to define a theme so that it inherits from Android: theme. wallpaper, and then use this theme in the activity.
Add an XML file named styles. xml under Res/valuse. The content is as follows:
<Resources> <style name = "theme" parent = "Android: theme. Wallpaper"> <! -- Set windownotitle to true and remove the title bar --> <item name = "Android: windownotitle"> true </item> </style> </resources>
The results of the entire project are as follows:
The following code uses this theme in androidmanifest. xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ShowWallpaper" android:theme="@style/Theme" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
Okay, run the program to see the Display Effect of the wallpaper: (displays the preset live Wallpaper: Galaxy)
Setting wallpaper with code is also very simple, we only need to send a "Set Request" to the system, and other things are processed by the system.
Use the following code:
Public void onsetwallpaper (view) {// generate a request for setting wallpaper final intent pickwallpaper = new intent (intent. action_set_wallpaper); intent chooser = intent. createchooser (pickwallpaper, "chooser_wallpaper"); // send the request startactivity (chooser) for wallpaper setting );}
To call the above Code, we add a button in XML and set the callback function, such:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="setWallpaper" android:onClick="onSetWallpaper" /></LinearLayout>
Finally, run the code, as shown in the following steps:
After setting the wallpaper:
References:
Android hands-on teaches you how to develop launcher (1)
Android hands-on teaches you how to develop launcher (2)
Android hands-on teaches you how to develop launcher (3)
Android hands-on teaches you how to develop launcher (4)
Android hands-on teaches you how to develop launcher (5)