版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Android Programming: Setup for Android DevelopmentBased on material from Adam Champion, Xinfeng Li, C. Horstmann 1, J. Bloch 2, C. Collins et al. 4, M.L. Sichitiu (NCSU), V. Janjic (Imperial College London), CSE 2221 (OSU), and other sources1Outline Introduction to Android Getting Started Android Pr
2、ogramming2Introduction to Android Popular mobile device OS: 52% of U.S. smartphone market 8 Developed by Open Handset Alliance, led by Google Google claims 900,000 Android device activations 9Source: 83What is Android Android is an operating system for mobile devices such as smartphones and tablet c
3、omputers. It is developed by the Open Handset Alliance led by Google. Android has beaten Apple iOS, being the leading mobile operating system from first quarter of 2011 Version: Android 1.0, 1.1 to 1.5 (Cupcake), 1.6 (Donut), 2.0/2.1 (Eclair), 2.2 (Froyo), 2.3 (Gingerbread), to 3.0 (Honeycomb), 4.0
4、(Ice Cream Sandwich), 5.0 (Lollipop)Android ArchitectureOutline Introduction to Android Getting Started Android Programming6Getting Started (1) Need to install Java Development Kit (JDK) to write Java (and Android) programs Do not install Java Runtime Environment (JRE); JDK and JRE are different! Ca
5、n download the JDK for your OS at Alternatively, for OS X, Linux: OS X: Open Type javac at command line Install Java when prompt appears Linux: Type sudo aptget install defaultjdk at command line (Debian, Ubuntu) Other distributions: consult distributions documentation7Install!8Getting Started (2) A
6、fter installing JDK, download Android SDK from Simplest: download and install Android Studio bundle (including Android SDK) for your OS Alternatives: Download/install Android Developer Tools from this site (based on Eclipse) Install Android SDK tools by themselves, then install ADT for Eclipse separ
7、ately (from this site) Well use Android Studio with SDK included (easy)9Install!10Getting Started (3)Install Android Studio directly (Windows, Mac); unzip to directory android-studio, then run (Linux)You should see this:11Getting Started (4) Strongly recommend testing with real Android device Androi
8、d emulator: very slow Faster emulator: Genymotion 14, 15 Install USB drivers for your Android device! Bring up the Android SDK Manager Recommended: Install Android 2.2, 2.3.3 APIs and 4.x API Do not worry about Intel x86 Atom, MIPS system imagesSettingsNow youre ready for Android development!12Outli
9、ne Introduction to Android Getting Started Android Programming1314Android Highlights (1) Android apps execute on Dalvik VM, a “clean-room” implementation of JVM Dalvik optimized for efficient execution Dalvik: register-based VM, unlike Oracles stack-based JVM Java .class bytecode translated to Dalvi
10、k EXecutable (DEX) bytecode, which Dalvik interprets15Android Highlights (2) Android apps written in Java 5 Actually, a Java dialect (Apache Harmony) Everything weve learned still holds Apps use four main components: Activity: A “single screen” thats visible to user Service: Long-running background
11、“part” of app (not separate process or thread) ContentProvider: Manages app data (usually stored in database) and data access for queries BroadcastReceiver: Component that listens for particular Android system “events”, e.g., “found wireless device”, and responds accordingly16App Manifest Every Andr
12、oid app must include an file describing functionality The manifest specifies: Apps Activities, Services, etc. Permissions requested by app Minimum API required Hardware features required, e.g., camera with autofocus External libraries to which app is linked, e.g., Google Maps library17Activity Lifec
13、ycleActivity: key building block of Android apps Extend Activity class, override onCreate(), onPause(), onResume() methods Dalvik VM can stop any Activity without warning, so saving state is important! Activities need to be “responsive”, otherwise Android shows user “App Not Responsive” warning: Pla
14、ce lengthy operations in Runnable Threads, AsyncTasksSource: 1218App Creation Checklist If you own an Android device: Ensure drivers are installed Enable developer options on device under Settings, specifically USB Debugging Android 4.2+: Go to SettingsAbout phone, press Build number 7 times to enab
15、le developer options For Android Studio: Under FileSettingsAppearance, enable “Show tool window bars”; the Android view shows LogCat, devices Programs should log states via s Log.d(APP_TAG_STR, “debug”), where APP_TAG_STR is a final String tag denoting your app Other commands: Log.e() (error); Log.i
16、() (info); Log.w() (warning); Log.v() (verbose) same parameters19Creating Android App (1) Creating Android app project in Android Studio: Go to FileNew Project Enter app, project name Choose package name using “reverse URL” notation, e.g., Select APIs for app, then click Next20Creating Android App (
17、2) Determine what kind of Activity to create; then click Next Well choose a Blank Activity for simplicity Enter information about your Activity, then click Finish This creates a “Hello World” app21Deploying the App Two choices for deployment: Real Android device Android virtual device Plug in your r
18、eal device; otherwise, create an Android virtual device Emulator is slow. Try Intel accelerated version, or perhaps Run the app: press “Run” button in toolbar22Underlying Source Codepackage edu.osu.helloandroid;import android.os.Bundle;import android.app.Activity;import android.view.Menu;public clas
19、s MainActivity extends ActivityOverrideprotected void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Overridepublic boolean onCreateOptionsMenu(Menu menu)/ Inflate the menu; this adds items to the action bar if it is present.getMenuInflat
20、er().inflate(R.menu.main, menu);return true;23Underlying GUI Code RelativeLayouts are quite complicated. See 13 for details24The App Manifest 25A More Interesting App Well now examine an app with more features: WiFi Tester (code on class website) Press a button, scan for WiFi access points (APs), di
21、splay them26Underlying Source Code (1)Overridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.activity_wi_fi);/ Set up WifiManager.mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);/ Create listener object for Button. When B
22、utton is pressed, scan for/ APs nearby.Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener()public void onClick(View v)boolean scanStarted = mWifiManager.startScan();/ If the scan failed, log it.if (!scanStarted) Log.e(TAG, WiFi scan failed.););/ Set
23、 up IntentFilter for WiFi scan results available Intent.mIntentFilter = new IntentFilter();mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);27Underlying Source Code (2)Code much more complexFirst get system WifiManagerCreate listener Object for button that performs scansWe register
24、 Broadcast Receiver, mReceiver, to listen for WifiManagers “finished scan” system event (expressed as Intent WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)Unregister Broadcast Receiver when leaving ActivityOverrideprotected void onResume()super.onResume();registerReceiver(mReceiver, mIntentFilter);Overr
25、ideprotected void onPause()super.onPause();unregisterReceiver(mReceiver);28The Broadcast Receiverprivate final BroadcastReceiver mReceiver = new BroadcastReceiver()Overridepublic void onReceive(Context context, Intent intent)String action = intent.getAction();if (WifiManager.SCAN_RESULTS_AVAILABLE_A
26、CTION.equals(action)Log.e(TAG, Scan results available);List scanResults = mWifiManager.getScanResults();mApStr = ;for (ScanResult result : scanResults)mApStr = mApStr + result.SSID + ; ;mApStr = mApStr + result.BSSID + ; ;mApStr = mApStr + result.capabilities + ; ;mApStr = mApStr + result.frequency
27、+ MHz;mApStr = mApStr + result.level + dBmnn;/ Update UI to show all this information.setTextView(mApStr);29User InterfaceUpdating UI in codeprivate void setTextView(String str)TextView tv = (TextView) findViewById(R.id.textview);tv.setMovementMethod(new ScrollingMovementMethod();tv.setText(str);Thi
28、s code simply has the UI display all collected WiFi APs, makes the text information scrollableUI Layout (XML) 30Android Programming NotesAndroid apps have multiple points of entry: no main() method Cannot “sleep” in Android During each entrance, certain Objects may be null Defensive programming is v
29、ery useful to avoid crashes, e.g., if (!(myObj = null) / do something Java concurrency techniques are required Dont block the “main” thread in Activities Implement long-running tasks such as network connections asynchronously, e.g., as AsyncTasks Recommendation: read 4; chapter 20 10; 11Logging stat
30、e via throughout app is essential when debugging (finding root causes)Better to have “too many” permissions than too few Otherwise, app crashes due to security exceptions! Remove “unnecessary” permissions before releasing app to publicEvent handling in Android GUIs entails many listener Objects31Con
31、currency: Threads (1)Thread: program unit (within process) executing independentlyBasic idea: create class that implements Runnable interface Runnable has one method, run(), that contains code to be executed Example:public class OurRunnable implements Runnable public void run() / run code Create a T
32、hread object from Runnable and start() Thread, e.g.,Runnable r = new OurRunnable();Thread t = new Thread(r);t.start();Problem: this is cumbersome unless Thread code is reused32Concurrency: Threads (2) Easier approach: anonymous inner classes, e.g.,Thread t = new Thread(new Runnable( public void run(
33、) / code to run );t.start(); Idiom essential for one-time network connections in Activities However, Threads can be difficult to synchronize, especially with UI thread in Activity. AsyncTasks are better suited for this33Concurrency: AsyncTasksAsyncTask encapsulates asynchronous task that interacts with UI thread in Activity:public class AsyncTask protected Result doInBackground(Pa
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 某著名企业双创项目介绍
- 某著名企业商务礼仪培训资料
- 《GB-Z 31477-2015航空电子过程管理 航空电子产品高加速试验定义和应用指南》专题研究报告
- 《GBT 16538-2008声学 声压法测定噪声源声功率级 现场比较法》专题研究报告
- 《GBT 21778-2008化学品 非啮齿类动物亚慢性(90天)经口毒性试验方法》专题研究报告
- 《GBT 15825.5-2008金属薄板成形性能与试验方法 第5部分:弯曲试验》专题研究报告
- 《GBT 2317.2-2008电力金具试验方法 第2部分:电晕和无线电干扰试验》专题研究报告
- 道路安全出行教育培训课件
- 道路交通安全法安全培训课件
- 2026年国际注册内部审计师考试试题题库(答案+解析)
- 2025年贸易经济专业题库- 贸易教育的现状和发展趋势
- 核子仪考试题及答案
- DB46-T 481-2019 海南省公共机构能耗定额标准
- 劳动合同【2026版-新规】
- 电子元器件入厂质量检验规范标准
- 中药炮制的目的及对药物的影响
- 688高考高频词拓展+默写检测- 高三英语
- 学生公寓物业管理服务服务方案投标文件(技术方案)
- 食品检验检测技术专业介绍
- 2025年事业单位笔试-贵州-贵州财务(医疗招聘)历年参考题库含答案解析(5卷套题【单项选择100题】)
- 二年级数学上册100道口算题大全(每日一练共12份)
评论
0/150
提交评论