2016年4月13日星期三

Android开发入门

内容简介

vAndroid简介
v开发环境配置
vSDK简介
v新建工程 / 运行
v工程配置说明
vDebug / Log
v常用UI组件
vActivity / Application生命周期
vService / Asynctask
vIntent / Broadcast
v打包发布流程
v进阶学习

Android简介

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。
Android作为一个移动设备的开发平台,其软件层次结构包括:
应用程序(Application)
应用程序框架(Application Framework)
各种库(Libraries)Android运行环境(Runtime)
操作系统层(OS)

开发环境配置

JDK 1.6 / 1.7
Android SDK
Eclipse
Help->Eclipse Marketplace
搜索 android,安装 Android Development Tools for Eclipse
Android Studio / IntelliJ IDEA

Ø1.启动 Eclipse, 点击菜单Window > Preferences
Ø2.点击Android,在SDK Location:选择SDK的目录
 


v其它设置
vWindow>Preferences  搜索

          



SDK简介
http://developer.android.com/sdk/exploring.html

docs - Android SDKAPI参考文档
platforms - 每个平台的SDK文件,里面会根据APILevel划分的SDK版本,data保存着一些系统资源,images是模拟器映像文件,skins则是Android模拟器的皮肤,templates是工程创建的默认模板,android.jar则是该版本的主要framework文件
platform-tools - 一些通用工具,比如adb、和aaptaidldx等文件,从android2.3开始这些工具被划分为通用了
tools 重要的工具,比如ddms用于启动Android调试工具,比如logcat、屏幕截图和文件管理器,而draw9patch则是绘制android平台的可缩放png图片的工具,sqlite3可以在PC上操作SQLite数据库,而monkeyrunner则是一个不错的压力测试应用,模拟用户随机按键,mksdcard则是模拟器SD映像的创建工具,emulatorAndroid SDK模拟器主程序。
samples - 示例工程


新建工程 / 运行

新建工程 启动Eclipse, 选择File >New>Android Application Project


v导入工程
vFile>Import>Existing Android Code Into Workspace

v运行工程
Run>Run As>Android Application
v真机
v模拟器





工程配置说明
1.src/,工程源文件,包括活动Java文件和所有其他的Java应用程序的文件
2.gen/包名/R.java文件。自动生成的工程资源索引,不需要修改。Android对资源进行了全局索引。res文件夹中内容发生任何变化,R.java都会重新编译,同步更新。
3.assets/,里边主要放置多媒体等一些文件。
4.res/,应用程序资源,如drawable文件,布局文件,字符串值等,当中的资源文件发生变化的时候,上边的R文件的内容就会自动发生变化。
---drawable  主要放置应用到的图片资源
---layout   主要放置用到的布局文件,都是xml文件
---values  主要放置字符串(String.xml)颜色(color.xml),数组(Arrays.xml)
5.androidMainfest.xml, 应用的配置文件。声明应用相关信息,包括名称,应用所用到的ActivityService,以及receiver等。
6.project.properties,自动生成,工程目标版本,打包混淆配置。
7.bin/,输出目录
        

Debug / Log

v断点调试

Run>Debug As>Android Application


Log输出


常用UI组件
v界面布局
vView / Viewgroup / Layout / LayoutParams
vAll user interface elements in an Android app are built using View and ViewGroup objects. A View is an object that draws something on the screen that the user can interact with. A ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the interface.


vLayout Parameters



v常用组件

v按钮(Button)
v文本框(TextView)
v编辑框(EditText)
v多项选择(CheckBox)
v单项选择(RadioGroup)
v下拉列表(Spinner)
v自动填充(AutoCompleteTextView)
v日期选择(DatePicker)
v滚动视图(ScrollView)
v进度条(ProgressBar)
v拖动条(SeekBar)
v标签(Tab)
v菜单menu


Android常用组件
vActivity
vService
vIntent
vHandler
vMessage
vAyncTask
vBroadcast / BroadcastReceiver


Activity / Application生命周期 


Activity回调方法
public class ExampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

v应用启动
onCreate()->onStart()->onResume
vBACK键退出
onPause()->onStop()->onDestory()
vHOME键退出
onPause()->onStop()
v再次启动应用程序
onRestart()->onStart()->onResume()


v应用程序退出功能?
v应用程序后台运行?


保存程序状态

vTasks and Back Stack
vA task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the "back stack"), in the order in which each activity is opened.
 

vTwo tasks: Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed.

           

Service

Service回调方法
public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used
    @Override
    public void onCreate() {
        // The service is being created
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to startService()
        return mStartMode;
    }
    @Override
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }
    @Override
    public void onRebind(Intent intent) {
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }
    @Override
    public void onDestroy() {
        // The service is no longer used and is being destroyed
    }
}


BindService示例
public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    // Random number generator
    private final Random mGenerator = new Random();
    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }
}


public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}


v通过Handler在service和activity传递消息
public class MessengerService extends Service {
    /** Command to the service to display a message */
    static final int MSG_SAY_HELLO = 1;
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
    final Messenger mMessenger = new Messenger(new IncomingHandler());
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        return mMessenger.getBinder();
    }
}

vHandler调用
public class ActivityMessenger extends Activity {
    Messenger mService = null;
    boolean mBound;
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }
        public void onServiceDisconnected(ComponentName className) {
            mService = null;
            mBound = false;
        }
    };
    public void sayHello(View v) {
        if (!mBound) return;
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to the service
        bindService(new Intent(this, MessengerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    }
    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }
}

AsyncTask
直接使用普通线程方式执行异步操作
public void onClick(View v) {
    new Thread(new Runnable() {
        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
            mImageView.post(new Runnable() {
                public void run() {
                    mImageView.setImageBitmap(bitmap);
                }
            });
        }
    }).start();
}

使用AsyncTask执行异步任务
public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }
   
    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}



vdoInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI
vonPostExecute(Result)  相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI
v
vonProgressUpdate(Progress…)   可以使用进度条增加用户体验度。
vonPreExecute()        这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,可以在这里显示进度对话框。
vonCancelled()             用户调用取消时,要做的操作


Intent / Broadcast
v通过Intent启动Activity
v[1] Activity A creates an Intent with an action description and passes it to startActivity(). [2] The Android System searches all apps for an intent filter that matches the intent. When a match is found, [3] the system starts the matching activity (Activity B) by invoking its onCreate() method and passing it the Intent. 


vBroadcast / BroadcastReceiver

  public void onReceive(Context context, Intent intent)
    <receiver android:enabled=["true" | "false"]
              android:exported=["true" | "false"]
              android:icon="drawable resource"
              android:label="string resource"
              android:name="string"
              android:permission="string"
              android:process="string" >
        . . .
    </receiver>
contained in:
    <application>
can contain:
    <intent-filter>
    <meta-data>


Android进程和线程
v进程
The manifest entry for each type of component element<activity>, <service>, <receiver>,
and <provider>supports an android:process attribute that can specify a process in which that component should run.
v前台进程 - 控制当前UI交互
   It hosts an Activity that the user is interacting with (the Activity's onResume() method has been called).
    It hosts a Service that's bound to the activity that the user is interacting with.
    It hosts a Service that's running "in the foreground"the service has called startForeground().
    It hosts a Service that's executing one of its lifecycle callbacks (onCreate()onStart(), or onDestroy()).
    It hosts a BroadcastReceiver that's executing its onReceive() method.
v可见进程 - 不在前台显示,但影响当前UI交互
    It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
    It hosts a Service that's bound to a visible (or foreground) activity.

vService进程
A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories.
v后台进程
A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called).
v空进程
A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. 

v线程
vWhen an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. It is also the thread in which your application interacts with components from the Android UI toolkit (components from the android.widget and android.view packages). As such, the main thread is also sometimes called the UI thread.
vThe system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread.
vDo not block the UI thread
vDo not access the Android UI toolkit from outside the UI thread

打包发布流程

选择工程
右键>Android Tools>Export Signed/Unsigned Application Package





进阶学习
vSDK samples
vAndroid API Guides
v常用布局和UI组件
v本地文件存取
v网络(HTTP/JSON/XML)
v数据库(sqlite)





没有评论:

发表评论