免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1398 | 回复: 0
打印 上一主题 下一主题

Android学习总结 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-30 23:06 |只看该作者 |倒序浏览

Android学习总结
Android教程
http://code.google.com/intl/zh-CN/android/intro/installing.html
http://code.google.com/intl/zh-CN/android/intro/hello-android.html
http://code.google.com/intl/zh-CN/android/intro/tutorial.html
android官方网站
http://www.android.com
android开发网站
http://developer.android.com
http://code.google.com/android/adt_download.html
Creating an Android Project
The ADT plugin provides a New Project Wizard that you can use to quickly create an Eclipse project for new or existing code. To create the project, follow these steps:
Select File > New > Project
Select Android > Android Project, and press Next
Select the contents for the project:
Select Create new project in workspace to start a project for new code.
Enter the project name, the base package name, the name of a single Activity class to create as a stub .java file, and a name to use for your application.
Select Create project from existing source to start a project from existing code. Use this option if you want to build and run any of the sample applications included with the SDK. The sample applications are located in the samples/ directory in the SDK.
Browse to the directory containing the existing source code and click OK. If the directory contains a valid Android manifest file, the ADT plugin fills in the package, activity, and application names for you.
Press Finish.
http://code.google.com/intl/zh-CN/android/samples/index.html
http://code.google.com/p/idea-android/wiki/GettingStarted
AndroidManifest.xml说明文档
http://code.google.com/intl/zh-CN/android/devel/bblocks-manifest.html
学习总结:
(1)Implementing a UI
设计界面用xml
setContentView(R.layout.layout_file_name)
(2)Building Blocks
Android APIs重要的部分
1.AndroidManifest.xml 是一个控制文件,告诉系统如何处理所有的顶层组件(特别是活动、服务、意图接收器,内容提供商下文)
2.Activities拥有生命周期的对象
3.Views用户界面是由视图树组成,视图用于界面的显示
4.Intents 是一个消息对象,代表做一些事情的意图
5.Services服务运行自己的进程,或另一个进程的上下文中.其它组件可以绑定到一个服务或通过远程进程调用来调用它的方法
6.Notifications 是一个出现在状态栏上的小图标,用户与之交互,通常的通知是SMS消息.
7.ContentProviders是一个提供访问在设备上的数据的数据仓库
   
(3)Storing and Retrieving Data
1.Preferences
2.Files
3.Databases
4.Content Providers
5.Network   
(4)Security Model
Resources and i18n
Life Cycle of an Android Application

一 Activity的生命周期
public class MyActivity extends Activity {   
    protected void onCreate(Bundle savedInstanceState);   
  
    protected void onStart();   
  
    protected void onResume();   
  
    protected void onPause();   
  
    protected void onStop();   
  
    protected void onDestroy();   
  }   
onCreate:    在这里创建界面,做一些数据的初始化工作
   onStart:   到这一步变成用户可见不可交互 的
   onResume:   变成和用户可交互 的,(在activity栈系统通过栈的方式管理这些个      
                      Activity的最上面,运行完弹出栈,则回到上一个Activity)
   onPause:     到这一步是可见但不可交互 的,系统会停止动画等消耗CPU 的事情
                    从上文的描述已经知道,应该在这里保存你的一些数据,因为这个时候
                    你的程序的优先级降低,有可能被系统收回。在这里保存的数据,应该在
                    onResume里读出来,注意:这个方法里做的事情时间要短,因为下一
                    个activity不会等到这个方法完成才启动
   onstop:      变得不可见 ,被下一个activity覆盖了
   onDestroy:  这是activity被干掉前最后一个被调用方法了,可能是外面类调用finish方
                     法或者是系统为了节省空间将它暂时性的干掉,可以用isFinishing()来判
                     断它,如果你有一个Progress Dialog在线程中转动,请在onDestroy里
                     把他cancel掉,不然等线程结束的时候,调用Dialog的cancel方法会抛
                     异 常 的。                     
              
二 让Activity变成一个窗口:Activity属性设定
android:theme="@android:style/Theme.Dialog"
android:theme="@android:style/Theme.Translucent"  
三 你后台的Activity被系统回收怎么办:onSaveInstanceState
public void onSaveInstanceState(Bundle outState) {   
    super.onSaveInstanceState(outState);   
    if(savedInstanceState != null){   
     long id = savedInstanceState.getLong("id");   
}   
}  
四 调用与被调用:我们的通信使者 - Intent
Intent intent = new Intent();   
intent.setAction(Intent.ACTION_CALL);   
intent.setData(Uri.parse("tel:" + number));   
startActivity(intent);  
那Intent通过什么来告诉系统需要谁来接受他呢?
通常使用Intent有两种方法,第一种是直接说明需要哪一个类来接收代码如下:

Java代码
Intent intent = new Intent(this, MyActivity.class);   
intent.getExtras().putString("id", "1");   
tartActivity(intent);  
Intent intent = new Intent(this, MyActivity.class);
intent.getExtras().putString("id", "1");
tartActivity(intent);
第一种方式很明显,直接指定了MyActivity为接受者,并且传了一些数据给MyActivity,在MyActivity里可以用getIntent()来的到这个intent和数据。
第二种就需要先看一下AndroidMenifest中的intentfilter的配置了

Xml代码
  
      
      
      
      
      

Notepad剖析
Android Tools > Fix Project Properties 修复在错误的地方寻找库文件
_id 的作用
The _id is named with an underscore convention used in a number of places inside the Android SDK and helps keep a track of state. The _id usually has to be specified when querying or updating the database (in the column projections and so on).
上下文对象
The constructor for NotesDbAdapter takes a Context, which allows it to communicate with aspects of the Android operating system. This is quite common for classes that need to touch the Android system in some way. The Activity class implements the Context class, so usually you will just pass this from your Activity, when needing a Context.
/*********************************************************************/
private final Context mCtx;
  public NotesDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
/*********************************************************************/
创建数据库
private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, "
                    + "title text not null, body text not null);";
DatabaseHelper, which is our local implementation of the SQLiteOpenHelper class
/*********************************************************************/
private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }
/*********************************************************************/
open()  creating/opening a database
close()  closes the database, releasing resources related to the connection.
createNote() takes strings for the title and body of a new note, then creates that note in the database. Assuming the new note is created successfully, the method also returns the row _id value for the newly created note.
deleteNote() takes a rowId for a particular note, and deletes that note from the database.
fetchAllNotes() issues a query to return a Cursor over all notes in the database. The query() call is worth examination and understanding. The first field is the name of the database table to query (in this case DATABASE_TABLE is "notes"). The next is the list of columns we want returned, in this case we want the _id, title and body columns so these are specified in the String array. The remaining fields are, in order: selection, selectionArgs, groupBy, having and orderBy. Having these all null means we want all data, need no grouping, and will take the default order.
fetchNote() is similar to fetchAllNotes() but just gets one note with the rowId we specify
updateNote() takes a rowId, title and body, and uses a ContentValues instance to update the note of the given rowId.
/*********************************************************************/
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
打开数据库
public NotesDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
关闭数据库   
public void close() {
        mDbHelper.close();
}
插入一条新的记录用 ContentValues 对象来实例华
public long createNote(String title, String body) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_BODY, body);
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }
删除一条记录
  public boolean deleteNote(long rowId) {
        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
查询所有记录,并返回指针对象
   public Cursor fetchAllNotes() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
                KEY_BODY}, null, null, null, null, null);
    }
查询一条记录,并返回指针对象
public Cursor fetchNote(long rowId) throws SQLException {
        Cursor mCursor =mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                        KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
更新一条记录用 ContentValues 对象来实例华
  public boolean updateNote(long rowId, String title, String body) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_BODY, body);
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
/*********************************************************************/
程序的布局文件
All Android layout files must start with the XML header line: .
The next definition will often (but not always) be a layout definition of some kind.
The XML namespace of Android should always be defined in the top level component or layout in the XML so that android: tags can be used through the rest of the file:
xmlns:android="
http://schemas.android.com/apk/res/android
"
/*********************************************************************/
  
  
/*********************************************************************/
The @ symbol in the id strings of the ListView and TextView tags means that the XML parser should parse and expand the rest of the id string and use an ID resource.
The ListView and TextView can be thought as two alternative views, only one of which will be displayed at once. ListView will be used when there are notes to be shown, while the TextView (which has a default value of "No Notes Yet!" defined as a string resource in res/values/strings.xml) will be displayed if there aren't any notes to display.
The list and empty IDs are provided for us by the Android platform, so, we must prefix the id with android: (e.g., @android:id/list).
The View with the empty id is used automatically when the ListAdapter has no data for the ListView. The ListAdapter knows to look for this name by default. Alternatively, you could change the default empty view by using setEmptyView(View) on the ListView.
The + after the @ in the id string indicates that the id should be automatically created as a resource if it does not already exist.
android.R文件的作用
the android.R class is a set of predefined resources provided for you by the platform, while your project's R class is the set of resources your project has defined. Resources found in the android.R resource class can be used in the XML files by using the android: name space prefix (as we see here).
Activity和ListActivity区别与联系
ListActivity has extra functionality to accommodate the kinds of things you might want to do with a list, for example: displaying an arbitrary number of list items in rows on the screen, moving through the list items, and allowing them to be selected
Activity的方法
onCreate() is called when the activity is started — it is a little like the "main" method for an Activity. We use this to set up resources and state for the activity when it is running.
onCreateOptionsMenu() is used to populate the menu for the Activity. This is shown when the user hits the menu button, and has a list of options they can select (like "Create Note").
onOptionsItemSelected() is the other half of the menu equation, it is used to handle events generated from the menu (e.g., when the user selects the "Create Note" item).
strings.xml文件的作用
strings.xml resource (under res/values)
添加菜单
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.menu_insert);  /***strings.xml  Add Item***/
        return result;
    }
The arguments passed to add() indicate: a group identifier for this menu (none, in this case), a unique ID (defined above), the order of the item (zero indicates no preference), and the resource of the string to use for the item.





本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/86601/showart_1885062.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP