2013年3月25日 星期一

Android 判斷目前手機鈴聲模式的設定值

想知道 android 手機目前是設定響鈴、震動或靜音,
可由 AudioManager 物件的 getRingerMode() 方法取得。

範例:

程式
package com.example.ringertest;

import android.os.Bundle;
import android.app.Activity;
import android.media.AudioManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class RingerTest extends Activity {
 private AudioManager audioManager;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_ringer_test);

  Button buttonRinger = (Button) findViewById(R.id.buttonringer);
  final TextView textRingerState = (TextView) findViewById(R.id.textringerstate);
  audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
  buttonRinger.setOnClickListener(new Button.OnClickListener() {

   @Override
   public void onClick(View arg0) {
    int ringerMode = audioManager.getRingerMode();
    if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
     textRingerState.setText("靜音");
    } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
     textRingerState.setText("震動");
    } else {
     textRingerState.setText("響鈴");
    }
   }
  });

 }
}

layout (activity_ringer_test.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=".RingerTest" >

    <TextView
        android:id="@+id/textringerstate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/buttonringer"
        android:layout_below="@+id/buttonringer"
        android:layout_marginTop="46dp"
        android:textIsSelectable="true" />

    <Button
        android:id="@+id/buttonringer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn" />

</RelativeLayout>

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">RingerMode測試</string>
    <string name="action_settings">Settings</string>
    <string name="btn">測試</string>

</resources>


執行結果

沒有留言:

張貼留言