開發者要讓使用者知道狀態
有時會採用音效、震動模式
讓使用者知道是有觸發的
目前採用 Kotlin 語法,會與 Java 有稍許不同
在此先來記錄
以便之後用的到
思路:
1 . 手機權限存取
2 . 取得對應服務
3 . 設定震動參數
實作開始
1 . 手機權限存取
<uses-permission android:name="android.permission.VIBRATE" />
2 . 取得手機對應服務
var myVibrator = application.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator;
3 . 設定手機震動參數
if (Build.VERSION.SDK_INT >= 26) {
myVibrator?.vibrate(VibrationEffect.createOneShot(100, 10));
} else {
myVibrator?.vibrate(100);
}
Source Code
import android.app.Service
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.support.v7.app.AppCompatActivity
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var myVibrator1: Vibrator;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myVibrator1 = application.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator;
constraintCounterBackground.setOnClickListener(this);
}
override fun onClick(view: View) {
when (view?.id) {
R.id.constraintCounterBackground -> {
println("item found");
if (Build.VERSION.SDK_INT >= 26) {
myVibrator1?.vibrate(VibrationEffect.createOneShot(100, 10));
} else {
myVibrator1?.vibrate(100);
}
var intCounterNum = (textCounterNum.text.toString()).toInt();
textCounterNum.setText((intCounterNum + 1).toString());
}
else -> {
println("item not found");
}
}
}
}
參考資料:
Android-Vibrator
Android學習筆記 - 震動(Vibrator)
Android vibrate is deprecated. How to use VibrationEffect in Android>= API 26?
沒有留言:
張貼留言