Android

PS:這里的東西肯定會有些遺漏,不知道你掌握程度怎么樣,有些我認為你理所應當懂的就一筆帶過了,所以如果你發現了,及時告訴我哈。

1、Bitmap分類(要打印)

1.1 BPM

優點:simple and direct operation,原圖,原始數據,最真實的圖片
缺點:memory consumption
適用場景:photo,單反(For professional digital photographers,preserve an image’s fidelity.Preferred to a digital negative by many photographers, who feel it preserves the subtle color and details possible.Can adjust brightness,contrast,sharpen, white balance and can apply noise reduction, sensor dust removal

1.2 S-RAW and M-RAW

試用場景:wedding photographers、sports/action photographers(suitable for wedding photographers who don’t need full resolution for wedding candidates, but who do want the post- production control that RAW offers. Could also be used by sports/action photographers who will get an increase in the number of frames when shooting in bursts due to using a smaller file size)

1.3 GIF

適用場景:graphics such as cartoon, line art,
不適用于:Not good for photos(Max 256 color i.e. 8 bits per pixel, need color table ,some colors may be missing for photos)

1.4 PNG

不支持動畫

1.5 JPEG

適用場景:(natural image and photo)Good for natural image and photo ,lots of color levels and removing some of them cannot be easily noticed.For 640x480 24-bit image, need 900 kB,JPEG may become 30 kB
不適用:art line
優點:Smaller file sizes (more images can be stored)、Images are easy to view, mail and print than RAW files
缺點:Reduced post-processing flexibility、Reduced color depth and resolution、Need to get everything correct in-camera (only limited computer processing is possible)


2、Java基礎(理解即可,不需要背)

2.1 main 方法

Java程序的入口,每個Java程序有且僅有一個main函數,程序運行時,系統會執行main函數,入口函數!

public class Sample1 {
  public static void main(String[] args) {
      System.out.println("Welcome to COMP7506!");
  }
}

2.2 變量(variable)聲明

  • 1、聲明一個 Primitive 類型變量
int a = 1; 
// Primitive 類型:int、float、double、boolean、char
  • 2、聲明一個 Reference 類型變量(也就是類和對象)
People hyx = new People("Huang YingXue", 21);
// Reference 類型:所有的類,包括String、Button、ImageView都是Reference類型

2.4 類(Class)和對象(Objec/Instance)(要打印)

public class People {
    // 屬性
    String name;
    int age;

    // 構造方法
    public People(String name, int age) {
      this.name = name;
      this.age = age;
    }

    public void setName(String name) {
      this.name = name;
    }

    public int getAge() {
      return this.age;
    }
    
    public void eat() {
      // People eat  
    }
}
  • 使用 People 類的例子
// People 是類,hyx 是People類的一個對象,通過new創建了這個對象
People hyx = new People("Huang YingXue", 22); 

// 下面可以通過對象調用方法
hyx.setName("HYX");
int age = hyx.getAge();
hyx.eat();

2.5 static 變量

  • PPT上的解釋是:static variables are independent of any object

  • 下面給你看下區別

public class Friend {
  String name;
  static int count;
  
  public void addFriend() {
    count++;
  }
}
// 上面Friend類里,name是普通屬性,count是成員屬性
Friend.count = 0; // static 屬性可以直接通過 Friend類名訪問

// 而普通屬性必須通過對象名訪問
Friend mxm = new Friend();
mxm.name;

// static 屬性是獨立于對象的,所以我就算通過不同的對象調用addFriend(),都會導致count增加,看下面
Friend mxm = new Friend();
Friend hyx = new Friend();
mxm.addFriend();
hyx.addFriend();
// 完了之后,count變成了2

2.6 面向對象編程(OOP)的優點

(1)Simplicity(2)Modularity(3)Modifiability(4)Extensibility(5)Maintainability(6)Re-usability

2.7 for 和 while 循環

    for (int i = 0; i < 100; i++) {
      // Do something
    }

    // 先判斷條件是否滿足,再執行 // Do something處的代碼
    int count = 0;
    while (count < 100) {
      // Do something
      count++;
    }

    // 先執行do中的代碼,再判斷條件是否滿足
    int num = 0;
    do {
      // Do something
      num++;
    } while (num < 100);

    // 選擇器,一定要寫break,不然如果進了case 0,沒有break,會接著執行到case 1
    int type = 1;
    switch (type) {
      case 0:
        // Do something
        break;
      case 1:
        // Do something
        break;
      case 2:
        // Do something
        break;
      default:
        // Do something
        break;
    }

2.9 數組和ArrayList(代碼要打印)

  • 看我之前寫的這篇:教女朋友學Android -- 數組:Array和ArrayList

  • 最好看下ppt Java 24-25頁的例子

  • 下面是 ArrayList幾個需要掌握的方法
    (1)new ArrayList:創建一個新的ArrayList
    (2)add:向ArrayList添加一個元素
    (3)get:獲取某個元素
    (4)size:獲取數組的長度
    (5)indexOf:獲取某個元素在數組中的位置

  • 這個直接看懂ppt的例子就好了,不需要背,理解就好,不懂的問我,在Java基礎那一節講的。

2.12 其它

(1)Integer.parseInt("1");

  • 把字符串轉換成 int
String num = "11";
int a = Integer.parseInt(num); // 把字符串“11”轉換成整數11
  • 如果是 double的話,這么寫
String num = "6.666";
double a = Double.parseDouble(num);

(2)toString() (getText().toString()

  • 從TextView中通過getText()獲取到的內容,需要通過toString()轉換成字符串
TextView tv = findViewById(R.id.tv);
String str = tv.getText().toString();

(3)String.valueOf(int) / String.valueOf(float)

  • 記住 String.valueOf(....)括號里不管穿什么參數,都是把傳入的參數轉換成字符串
int r = 0;
TextView tv; 
tv.setText(String.valueOf(r));

(4)字符串拼接

// sample 1
String str1 = "Huang";
String str2 = " YingXue";
String name = str1 + str2; // Huang YingXue
//也可以這樣寫,一樣的結果
String name = "Huang" + " YingXue";

// sample 2(結合String.valueOf使用)
int r1 = 1;
int r2 = 2;
TextView tv;
tv.setText(String.valueOf(r1) + “ “ + String.valueOf(r2)); // 得到結果"12"

(5)Random 隨機數

  • 要記得 Random 和 do while 循環配合使用的例子
Random myRandom = new Random();
myRandom.nextDouble(); // 生成[0.0, 1.0)的隨機double數
myRandom.nextFloat(); // 生成[0.0, 1.0)的隨機float數
myRandom.nextInt(); //隨機生成一個整數
myRandom.nextInt(int n); //生成[0, n)的隨機整數

3、Android 基礎

3.1 概念

(1)OHA:A business alliance consisting of 47 companies to develop open standards for mobile devices
(2)Android 2017 Q1 市場占有率:85%,iOS 2017 Q1 市場占有率:14.7%
(3)2017 Q1 智能手機市場占有率:三星23.3%、Apple14.7%、華為10%、OPPO7.5%、vivo5.5%
(4)Android分層結構(要打印)

  • Application:Email Client、SMS Program、Calendar、Maps、Browser、Contacts
  • Application Framework:Developers have full access to the same framework APIs used by the core applications(View System、Content Provider、Resource Manager、Notification Manager、Activity Manager)
  • Libraries:Including a set of C/C++ libraries used by components of the Android system
  • Android Runtime:Providing most of the functionality available in the core
    libraries of the Java language(Data Structures、Utilities、File Access、Network Access、Graphics)
  • Hardware Abstraction Layer
  • Linux Kernel:Memory and Process Management、Network Stack、Driver Model、Security

3.2 AndroidManifest.xml 配置文件

AndroidManifest.xml

AndroidManifest.xml的重要屬性:(要打印)
(1)user-permission:表示APP需要的權限,如INTERNET(網絡訪問權限)
(2)package:表示APP 的 package name
(3)icon:設置 APP 的圖標
(4)activity:配置該 APP 需要展示的所有 activity

3.3 資源文件(res文件夾下)

  • 主要就是這三個
    (1)drawable:存放圖片
    (2)layout:存放布局文件
    (3)value:里面有string、style等幾個子文件夾,存放字符串和樣式等文件

3.4 如何新建 Android Studio project

  • 去看你們的 WordShop,了解下步驟

3.5 Activity 和 Layout file

  • All Android classes are inherited from Activity (old system) or AppCompatActivity (new system) superclass.(記得試卷上的填空題,在 extends 后面讓填 AppCompatActivity 或者是 Activity,看 import 了哪個就寫哪個,如果沒有 import 就寫 AppCompatActivity )

  • You must override the onCreate() methods in Activity / AppCompatActivity superclass.(在Activity中,onCreate()是程序的入口,類似于main()方法的作用)

(1)設置 Activity 要顯示的 Layout file

setContentView(R.layout.activity_main);

(2)xml 中 的 include 屬性:記住我卷子上給你講過的例子,include等于把被include的文件里的代碼插入到這個地方

(3)也可以直接把某個 View 直接 設置給 Activity 顯示,如下:

LinearLayout layout = new LinearLayout(this);
setContentView(layout);
  • 這樣,Activity 的根視圖就顯示這個 LinearLayout

(4)在 Activity 中獲得 Layout file 中某個控件的對象引用

  • findViewById(R.id.xxx) helps you to find the required components on the layout and then maps them to the corresponding variables.
Button btn1 = (Button)findViewById(R.id.btn1);

(5)設置Click Listener,兩種方法:

  • setOnClickListener
Button btn = findViewById(R.id.btnStart);
    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // Do Something
      }
    });
  • 布局文件中配置 onClick 屬性(和前者效果一樣)
// 先在布局文件中 activity_main.xml 這么寫
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="OpenWindow"
        android:text="Start"/>

// 然后在對應的Activity里寫上OpenWindow這個方法,如下:
public void OpenWindow(View v) {
    // Do something
}
  • 這樣,當該Button被點擊時,會執行 // Do Something 處的代碼

3.6 Activity 生命周期(要打印)

Activity 生命周期
  • (1) 新打開一個Activity,然后再關掉,這個過程的生命周期如下:onCreate()->onStart()->onResume()->onPause()->onStop()->onDestory()

  • (2) 假設已經打開了一個 Activity A,此時在 A 上面再打開一個全屏的 Activity B,然后再關掉 Activity B,在 Activity B 從打開到關閉的過程中,Activity A 的生命周期如下:onPause()->onStop()->(前半部分是打開B,接下來是關閉B)->onStart()->onResume()

  • (3) 假設已經打開了一個 Activity A,此時在 A 上面再打開一個對話框(或者是非全屏的Activity)。然后再關掉這個對話框,在此對話框從打開到關閉的過程中,Activity A 的生命周期如下:onPause()->(前面是打開對話框,接下來關閉對話框)->onResume()

3.7 Activity 之間的跳轉

  • 下面代碼的意思是,點擊一個 Button,從 ActivityA 跳轉到 ActivityB,并把整數 X 傳遞給 ActivityB,代碼如下:

ActivityA.java

Button btn = findViewById(R.id.btnStart);
    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        // 在這里跳轉到 ActivityB

        Intent intent = new Intent(ActivityA.this,ActicityB.class);
        // 把99傳遞給 ActivityB,key是“X”,在 ActivityB 中可以通過 “X”取到這個值
        intent.putExtra("X",99);
        startActivity(intent);
      }
 });

ActivityB

// 接受 ActivityA 傳遞過來的數據
Intent intent = getIntent();
int num = intent.getIntExtra("X",0); // 取到99,然后賦值給num,0是說如果沒取到任何值,就把0賦給num,默認值。

4、布局系統

  • 容器(Container)和控件(View)。

  • Container里可以包含其它 Container和 View,View 里不能包含任何元素

4.1 容器(Container/ViewGroup)

4.1.1 LinearLayout

(1)orientation:houriziontal、vertical

4.1.2 RelativeLayout

(1)第一類:描述該控件相對父容器的四個邊緣的位置(屬性值為true或false)
android:layout_alignParentBottom 貼緊父元素的下邊緣
android:layout_alignParentLeft 貼緊父元素的左邊緣
android:layout_alignParentRight 貼緊父元素的右邊緣
android:layout_alignParentTop 貼緊父元素的上邊緣

(2)第二類:描述該控件相對父容器居中的方向(屬性值為true或false)
android:layout_centerHrizontal 水平居中
android:layout_centerVertical 垂直居中
android:layout_centerInparent 相對于父元素完全居中
(3)第三類:描述該控件相對同級元素的外切位置(屬性值必須為id的引用名“@id/id-name”)
android:layout_below 在某元素的下方
android:layout_above 在某元素的的上方
android:layout_toLeftOf 在某元素的左邊
android:layout_toRightOf 在某元素的右邊

(4)第四類:描述該控件相對同級元素的內切位置(屬性值必須為id的引用名“@id/id-name”)
android:layout_alignTop 本元素的上邊緣和某元素的的上邊緣對齊
android:layout_alignLeft 本元素的左邊緣和某元素的的左邊緣對齊
android:layout_alignBottom 本元素的下邊緣和某元素的的下邊緣對齊
android:layout_alignRight 本元素的右邊緣和某元素的的右邊緣對齊

4.1.3 FrameLayout

上次給你講了的,按順序往FrameLayout中繪制元素,寫在后面的元素,覆蓋在最上面,默認對齊左上角。
記不得可以問我。

4.1.4 TableLayout

  • 表格布局
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/re s/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_height="match_parent"
             android:layout_width="match_parent">

    <TableRow>
        <Button
            android:id="@+id/backbutton"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Back"/>
    </TableRow>

    <TableRow>
        <TextView
            android:layout_column="1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="First Name"/>

        <EditText
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:width="500px"/>
    </TableRow>

    <TableRow>
        <TextView
            android:layout_column="1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Last Name"/>

        <EditText
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:width="500px"/>
    </TableRow>
</TableLayout>

4.1.5 ScrollView

當內容太長了放不下可滾動查看ScrollView里的內容

4.1.6 ConstraintLayout

類似 RelativeLayout:
(1)第一類屬性: layout_constraintLeft_toRightOf

<Button 
    android:id="@+id/buttonA" ... />
<Button 
    android:id="@+id/buttonB" ...
    app:layout_constraintLeft_toRightOf="@+id/buttonA" />

表示B的左邊緣貼著A的右邊緣:


image.png

(在水平布局中,Start就是Left,End就是Right)
– layout_constraintLeft_toLeftOf
– layout_constraintLeft_toRightOf
– layout_constraintRight_toLeftOf
– layout_constraintRight_toRightOf
– layout_constraintTop_toTopOf
– layout_constraintTop_toBottomOf
– layout_constraintBottom_toTopOf
– layout_constraintBottom_toBottomOf
– layout_constraintBaseline_toBaselineOf – layout_constraintStart_toEndOf
– layout_constraintStart_toStartOf
– layout_constraintEnd_toStartOf
– layout_constraintEnd_toEndOf

(2)第二類屬性
– android:layout_marginStart
– android:layout_marginEnd
– android:layout_marginLeft
– android:layout_marginTop
– android:layout_marginRight – android:layout_marginBottom

4.1.7 ListView(要打印)

  • 用來顯示這樣的列表,每一項都長得一樣,但是內容不同


    image.png
  • item_layout.xml(用于顯示每一個項目的布局,長得一樣所以通用這一個布局文件)

<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:padding="10dp"
    android:textSize="16sp" >
</TextView>
  • MainActivity.java
public class MainActivity extends AppCompatActivity {
    private ListView mainListView ;
    // 通過一個適配器,往ListView每一項塞數據
    private ArrayAdapter<String> listAdapter ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);

        // 初始化ListView
        mainListView = (ListView) findViewById( R.id.mainListView );

        // 這是每一項需要展示的數據
        String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
        ArrayList<String> planetList = new ArrayList<String>();
        planetList.addAll( Arrays.asList(planets) );

        // 初始化適配器,傳入R.layout.simplerow,planetList表示每一項需要顯示這個布局,傳入planetList告訴適配器每一項要顯示什么數據
        listAdapter = new ArrayAdapter<String>(this,R.layout.simplerow, planetList);
        
        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter( listAdapter );
   }
}

4.2 控件(View)

4.2.1 Button

  • 按鈕

4.2.2 TextView

  • text屬性:文字內容
  • textSize屬性:字體大小
<TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Hello"
            android:textSize="19sp"/>
  • 在Activity中設置文字內容
TextView tv = findViewById(R.id.tv);
tv.setText("Hello World!");

4.2.3 EditText

  • 輸入框
  • 在Activity中拿到EditText中輸入的內容
EditText et = findViewById(R.id.et);
String str = et.getText().toString();

4.2.4 ImageView

  • 在布局文件中,通過 src 屬性設置圖片
<ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_launcher_background"/>
  • 在Activity中設置圖片
ImageView image = findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher_background);
  • drawable 后寫的都是圖片的文件名

4.2.5 RadioGroup、RadioButton

  • RadioGroup 里裝 RadioButton,單選框的意思,就是圖片下面這玩意兒:
image.png
  • 這是布局文件
<RadioGroup 
    android:id="@+id/radioGroup" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
    <RadioButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"   
        android:text="男" 
        android:checked="true">
    </RadioButton>
    <RadioButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="女">
    </RadioButton>    
</RadioGroup>

// 第一個RadioButton 中的 checked="true" 表示第一次打開頁面時,這個項目是被選中的

  • 這是Activity里的部分代碼
        RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
         // 綁定一個監聽器,當單選框的任何一個項目(男或女)被選擇時,onCheckedChanged里的代碼都會被執行,
        group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(RadioGroup arg0, int arg1) {
                 // 如果選中單選框的“男”
                 int radioButtonId = arg0.getCheckedRadioButtonId();
                 RadioButton rb = (RadioButton)MyActiviy.this.findViewById(radioButtonId);
                 String sex = rb.getText());
             }
         });

4.3 通用屬性

(1)width、height、layout_width、layout_height:

  • match_parent / fill_parent:FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent.

  • wrap_content:Which means that the view wants to be just big enough to enclose its content.

  • width 和 layout_width 的區別在微信比較詳細的給你說過,你搜索微信聊天記錄看一下,分三種情況,不過我覺得你們不會考這個

(3)margin(外邊距):表示自身的位置偏移

(4)padding(內邊距):用于指定容器內部元素距離容器邊框的距離

(5)gravity = center:如果寫在普通控件上,表示該控件在父容器里是居中的,如果寫在TextView上,表示文字內容在TextView是居中的

(6)layout_gravity = center:不同于gravity ,layout_gravity 是作用于容器,表示該容器中所有的子元素都是居中排列的

(7)gravity和layout_gravity還有兩個值:centerHouriziontal(水平方向居中)、centerVertical(垂直方向居中)

4.4 Dimension 單位說明

  • 描述 Android 布局系統中的長度或大小有以下單位,用于修飾如 height、width、margin、padding 等屬性

(1)px:像素
(2)dp:在屏幕像素密度(dpi)是160的屏幕上,1dp=1px;在320dpi的屏幕上,1dp=2px;也就是說,dp和px是按照160的比例縮放。(這個要記住,可能會給你dpi的數值,讓你做dp和px的換算)
(3)sp:和dp類似,但是用于描述文字大小(TextView、EditText中的textSize屬性: android:textSize = 16sp


  • 下面這幾個都直接給你寫代碼,視頻講解

6、Sample Move Image(主要看onClick方法內部的代碼)

public class MainActivity extends AppCompatActivity {

  ImageView img;
  Button btnMoveLeft;
  Button btnMoveRight;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    img = findViewById(R.id.img);
    btnMoveLeft = findViewById(R.id.btnMoveLeft);
    btnMoveRight = findViewById(R.id.btnMoveRight);

    btnMoveLeft.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screen_width = size.x;
        int screen_height = size.y;

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) img.getLayoutParams();
        if (lp.leftMargin - 5 > 0) {
          lp.leftMargin -= 5;
          img.setLayoutParams(lp);
        }
      }
    });

    btnMoveRight.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screen_width = size.x;
        int screen_height = size.y;

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) img.getLayoutParams();
        if (lp.leftMargin + 5 > screen_width - lp.width) {
          lp.leftMargin += 5;
          img.setLayoutParams(lp);
        }
      }
    });
  }
}

7、Sample Dragging Image(主要理解Touch事件的類型、Down、Moce和Cancel)

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView image = findViewById(R.id.img);

    final RelativeLayout.LayoutParams par
            = (RelativeLayout.LayoutParams) image.getLayoutParams();

    image.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
            break;

          case MotionEvent.ACTION_MOVE:
            int x_cord = (int) event.getRawX();
            int y_cord = (int) event.getRawY();
            par.leftMargin = x_cord - par.width / 2;
            par.topMargin = y_cord - par.height / 2;
            image.setLayoutParams(par);
            break;

          case MotionEvent.ACTION_CANCEL:
            break;
        }
        return true;
      }
    });
  }
}

8、Playing Background Music(要打印,包括步驟)

  • 步驟

(1)Create folder “res/raw” on your project
(2)Place xxx.mp3 into “res/raw”
(3)然后代碼如下:

Button btnStart;
Button btnPause;
Button btnStop;

MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(this, R.raw.xxx);

btnStart.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if (!mediaPlayer.isPlaying())
          mediaPlayer.start(); 
      }
});

// btnPause(監聽器我就省略不寫了)
if (mediaPlayer.isPlaying())
    mediaPlayer.pause();

// btnStop
if (mediaPlayer.isPlaying())
    mediaPlayer.stop();

9、Vibration

  • 步驟

(1)需要在AndroidManifest.xml配置權限(要打印)

<uses-permission android:name="android.permission.VIBRATE"/>

(2)震動 1000 毫秒

Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);

(3)按規律震動

long[] pattern = { 100, 200, 500,100,200 }; // 等待100,震動200,等待500,震動100,等待200
v.vibrate(pattern, -1);// -1 代表不重復震動
v.vibrate(pattern, 0); // 0代表重復震動

(4)取消震動

v.cancel();

10、Network communications(要打印)

  • 需要在AndroidManifest.xml配置權限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class MainActivity extends AppCompatActivity {

  private TextView textView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 需要訪問的URL
    String stringUrl = "http://www.hku.hk/";
    // 獲取網絡連接和網絡信息
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    // 判斷網絡是否可用
    if (networkInfo != null && networkInfo.isConnected()) {
      new DownloadWebpageTask().execute(stringUrl);
    } else {
      // 表示網絡不可用
      textView.setText("No network connection available.");
    }
  }

  // 需要定義一個執行網絡訪問任務的類
  private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      try {
        // 調用下載網絡內容的方法,返回下載的內容
        return downloadUrl(urls[0]);
      } catch (IOException e) {
        // 如果下載失敗,會執行到這里
        return "Unable to retrieve web page. URL may be invalid.";
      }
    }

    @Override
    protected void onPostExecute(String result) {
      // 下載網頁內容成功,顯示在textView上
      textView.setText(result);
    }
  }

  // 下載網頁內容,傳入的參數就是網址URL
  private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    try {
      // 連接網絡并下載網頁內容,中間代碼不用理解,抄下來就好
      URL url = new URL(myurl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.connect();
      is = conn.getInputStream();
      String contentAsString = readIt(is, len);
      return contentAsString;
    } finally {
    }
  }
}

11、Timer function

  • 下面是你們16年試卷的例子,給你講了的,自己回憶下哈
public class MainActivity extends AppCompatActivity { 
    Long startTime;
    Long duration = new Long(1800000);
    Handler handler = new Handler();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView time = (TextView) findViewById(R.id.timer); 
        startTime = System.currentTimeMillis();
        handler.postDelayed(updateTimer, 1000);
    }
    
    private Runnable updateTimer = new Runnable() {
        public void run() {
            Long spentTime = System.currentTimeMillis() - startTime; 
            Long remainTime = duration - spentTime;
            Long minutes = (remainTime / 1000) / 60;
            Long seconds = (remainTime / 1000) % 60; 
            time.setText(minutes + ":" + seconds); 

            if (remainTime > 0) {
                handler.postDelayed(this, 1000);
            }

            if (remainTime == 0) {
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(10000); 
            }
    } };
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容