Full tutorial is given below. Dear Viewer we are working hard to maintain this website. We doesn't want any think from you. Its just a humble request If you thinks that this posts helps you please share this post with your friends.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.usmtip.myapplication"> <!--VIBRATE permission--> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.MyApplication"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Click vibrate button below to start vibrating your phone." android:textAlignment="center" android:textColor="#000" android:textSize="20sp" /> <Button android:id="@+id/vibrateBtn" style="@style/Widget.AppCompat.Button.Colored" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:minWidth="150dp" android:text="Vibrate" /> </RelativeLayout>
MainActivity.java
package com.usmtip.myapplication; import android.os.Build; import android.os.Bundle; import android.os.VibrationEffect; import android.os.Vibrator; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { //declare Android Vibrator API private Vibrator vibrator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //init UI Button Button vibrateBtn = findViewById(R.id.vibrateBtn); //init Android Vibrator API vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); //handle button click, vibrate phone for 1000 microsecs (1 second) vibrateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= 26) { vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE)); } else { vibrator.vibrate(1000); } } }); } }
0 Comments: