My Calendar

2014年8月17日 星期日

CCNA Security Chapter 2 筆記

CCNA Security Chapter 2

Securing the Edge Router

Single Router Approach
A single router connects the protected network, or internal LAN to the internet. All security policies configured on this device. This is more commonly deployed in smaller site implementation. In smaller networks, the required security features can be supported  by ISRs without impeding the router's performance capabilities.


Defense-in-Depth Approach
Is more secure than the single router approach. In this approach, the router act as the first line defense and is know as a screening router. It passes all connection that are intended for the internal LAN to the firewall.

The second line of defense is the firewall. The firewall typically picks up the router leave off and perform additional filtering.


DMZ  Approach
A variation of defense-in-depth approach is to offer an intermediate area often call demilitarized zone (DMZ). The DMZ can be used for servers that must be accessible from the internet or some other external network. In the DMZ approach, the router provides some protection by filtering some traffic, but leaves the bulk of the protection to the firewall.


Three areas of router security must be maintained:
Physical Security:
  • Place the router and physical device that connects to it in a secure locked room that is accessible only to authorized personnel,
  • Install an uninterruptible power supply (UPS) and keep spare components available. This reduces the possibility of a DoS attack from power loss to the building.
Router Hardening: Eliminate potential abuse of unused port and services 
  • Secure administrator control. Ensure that only authorized personnel have access and that their level of access is controlled.
  • Disable unused ports and interfaces. Reduce the  number of ways  a device can be accessed.
  • Disable unnecessary services.
Operation System security: Secure the feature and performance of router operating system
  • Configure the router with the maximum amount of memory possible.The availability of memory can help protect the network from some DoS attacks, while supporting the widest range of security services. 
  • Use the latest stable version of the operation system that meet the feature requirement of network
  • Keep a secure copy of  router operation system image and router configuration files as a backup
Task involved in securing administrative access to an infrastructure device
  1. Restrict device accessibility : Limit the accessible port, restrict the permitted communications, and restrict the permitted method of access
  2. Log and account for all access : Record anyone who accesses a device, including what occurs and when.
  3. Authenticate access : Ensure that access is granted only to authenticated users, groups, and services. Limit the number of failed login attempts and the time between logins.
  4. Authorize action : Restrict the actions and views permitted by any particular users, groups, or service.
  5. Present legal notifications : Display a legal notice, developed in conjunction with company legal course, for interactive session
  6. Ensure the confidentiality of data : Protect locally store sensitive data from viewing and copying 
Two ways to access a device for administrative purposes

Local Access : Local access to a router usually requires a direct connection to a console port on the Cisco router using a computer that is running terminal emulation software.

Remote Access : Some network devices can be accessed remotely. Remote access typically involves allowing Telnet, Secure Shell (SSH), HTTP, HTTPS, or Simple Network Management Protocol (SNMP) connections to the router from a computer For security reason, it is preferable to allow only local access to the router. However, remote access might still be necessary. When accessing the network remotely, a few precautions should be taken:

  • Encrypt all traffic between administrator computer and router
  • Establish a dedicated management network
  • Configure packet filter allow only identified administration host and preferable protocol to access the router
Configure Secure Administrative Access
Attacker deploy various methods of discovering administrative passwords. Such as L0phtCrack and Cain & Abel to attempt brute force attacks and guess passwords.

Guidelines designed to make passwords less easily discovered:
  • Use a password length of 10 or more characters
  • Make password complex. Include mix upper, lower case letters, numbers, symbol, and spaces.
  • Avoid password based on repetition or other easily identification information.
  • Deliberately misspell password
  • Change password often
  • Do not write password down and leave them in obvious place.
Configure Router Password

Enable Secret Password
The enable secret password is global configuration commands restricts access to privileged EXEC mode. The password hashed by MD5. If password lost or forgotten, using the Cisco password recovery procedure.

Console Line
Default, console port does not require password. However, it should always configure as a console port line-level password. Use the line console 0 command followed by the login and password on the console line.


Virtual Terminal Lines
Default, Cisco routers support five simultaneous virtual terminal vty (Telnet or SSH) sessions. On the router, the vty ports are numbered from 0 through 4. Use the line vty 0 4 command followed by the login and password.


Auxiliary Line
Default, Cisco router auxiliary ports do not require a password for remote administrative access. Administrators sometimes use this port to remotely configure and monitor the router using a dialup modem connection.

Enhance Security for Virtual Logins
The Cisco IOS login enhancements feature provides more security for Cisco IOS devices when creating a virtual connection, such as Telnet, SSH, or HTTP, by slowing down dictionary attacks and stopping DoS attacks. To better configure security for virtual login connections, the login process should be configured with specific parameters:
  • Implement delays between successive login attempts.
  • Enable login shutdown if DoS attacks are suspected.
  • Generate system-logging messages for login detection.

Command: login block-for seconds attempts tries within seconds
All login enhancement features are disabled by default. Use the login block-for command to enable login enhancements. The login block-for feature monitors login device activity and operates in two modes:
  • Normal mode (watch mode) - The router keeps count of the number of failed login attempts within an identified amount of time. 
  • Quiet mode (quiet period) - If the number of failed logins exceeds the configured threshold, all login attempts using Telnet, SSH, and HTTP are denied.

Login will disabled for 120 seconds if more than 5 login attempts within 60 seconds
  • This command must be issued before any other login command can be used.
  • This command can help provide DoS detection and prevention.



Command : login quiet-mode access-class {acl-name | acl-number}
When quiet mode is enabled, all login attempts, including valid administrative access, are not permitted. However, to provide critical hosts access at all times, this behavior can be overridden using an ACL.

The example shows a configuration that invokes on ACL named PERMIT-ADMIN. Hoste that match the PERMIT-ADMIN are exempt from the Quiet-Mode.
  • Command specifies an ACL is applied to the router when switched to Quiet-Mode and identifies hosts that are exempt from the Quiet-Mode failure time.
  • If not configured, all login requests will be denied during the Quiet-Mode.

Command : login delay seconds
This delay time can be changed using the login delay command. The login delay command introduces a uniform delay between successive login attempts. The delay occurs for all login attempts, including failed or successful attempts. 

  • Helps mitigate dictionary attacks
  • This is an optional command. If not set, a default delay of one second is enforced after the login block-for command is configured.
Command : log commands

  1. login on-failure log [every login]
  2. login on-success log [every login]


Configuring SSH

  1. Configure the IP domain name. : If the router has a unique host name, configure the IP domain name of the network using the ip domain-name domain-name command in global configuration mode.
  2. Generate one-way secret keys : To create the RSA key, use the crypto key generate rsa general-keys modulus modulus-size command in global configuration mode
  3. Verify or create a local database entry : Ensure that there is a valid local database username entry. If not, create one using the username name secret secret command.
  4. Enable VTY inbound SSH sessions : Enable vty inbound SSH sessions using the line vty commands login local and transport input ssh.

SSH timeouts and authentication retries
Router(config)#ip ssh time-out seconds
Router(config)#ip ssh authentication-retries tries

Version
Router(config)#ip ssh verison verison
version1 or 2

Configuring Privilege Levels

16 Privilege Levels
  • Level 0Predefined for user-level access privileges. Seldom used, but includes five commands: disable, enable, exit, help, and logout.
  • Level 1: The default level for login with the router prompt Router>. A user cannot make any changes or view the running configuration file.
  • Levels 2 –14: May be customized for user-level privileges. 
  • Level 15:  Users can change configurations and view configuration files.

Configuring Role-Based CLI Access
Role-based CLI provides three type of views:

Root View : To configure any view for the system, the administrator must be in root view. Root view has the same access privileges as a user who has level 15 privileges. However, a root view is not the same as a level 15 user. Only a root view user can configure a new view and add or remove commands from the existing views. 

CLI View : A specific set of commands can be bundled into a CLI view. Unlike privilege levels, a CLI view has no command hierarchy and, therefore, no higher or lower views. Each view must be assigned all commands associated with that view, and a view does not inherit commands from any other views. Additionally, the same commands can be used in multiple views. 

Superview : A superview consists of one or more CLI views. Administrators can define which commands are accepted and which configuration information is visible. Superviews allow a network administrator to assign users and groups of users multiple CLI views at once, instead of having to assign a single CLI view per user with all commands associated to that one CLI view. 

Superview characteristics : 

  • A single CLI view can share within multiple superviews.
  • Commands cannot be configured for a superview. An administrator must add commands to the CLI view and add that CLI view to the superview.
  • User who logged into a superview can access all the commands configure by CLI views
  • Each superview has a password that is used to switched between superviews or form a CLI view to superview
 


Create and manage specific view :

  1.  Exit and enter the root view with the enable view command.
  2.  Create a view using parser view command
  3. Assign a secret password to the view using secret command
  4. Assign commands to the view using the  commands parser-mode {include | include-exclusive | exclude} [all] [interface interface-name | command] command in view configuration mode.

Create and manage superview :
  1. Create a view using the parser view view-name superview command and enter superview configuration mode.
  2. Assign a secret password to view
  3. Assign an existing view using the view view_name
  4. Exit superview

Restore a primary bootset

  1. Reload the router using the reload command
  2. The device name can be found in the output from show secure bootset
  3. Using the boot command with the file name found in Step 2.
  4.  Go to global configuration mode conf t
  5.  Restore secure configuration files using secure boot-config restore filename command
Using Syslog for Network Security
Configure the router to send log messages:
  • Console : Console logging is default. Message log to the console can viewed when modifying or testing the router using terminal emulation.
  • Terminal lines : Enable EXEC mode can be configured to received log messages on any terminal lines
  • Buffered logging : Is a little more useful as a security tool because log messages are stored in router memory for a time. However, the vent are cleared when the router reboot.
  • SNMP traps : Can be preconfigured on routers. SNMP traps are a viable security logging facility but required the configuration and maintenance of an SNMP system
  • Syslog : Cisco routers can be configured to forward log message to an external syslog service. Syslog is the most popular message logging facility, because it provides long-term log storage capabilities and a central location for all router message 
Cisco Router log message contain three main part:
  1. Timestamp
  2. Log message name and severity level
  3. Message text
Severity Levels






Syslog implementations contains two types of system
  • Syslog servers : Knows as log hosts, these systems accept and process log messages from syslog clients
  • Syslog clients : Routers or other type devices that generate and forward log messages to syslog servers.
Configure system logging :
  1. Set the destination host using the logging host command
  2. (Optional) Set the log security level using logging trap level command
  3. Set the source interface using the logging source-interface command
  4. Enable logging 


Reference :
1) CCNA Security Cisco Network Academy

2014年8月15日 星期五

CCNA Security Chapter 1 筆記

CCNA Security Chapter 1

Viruses, Worms, and Trojan Horse
The primary vulnerabilities for end users computers are virus, worm and Trojan Horse attacks:

  • Viruses = Malicious software which attaches to another program to execute a specific unwanted function on a computer.
  • Worm = Executes arbitrary code and installs copies of itself in the memory of the infected computer, which then infects other hosts.
  • Trojan Horse = An application written to look like something else. When a Trojan Horse is downloaded and opened, it attacks the end user computer from within.

Viruses
Malicious code that is attached to legitimate programs or executable files:
  • Most viruses require end user activation and can lay dormant for an extended period and then activate at a specific time or date.
  • A simple virus may install itself at the first line of code on an executable file.
  • Viruses can be harmless, such as those that display a picture on the screen, or can be destructive, such as delete files on the hard drive
Worms
Particularly dangerous type of hostile code. They replicate themselves by independently exploiting vulnerabilities in network.
  • Virus require host program to run, worms can run by themselves.
  • Do not require user participation and can spread very quickly over network.
Worms attack-Three major components
  • Enabling vulnerability = A worms install itself using an exploit mechanism(email-attachment, executable file, Trojan) on a vulnerable system.
  • Propagation mechanism = After gaining access to a device, the worm replicates itself and locates new targets. 
  • Payload - Any malicious code that results in some action. Most often this is used to create a backdoor to the infected host. 
Five phase of attack
  1. Probe phase = Vulnerable targets are identified. The goal is to find computer that can be subverted.
  2. Penetrate phase = Exploit code is transferred to the vulnerable target. The goal is to get the target to execute the exploit code through an attack vector.
  3. Persist phase = After the attack is successfully launched in the memory, the code tries to persist on the target system. The goal is to ensure that the attacker code is running and available to the attacker even if the system reboots.
  4. Propagate phase = The attacker attempts to extend the attack to other targets by looking for vulnerable neighboring machines.
  5. Paralyze phase = Actual damage is done to the system. Files can be erased, systems can crash, information can be stolen
Trojan Horse
A Trojan Horse is malware that carries out malicious operations under the guise of a desired function. It's contains hidden, malicious code that exploits the privileges of the user that runs it.

Trojan Horse classified according damage in system:
  • Remote-access Trojan Horse - Enables unauthorized remote access
  • Data sending Trojan Horse - Provides the attacker with sensitive data such as passwords
  • Destructive Trojan Horse - Corrupts or deletes files
  • Proxy Trojan Horse - User's computer functions as a proxy server
  • FTP Trojan Horse -Opens port 21
  • Security software disabled Trojan Horse - Stops antivirus programs or firewalls from functioning
  • Denial of Service Trojan Horse - Slows or halts network activity
Mitigating Viruses, Worms, and Trojan Horse
Mitigation technique referred in security community as "countermeasure".

The primary means of mitigating virus and Trojan Horse attacks is antivirus software.

Worm mitigation requires diligence and coordination on the part of network security professionals.The response to a worm infection can be broken down into four phases: 

  

  • Containment = Compartmentalization and segmentation of the network to slow down or stop the worm and prevent currently infected hosts from targeting and infecting other systems.
  • Inoculation = Runs parallel to or subsequent to the containment phase. During the inoculation phase, all uninfected systems are patched with the appropriate vendor patch for the vulnerability.
  • Quarantine = Tracking down and identifying infected machines within the contained areas and disconnecting, blocking, or removing them. Isolates these systems appropriately for the treatment phase.
  • Treatment = Actively infected systems are disinfected of the worm. This can involve terminating the worm process, removing modified files or system settings that the worm introduced, and patching the vulnerability the worm used to exploit the system.
Attack Methodologies
CCNA Security classifies attacks in three major categories:
  • Reconnaissance Attacks =  Involve the unauthorized discovery and mapping of systems, services, or vulnerabilities. Reconnaissance attacks often employ the use of packet sniffers and port scanners.
  • Access Attacks = Exploits known vulnerabilities in authentication services, FTP services, confidential databases etc. Access attacks often employs a dictionary attacks.attacks.
  • Denial of Service Attacks = Send extremely large numbers of request over a network or the Internet. There excessive request cause the target device become unavailable for legitimate access and use.

Reconnaissance Attacks
Reconnaissance also known as information gathering,. The attacks using various tools to gain access to a network.
  • Packet sniffer
  • Ping sweeps
  • Port scans
  • Internet information queries
Packet Sniffer
A software application that uses a network adapter card in promiscuous mode to capture all network packets that are sent across a LAN.

Promiscuous mode is a mode causes the controller to pass all traffic it receives to the CPU rather than passing only the frame that the controller is intended to receive.

Packet sniffer can only work in the same collision domain.

Tools : Wireshark

Ping Sweep
Basic network scanning technique that determine which range of IP addresses map to live hosts.

Tools : nmap

Port Scan
Scan a range of TCP and UDP port numbers on a host to detect listening services.

Tools : nmap

Internet information queries

Reveal information such as who owns a particular domain and what addresses have been assigned to that domain. They can also reveal who owns a particular IP address and which domain is associated with the address.

Tools : http://whois.net/

Access Attacks
Hackers use access attacks on networks or systems for three reasons: retrieve data, gain access, and escalate access privileges. 

There are five types of access attacks:

  1. Password attacks = An attacker attempts to guess system password
    • Brute-force
    • Trojan Horse
    • Packet sniffer
  2. Trust exploitation - An attacker uses privileges granted to a system in an unauthorized way, possibly leading to compromising the target.
  3. Port redirection - A compromised system is used as a jump-off point for attacks against other targets. An intrusion tool is installed on the compromised system for session redirection.
  4. Man-in-the-middle attack - An attacker is positioned in the middle of communications between two legitimate entities in order to read or modify the data that passes between the two parties.
  5. Buffer overflow - A program writes data beyond the allocated buffer memory. Buffer overflows usually arise as a consequence of a bug in a C or C++ program. A result of the overflow is that valid data is overwritten or exploited to enable the execution of malicious code.

Denial of Service Attack
Is a network attack that results in some sort of interruption of service to users, devices, or applications.

Two major reasons of DoS attacks occurs:

  1. A host or application fails to handle unexpected condition.
  2. A network, host, or application unable to handle enormous quantity of data
Three common DoS attacks:

  • Ping of Death = A hacker sends an echo request in an IP packet larger than the packet maximum size of 65,535 bytes, Sending a ping of this size can crash the target computer.
  • Smurf Attack = A perpetrator send a large number of ICMP request to directed broadcast addresses, all with spoofed source addresses on the same network as the respective directed broadcast.
  • TCP SYN Flood = TCP SYN Flood often with a forged sender address. Each packet is handled like a connection request, causing the server to spawn a half-open connection by sending back TCP SYN-ACK and waiting for a packet in response from the sender address.
Mitigating Network Attacks
Reconnaissance attack can be mitigate several ways:

  1. Implement authentication to ensure proper access.
  2. Use encryption to render packet sniffer attacks useless.
  3. Use anti-sniffer tools to detect packet sniffer attacks.
  4. Implement a switched infrastructure.
  5. Use a firewall and IPS.
Mitigate access attacks in several ways:
  1. Strong password security
  2. Principle of minimum trust
  3. Cryptography
  4. Applying operating system and application patches
Mitigate DoS Attack:
  1. IPS and firewalls
  2. Antispoofing technologies
  3. Quality of Service – traffic policing

Cisco Network Foundation Protection (NFP) framework 
NFP logically divides router and switches into three functional areas:

  • Control Plane = Responsible for routing data correctly. Control plane traffic consists of device-generated packets required for the operation of the network itself such as ARP message exchanges or OSPF routing advertisements.
  • Management Plane = Responsible for managing network elements. It is generated either by network devices or network management stations using processes and protocols.
  • Data Plane = Responsible for forwarding data.


Control plane
Control plane security can be implemented using the following features:

  • Cisco AutoSecure - Provides a one-step device lockdown feature to protect the control plane as well as the management and data planes. It is a script that is initiated from the CLI to configure the security posture of routers. The script disables nonessential system processes and services. It first makes recommendations to address security vulnerabilities and then modifies the router configuration.
  • Routing protocol authentication - Routing protocol authentication prevents a router from accepting fraudulent routing updates. 
  • Control Plane Policing (CoPP) - CoPP is a Cisco IOS feature designed to allow users to control the flow of traffic that is handled by the route processor of a network device.

Management plane
Management plane security can be implemented using the following features:
  • Login and password policy - Restricts device accessibility. Limits the accessible ports and restricts the "who" and "how" methods of access.
  • Present legal notification - Displays legal notices. These are often developed by legal counsel of a corporation. 
  • Ensure the confidentiality of data - Protects locally stored sensitive data from being viewed or copied. Uses management protocols with strong authentication to mitigate confidentiality attacks aimed at exposing passwords and device configurations. 
  • Role-based access control (RBAC) - Ensures access is only granted to authenticated users, groups, and services. RBAC and authentication, authorization, and accounting (AAA) services provide mechanisms to effectively manage access control. 
  • Authorize actions - Restricts the actions and views that are permitted by any particular user, group, or service.
  • Enable management access reporting - Logs and accounts for all access. Records who accessed the device, what occurred, and when it occurred.

Data plane
Data plane security can be implemented using the following features:
  • ACLs
  • Antispoofing
  • Layer 2 security including port security, DHCP snooping, dynamic ARP inspection (DAI)

Reference :
1) CCNA Security Cisco Network Academy

2014年7月26日 星期六

Android-建立選單(Menu)

Android-建立選單(Menu)

建立選單有兩種方法:
  1. 透過XML定義選單
  2. 透過程式碼定義選單

不管是第一種或第二種方法都要用onCreateOptionMenu建立選單。

透過XML定義選單

選單的xml描述檔在 res -> menu 當中,本篇的選單xml檔案名稱為main.xml(任何名稱都可以)在xml檔案裡定義我們想要的選單內容。以下是一個範例。

main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.bmi.MainActivity" >

<item
     android:id="@+id/action_settings"
     android:orderInCategory="100"
     android:title="@string/action_settings"
     android:showAsAction="never"/>

</menu>


menu標籤在加入item標籤,就可以定義每個選項與顯示的內容。
  • android:id = 指定選單項目的識別代號
  • android:title = 指定選項的名字。
  • android:orderInCategory = 指定選單間的排列順序,數字小的優先。若沒有指定這個屬性,則按照你定義item標籤的順序顯示。
  • android:showAsAction = 定義選單項目在ActionBar上的顯示方式。詳細資訊到Menu Resources看看。
將選單定義完成過後,要將定義好的選單加到Android應用程式上要用到onCreateOptionMenugetMenuInfalter.inflate().
@Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

透過程式碼定義選單

除了可以透過XML定義選單,也可以透過程式碼來定義選單。新增一個選項要用到menu.add()


menu.add(groupId, itemId, order, title)
  • groupId = 指定選項屬於哪一個組別
  • itemId = 指定每一個選項一個唯一值,如果沒有指定就用Menu.NONE
  • order = 排列順序
  • title = 顯示選項的名字

 
@Override 
public boolean onCreateOptionsMenu(Menu menu) {
  menu.add(0,Menu.FIRST,100,R.string.about)
  return true;
 }

處理選單項目的功能
當選單設定好過後,這時候要處理每個選單項目的功能就需要加入onOptionsItemSelected函式。
 
@Override
public boolean onOptionsItemSelected(MenuItem item){
  // TODO Auto-generated method stub
  switch(item.getItemId()) {
     case R.id.action_about:
       openOptionsDialog();
       break;
     case R.id.action_close:
       finish();
       break;
   }
    return super.onOptionsItemSelected(item);
}

onOptionsItemSelected這個函式可以處理所有選項項目。函式中傳入一個MenuItem型別的item參數程式中的super.onOptionsItesSelected(item)表示要先執行已定義在Activity類別中原本的onOptionsItemSelected函式內容,後面才執行我們為此函式新定義的動作。

接著要在程式中對每個選項作處理 :
 
 switch(item.getItemId()) {
   case R.id.action_about:
       openOptionsDialog();
       break;
   case R.id.action_close:
       finish();
       break;
}
我們可以使用item.getItemId()函式,來取得在熒幕上選取的選單項目所對應的識別符號。然後在『switch』中,根據從item.getItemId()所取得的識別符號判斷程式應該運行的流程。R.id.action_aboutR.id.action_close是XML檔中定義的識別符號。 

2014年6月15日 星期日

Android 程式開發(四)

Android 程式開發(四)

在 Android程式開發 (三) 中已經將BMI程式所需要的UI Components都已經建立好。接下來將開始BMI的程式設計。以下是BMI完整的程式。

package com.example.bmi;

import java.text.DecimalFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  initViews();
  setListener();  
 }
 
 private Button button_calc;
 private EditText num_height;
 private EditText num_weight;
 private TextView show_result;
 private TextView show_suggest;
 
 private void initViews(){
  button_calc = (Button)findViewById(R.id.submit); 
  num_height = (EditText)findViewById(R.id.height);
  num_weight = (EditText)findViewById(R.id.weight);
  show_result  = (TextView)findViewById(R.id.result);
  show_suggest  = (TextView)findViewById(R.id.suggest);
 }
 
 private void setListener(){
  button_calc.setOnClickListener(calcBMI);
 }

 
 private OnClickListener calcBMI = new OnClickListener(){
  public void onClick(View v){
     
    DecimalFormat nf = new DecimalFormat("0.00");
    double height = Double.parseDouble(num_height.getText().toString())/100;
    double weight = Double.parseDouble(num_weight.getText().toString());
    double BMI = weight/ (height*height);
     
    //Present result
    show_result.setText(getText(R.string.bmi_result)+nf.format(BMI));
       
    //Give advice 
    if(BMI > 25){
      show_suggest.setText(R.string.advice_heavy);
     } else if (BMI < 20){
      show_suggest.setText(R.string.advice_light);
     } else {
      show_suggest.setText(R.string.advice_average);
     }
  }
 };
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
}


第15-16行
@Override
protected void onCreate(Bundle savedInstanceState) {
}
『onCreate』是這個方法的名稱,同時傳入一個Bundle類別的參數savedInstanceState。目前只需要知道savedInstanceState只是處理記憶體相關的事情就可以。因為我們的『MainActivity』類別繼承了Activity類別,所以『MainActivity』也要實作『onCreate』方法。事實『onCreate』方法是每個Activity類別在初始化時都會呼叫的方法。第15行中有『@』開頭的語句,那是裝飾子(decorator)的語句,『@Override』的作用是告訴程式我們要覆載『onCreate』這個方法。這時候當程式執行的時,將不再使用Activity類別裡的『onCreate』方法,而是使用『MainActivity』中自行實作的行為。接下來看看『onCreate』方法中的程式內容。

第17行
super.onCreate(savedInstanceState);
『super』是關鍵字,表示『MainActivity』的父類別(Activity)。程式的意思是呼叫Activity中的『onCreate』方法。Activity類別初始化的時候都會呼叫『onCreate』的方法。原本繼承『Activity』類別的『onCreate』方法,因為『@Override』的原因內容被重寫。因此想要將『Activity』類別的『onCreate』方法保留並加入我們的內容,就要使用『super』語句。

第18行
setContentView(R.layout.activity_main);
要將我們所定義好的畫面顯示在Activity當中要用『setContentView』,而在上一章節所定義好的UI components在activity_main.xml檔案中,只要透過『setContentView』參數設定為『R.layout.activity_main』引用XML文件描述檔就能將UI 顯示在Activity中。

第24-36行
private void initViews(){
  button_calc = (Button)findViewById(R.id.submit); 
     ...
 }
這段程式主要的功用是宣告Android介面上全部的UI components。透過Activity類別中內建的『findViewById』方法,可以根據識別代號從資源檔中取得對應的UI components實體。這邊以『R.id.submit』按鈕元件為例。我們可以在前面加上『Button』來強制將這個UI components 實體轉型為Button類別的實體。

『R.id.submit』對應到XML描述檔的資源。
  <Button android:id="@+id/submit"
  />
第39行
button_calc.setOnClickListener(calcBMI);
這句是包含『Button』類別中『setOnClickListener』方法。方法中傳入一個名叫『calcBMI』的函式。在Android系統的UI互動方式是採用事件驅動方式。也就是當使用者按下『button_calc』按鈕的時候,Android系統會去觸發『setOnClickListener』方法中所指定的函式『calcBMI』。

 private OnClickListener calcBMI = new OnClickListener(){
  public void onClick(View v){
    ....
   }
};
當使用者按下按鈕時,就會觸發『OnClickListener』類型的事件函式。此範例中的所有邏輯運算都放在這函式中。

BMI值運算,BMI的公式是(體重/身高(m)*身高(m))
double height = Double.parseDouble(num_height.getText().toString())/100;
double weight = Double.parseDouble(num_weight.getText().toString());
double BMI = weight/ (height*height);

透過『TextView』類別中的『setText』方法將結果輸出到手機畫面。
show_result.setText(getText(R.string.bmi_result)+nf.format(BMI));

顯示建議
if(BMI > 25){
   show_suggest.setText(R.string.advice_heavy);
} else if (BMI < 20){
   show_suggest.setText(R.string.advice_light);
} else {
   show_suggest.setText(R.string.advice_average);
}

2014年5月19日 星期一

Android 程式開發(三)

           Android 程式開發(三)

上一篇 Android程式開發(二)介紹了Android的UI Components。接下來將會以開發一個BMI程式為例子進行講解。在開始寫BMI程式之前,應該先設計interface。

介面設計

我們從Form Widgets當中選擇兩個TextView,兩個Large Text和一個Button。再來從Text Fields當中選擇兩個 Number (Decimal)。然後將這些UI Components擺放在自己喜歡的地方。TextView是用來顯示文字,Large Text是用來顯示結果,Button是用來計算BMI,Number(Decimal) 則是讓使用者輸入。


然後點擊第一個Edit Text按右鍵,選擇Edit ID,會彈出一個對話框讓我們輸入識別符號,我們在對話框中輸入 『height』當作這個這個UI Component的識別符號。



除了使用 Graphical Layout的方法設定ID,當然也可以使用XML檔進行編輯。現在我們將切換到 『activity_main.xml』將會看到以下的片段。

<TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="身高 (cm)" />

『android:text』是用來顯示文字,而『android:id』和給UI Components的識別符號,每一個介面元件都要有一個ID,主要的用處是為了讓程式可以找到相關的UI Components。以下是完整的activity_main.xml的描述

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.bmi.MainActivity$PlaceholderFragment" />

<EditText
        android:id="@+id/weight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="numberDecimal" >
    </EditText>

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/weight"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:text="計算 BMI 值" />

    <TextView
        android:id="@+id/suggest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/result"
        android:layout_below="@+id/result"
        android:layout_marginTop="14dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/submit"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/height"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="numberDecimal" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:text="身高 (cm)" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView2"
        android:layout_below="@+id/height"
        android:text="體重 (kg)" />

</RelativeLayout>

將字串抽離XML介面描述檔

為了更好的維護介面,我們可以將『activity_main.xml』檔中的字串抽離。我們可以在 『res』->『values』->『string.xml』中定義我們所需要的字串如下。

    <string name="app_name">BMI</string>
    <string name="hello_world">Hello world!</string>
    <string name="bmi_height">身高 (cm)</string>
    <string name="bmi_weight">體重 (kg)</string>
    <string name="bmi_btn">計算  BMI 值</string>
    <string name="bmi_result">你的BMI值是 </string>
    <!-- advise -->
    <string name="advice_light">你該多吃點</string>
    <string name="advice_average">體型很棒</string>
    <string name="advice_heavy">你該節食</string>
    <!-- other -->
    <string name="action_settings">Settings</string>

定義完成後,要使用所定義的文字我們要使用"@string/"。可以在『Graphical Layout』中選擇『身高(cm)』然後按F2後輸入 @string/bmi_height 。有沒有注意畫面的感嘆號已經消失了。其他在介面所顯示的文字採用一樣的方法進行更換。

2014年4月8日 星期二

Android 程式開發(二)

Android 程式開發(二)


上一篇Android程式開發(一)介紹開發Android程式的工具和前置工作,接下來將討論Android的介面元件 (UI Components)。

在開發Android程式之前,一定要先弄清楚Android有提供那些UI components讓我們使用才能更好的開發Android程式。

Android UI Components

Android提供非常豐富和多樣化的UI components,開啟專案中的『res/layout/activity_main.xml』可以看到預覽畫面和包含Hello World的字串。在左下角有兩個標籤『Graphical Layout』和『activity_main.xml』。在『Graphical Layout』我們可以直接將UI components以drag and drop(拖、拉)的方式進行設定,而 『activity_main.xml』是採用XML檔案描述手機畫面,可以透過修改XML檔進而設計手機畫面。



UI components 根據GraphicalLayout上的分類,共有以下幾種

  • Form Widgets
  • Text Fields
  • Layouts
  • Composite
  • Images and Media
  • Time and Date
  • Transitions
  • Advanced
Android Form UI Components:

名稱 作用
TextView 顯示文字
Button 按鈕
Spinner 下拉選單
CheckBox 勾選鈕

Android Layout Components:


名稱 作用
Linear Layout 線性版面
Relative Layout 相對版面
FrameLayout 框架版面
TableLayout 表格版面

Android DatePicker Components:

名稱 作用
TimePicker 選取時間
DatePicker 選取日期
CalendarView 日曆檢視
AnalogClock 類比時鐘

更詳細的UI components到官網觀看Android UI Components

我們從預覽換面看到『Hello World!』,現在要把它改成『Hello, Android Program』。剛才提到有『Graphical Layout』和『activity_main.xml』描述手機畫面。透過『Graphical Layout』修改,只要點擊畫面中的『Hello World!』然後按 "F2" 就能直接修改文字。透過『activity_main.xml』我們看到如下的XML檔案:
        
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" ?>
我們只需要將『android:text="@string/hello_world"』改成 『android:text="Hello,Android Program"』就能將文字內容改變了。

Android 程式開發(一)

Android 程式開發(一)

Android 是什麼?
Android 簡單來說就是一個手持式設備(主要是手機)的作業系統平台。

安裝 Android 開發工具
Android的安裝流程可以分為以下兩個步驟 :
  1. 下載並安裝Java
  2. 到Android官網下載Eclipse (已經整合了Android 的套件) 或 Android Studio.(我是採用Eclipse)

Android程式執行前置工作
執行Android程式有兩種方法:
  1. 在Eclipse當中建立一個Android的虛擬機器
  2. 有一台Android 平台的手機 (廢話....)
     建立一個Android的虛擬機器
  1. 在Eclipse上方點選Android Virtual Device Manager                                                                                                  
  2. 點選過後會彈出一個表格然後點選New,接下來輸入虛擬器的名稱,你要的設備,CPU,Memory等等

  3. 設定完成後,就可以執行Android程式了。
     P.S. 個人而言不建議這種做法,因為每次執行虛擬機器的時候都需要等很久,當需要debug
     時真的很浪費時間尤其只有小錯誤的時候(其實是我沒耐心)。所以說既然要寫Android程式
     那不如買一台Android手機吧

     有一台Android手機
     如果你有一台Android手機那就太好了,不管在執行Android程式或者debug的時候都會很方  
     便。
     1. 首先要開啟手機的開發人員選項,然後對USB偵錯模式打勾。(Android 4.2 以上的使用者            官方因為安全因素將開發人員選項隱藏。開啟方法是設定->關於手機->不斷點選"軟體版
         本", 這樣就能開啟開發人員選項了)

     2.當你執行程式的時候會出現以下的圖,然後選擇 "Choose a running Android device" 就能將
        你所寫的程式在手機執行。

    
  
接下來將會討論關於Android手機的介面元件(User Interface Components)