顯示具有 java 標籤的文章。 顯示所有文章
顯示具有 java 標籤的文章。 顯示所有文章

2012年7月30日 星期一

在Intent間傳遞2個不同元件的值

在Intent間傳遞2個不同元件的值,並且設定可以清除EditText


主程式
public class MainActivity extends Activity {
     private EditText name;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        Spinner spinner=(Spinner)findViewById(R.id.spinner);
        //建立一個Adapter物件來放置下拉式選單物件
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,new String[]{"國營","民營","股份有限公司","SOHO"});
       //選擇下拉式選單樣式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
       
        //EditText
        name=(EditText)findViewById(R.id.username);
        //next Activity
        Button next_btn=(Button)findViewById(R.id.next);
        next_btn.setOnClickListener(ret_btn);
        //Button event
        Button button=(Button)findViewById(R.id.clear);
        button.setOnClickListener(bc);
       
       
    } 
    //rec_btn
    private OnClickListener ret_btn=new OnClickListener(){
                    
                @Override
                public void onClick(View v) {
                        // TODO Auto-generated method stub
                        //page透過Intent通知系統框架
                        Intent intent=new Intent();
                        //指定要呼叫的Activity class
                        intent.setClass(MainActivity.this,Report.class);
                        //建立Bundle物件
                        Bundle bundle=new Bundle();
                        //將附加的訊息儲存在Bundle
                        bundle.putString("username",((EditText)findViewById( R.id.username)).getText().toString());
                        bundle.putString("spinner",((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString());
                        //Bundle指定到Intent
                        intent.putExtras(bundle);
                        //呼叫新的Activity
                        startActivity(intent);
                        // 不結束原先的 Activity Class
            // 這樣按返回鍵時, 就可以回到這個 Activity
            //RadioActivity.this.finish();

                }
           
    };
    private OnClickListener bc=new OnClickListener(){

                @Override
                public void onClick(View arg0) {
                        // TODO Auto-generated method stub
               name.setText("");
                }
     };
       
}

下一個Intent
public class Report extends Activity {
        private TextView name;
        /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.report);
       
        //TextView name
         name=(TextView)findViewById(R.id.show);
        
         //取得前一個Activity傳過來的Bundle物件
         Bundle nameb = this.getIntent().getExtras();
         Bundle namec = this.getIntent().getExtras();
       // 取得的Bundle 中的資料設定
         String result = nameb.getString("username");
         String resultA = namec.getString("spinner");
       // 顯示結果    
         name.setText("你的帳號是:"+result+",你的單位是:"+resultA); 
   }
}






2012年1月10日 星期二

撥放音樂

請先將資源置入,可以選擇SD card或以資料夾的方式




XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/localBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="撥放SD卡音樂"
        android:onClick="OnLocalClick" />

    <Button
        android:id="@+id/urlBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="撥放網路音樂"
        android:onClick="OnUrlClick" />

    <Button
        android:id="@+id/resBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放資源檔"
        android:onClick="OnResClick" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/incBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+"
            android:onClick="OnIncClick" />

        <Button
            android:id="@+id/decBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-"
            android:onClick="OnDecClick" />
         <Button
            android:id="@+id/stopBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="STOP"
            android:onClick="OnStopClick" />
         <Button
            android:id="@+id/pauseBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PAUSE"
            android:onClick="OnPauseClick" />
          <Button
            android:id="@+id/playBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PLAY"
            android:onClick="OnPlayClick" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="音量" />

        <ProgressBar
            android:id="@+id/volPb"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="251dp"
            android:layout_height="wrap_content"
            android:max="15" />

    </LinearLayout>

</LinearLayout>

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
java
package com.demo.android.Player;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PlayerActivity extends Activity {
private ProgressBar volPb;
private MediaPlayer player;
private TextView title;
private AudioManager audio;
private int volume = 0;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //取得audio服務
        audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        title = (TextView)findViewById(R.id.title);
        volPb = (ProgressBar)findViewById(R.id.volPb);
        
        //取得目前音量
        volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
        
        //設定音量Bar
        volPb.setProgress(volume);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //釋放MediaPlayer物件
        if (player != null) {
        player.release();
        player = null;
        }
    }
    
    public void OnLocalClick(View v){
    String path = "file:///sdcard/FromU.mp3";//sdcard的音訊檔案
   
    //釋放MediaPlayer物件
        if (player != null) {
        player.release();
        player = null;
        }
   
    player = new MediaPlayer();
    try{
    player.setDataSource(path);
    player.prepare();
    player.start();
    title.setText("播放SD卡音樂...");
    }catch(Exception e){
        //Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
        e.printStackTrace();
        }
    }
    
    public void OnUrlClick(View v){
    String path = "http://fs.jcache.com/Download.aspx?fpath=ringtone%2f2010%2f12%2f2102420466.mp3";
        
    //釋放MediaPlayer物件
        if (player != null) {
        player.release();
        player = null;
        }
        
    player = new MediaPlayer();
        try{
       
       player.setDataSource(path);
       player.prepare();
       player.start();
       
       title.setText("播放網路音樂");
        }catch(Exception e){
       
        e.printStackTrace();
        }
        
        
    }
    
    public void OnResClick(View v){
        
    //釋放MediaPlayer物件
        if (player != null) {
        player.release();
        player = null;
        }
        
    player = MediaPlayer.create(this, R.raw.system);//system.mp3
        try{
       player.start();
       
       title.setText("播放資源檔音樂");
        }catch(Exception e){
       
        }
    }
    
    public void OnIncClick(View v){
    //調大聲
    audio.adjustVolume(AudioManager.ADJUST_RAISE, 0);
    //取得目前音量
        volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
        
        //設定音量Bar
        volPb.setProgress(volume);
   
    }
    
    public void OnDecClick(View v){
    //調小聲
    audio.adjustVolume(AudioManager.ADJUST_LOWER, 0);
    //取得目前音量
        volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
        
        //設定音量Bar
        volPb.setProgress(volume);
    }
    public void OnPauseClick(View v){
    player.pause(); //暫停    
    }
    public void OnStopClick(View v){
    player.stop(); //停止
    }
    public void OnPlayClick(View v){
    player.start(); //重新啟動
    }
}




2012年1月2日 星期一

猜數字遊戲

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請輸入四個不重複數字"
        android:textAppearance="?android:attr/textAppearanceLarge" />




    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <EditText
            android:id="@+id/inputEt"
            android:layout_width="226dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.93"
            android:inputType="number" />


        <Button
            android:id="@+id/guessBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />
    </LinearLayout>


    <TextView
        android:id="@+id/resultTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />


</LinearLayout>
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
JAVA

package com.demo.android.Guess;


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


public class GuessActivity extends Activity {
    /** Called when the activity is first created. */
private String result="";
private char[] numAnswer = {};
private char[] numInput = {};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        numAnswer = GenNum().toCharArray();
        
        Button guessBtn = (Button)findViewById(R.id.guessBtn);
        
        guessBtn.setOnClickListener(new Button.OnClickListener(){   
  public void onClick(View v){
   
  int countA=0;//A的個數
  int countB=0;//B的個數
   
   
  EditText inputEt = (EditText) findViewById(R.id.inputEt);
  numInput = inputEt.getText().toString().toCharArray();
   
  //比對數字
  for(int i=0; i<4; i++){
  for(int j=0;j<4;j++){
  if(numInput[i] == numAnswer[j]){
  if(i==j)
  countA+=1;//數字相同而且位置相同 +1A
  else
  countB+=1;//數字相同但是位置不同 -1A
  }
  }
  }
     
       
    result="=>"+countA+"A"+countB+"B";
     
    if( countA == 4){
    result += " 答對了!遊戲結束。";
    }
     
  //顯示資料
    TextView resultTv = (TextView)findViewById(R.id.resultTv);
    resultTv.setText(inputEt.getText().toString()+result);
     
    inputEt.setText("");//清除輸入
  }
    });
    }


    
    //亂數產生數字
    public String GenNum(){
    String number = "0123456789";
    String numAnswer = "";


    //從0~9抽號碼
    //每次亂數抽一個號碼
    for(int i=0; i<4; i++){
    //因為每次會抽一個號碼,所以數字個數會少一個
    //i=1 產生亂數第0~9個號碼 0123456789 假設抽到第3個數字3
    //i=2 產生亂數第0~8個號碼 012456789 假設抽到第6個數字7
    //i=3 產生亂數第0~7個號碼 01245689 假設抽到第1個數字1
    //...
    int randNum =(int)(Math.random()*(10-i));
    //抽到的號碼
    String randStr = number.substring(randNum, randNum+1);
    //刪掉抽到的號碼
    number = number.replace(randStr, "");
    //存抽到的號碼
    numAnswer += randStr;
    }
   
    //測試用,顯示答案
    TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(tv.getText().toString()+"( "+ numAnswer + " )");
     
    return numAnswer;
    }
}
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

2011年12月23日 星期五

來電警衛

由於我們需取得目前手機的通話狀態,因此必需在AndroidManifest.xml內新增一個讀取通話狀態的權限。
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Caller.java
package com.demo.android.Caller;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class CallerActivity extends Activity {
private PhoneState phoneState;

static String TABLE_NAME="Caller";
    static String ID="_id"; //使用SimpleCursorAdapter,欄位名稱必須為_id
    static String PHONE="phone";
    static String STATE="state";
 
    static String[] COLUMNS = { ID, PHONE, STATE };
    //android內建list樣式
    //android.R.layout.simple_list_item_2
    //android.R.id.hint
    //android.R.id.text1
    //android.R.id.text2
    static int[] TO = { android.R.id.hint, android.R.id.text1, android.R.id.text2};
    long selectedIndex = 0;//儲存點選ListView項目
 
    DBConnection dbconn;
     
    private Button InsBtn;
    private Button DelBtn;
    private RadioGroup stateRg;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        phoneState = new PhoneState(this);
     
        TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        telMgr.listen(phoneState, PhoneState.LISTEN_CALL_STATE);
     
        //建立資料庫實體
        dbconn=new DBConnection(this);
        show();
     
        InsBtn = (Button)findViewById(R.id.InsBtn);
        DelBtn = (Button)findViewById(R.id.DelBtn);
        stateRg = (RadioGroup) findViewById(R.id.stateRg);
        ListView callerLv = (ListView)findViewById(R.id.callerLv);
     
        //建立新增按鈕事件
        InsBtn.setOnClickListener(new Button.OnClickListener(){
        @Override
public void onClick(View v) {
// TODO Auto-generated method stub
        //取得DatePicker設定的日期
        String phoneEt = ((EditText)findViewById(R.id.phoneEt)).getText().toString();
        String state = "";

//新增Note
switch(stateRg.getCheckedRadioButtonId()){
case R.id.normal:
state = "鈴聲";
break;
case R.id.vibrate:
state = "震動";
break;
case R.id.silent:
state = "無聲";
break;
}

insert( phoneEt, state);

//清除EditText
((EditText)findViewById(R.id.phoneEt)).setText("");
}
        });
     
        //建立刪除按鈕事件
        DelBtn.setOnClickListener(new Button.OnClickListener(){
        @Override
public void onClick(View v) {
// TODO Auto-generated method stub
        delete(selectedIndex);
}
        });
     
        callerLv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view,
                                           int position, long id) {

//儲存點選編號
selectedIndex = id;
}
        });
     
     
    }
 
    //必須要覆寫OnResume,完成通話後才可以顯示資料表資料
    @Override
    protected void onResume() {
    super.onResume();
   
   
    show();
    }
 
    private void show() {
   
   
    SQLiteDatabase db=dbconn.getWritableDatabase();
        Cursor c=null;
     
        //查詢資料 SELECT _id, date, note FROM Notes
        c=db.query(TABLE_NAME, COLUMNS,null, null, null, null, null);  
     
      //使用SimpleCursorAdapter直接將資料表資料顯示至ListView上
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, COLUMNS, TO);
    ListView callerLv = (ListView)findViewById(R.id.callerLv);
    callerLv.setAdapter(adapter);
   
    //把建立的Cursor實體交給Activity管理,
    startManagingCursor(c);
   
    db.close();
    }
 
    private void insert(String phone, String state) {
    // 用ContentValues插入資料
    ContentValues values=new ContentValues();
values.put(PHONE,phone);
values.put(STATE,state);
SQLiteDatabase db = dbconn.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();

//ListView顯示Caller表格內容
show();
    }
 
    private void delete(long id) {
    // 刪除代號為id的資料
    SQLiteDatabase db = dbconn.getWritableDatabase();
    db.delete(TABLE_NAME, "_id=?" , new String[]{Long.toString(id)});
db.close();

//ListView顯示Caller表格內容
show();
    }
}
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="電話號碼" />

        <EditText
            android:id="@+id/phoneEt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="phone">"

            <requestFocus />
        </EditText>
    </LinearLayout>
 

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/TextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="來電狀態" />

        <RadioGroup
            android:id="@+id/stateRg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/normal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="鈴聲" />

            <RadioButton
                android:id="@+id/vibrate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="震動" />

            <RadioButton
                android:id="@+id/silent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="無聲" />
        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/InsBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="新增" />

        <Button
            android:id="@+id/DelBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="刪除" />
    </LinearLayout>

    <ListView
        android:id="@+id/callerLv"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:layout_weight="0.56" >
    </ListView>

</LinearLayout>
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
DBConnection.java

package com.demo.android.Caller;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBConnection extends SQLiteOpenHelper {

private static final String DATABASE_NAME="CallerDB";
    private static final int DATABASE_VERSION=1;
public DBConnection(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//建立表格
//空格一定要保留
String sql = "CREATE TABLE  Caller  ("
+ " _id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " phone text not null, "
+ " state text not null" + ");";

db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

}
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
package com.demo.android.Caller;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class PhoneState extends PhoneStateListener {
private String stateStr;
private Context context;
private AudioManager audioManager;
public PhoneState(Context c){
super();
context = c;
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
}
@Override
public void onCallStateChanged(int state, String incomingNumber){
super.onCallStateChanged(state, incomingNumber);
switch(state){
case TelephonyManager.CALL_STATE_IDLE:
//待機
stateStr = "待機預設為震動模式";
//待機預設為震動模式
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//通話中
stateStr = "通話中";
break;
case TelephonyManager.CALL_STATE_RINGING:
//來電
stateStr = GetStat(incomingNumber);
if(stateStr.equals("鈴聲")){
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}else if(stateStr.equals("震動")){
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}else if(stateStr.equals("無聲")){
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
break;
}
Toast.makeText(context, stateStr, Toast.LENGTH_SHORT).show();
}
private String GetStat(String incomingNumber){
//建立資料庫實體
DBConnection dbconn = new DBConnection(context);
SQLiteDatabase db = dbconn.getReadableDatabase();
String state = "";
        //取得所有資料放在list
        Cursor c = db.query("Caller", new String[]{"state"}, "phone = ?", new String[]{incomingNumber}, null, null, null);
c.moveToFirst();
if( c.getCount() > 0 ){
state = c.getString(0);
}
c.close();
return state;
}

}

2011年12月16日 星期五

PhoneStateListener_手機通話狀態

手機通話狀態,必須繼承PhoneStateListener這個類別
以下為API的reference 

Class Overview


A listener class for monitoring changes in specific telephony states on the device, including service state, signal strength, message waiting indicator (voicemail), and others.


Override the methods for the state that you wish to receive updates for, and pass your PhoneStateListener object, along with bitwise-or of the LISTEN_ flags to TelephonyManager.listen().


Note that access to some telephony information is permission-protected. Your application won't receive updates for protected information unless it has the appropriate permissions declared in its manifest file. Where permissions apply, they are noted in the appropriate LISTEN_ flags.


在監測設備上的特定電話的國家,包括服務的狀態,信號強度,消息等待指示(語音信箱),及其他變化的一個監聽器類別。


如果是在覆蓋的狀態,您希望收到更新的方法,需透過 PhoneStateListener,或LISTEN_ flags TelephonyManager.listen()。


需要注意的是一些電話信息的接聽權限保護。您的應用程序將不會收到保護信息的更新,除非它已在其清單文件中聲明的適當的權限。


權限申請需要在適當的LISTEN_ flags。


由於我們需取得目前手機的通話狀態,因此必需在AndroidManifest.xml內新增一個讀取通話狀態的權限。


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


package com.demo.android.PhoneStateListener;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import android.widget.Toast;

public class PhoneState extends PhoneStateListener {
private TextView textView;
private Context context;

public PhoneState(Context c){
super();
context = c;
}

@Override
public void onCallStateChanged(int state, String incomingNumber){
super.onCallStateChanged(state, incomingNumber);

switch(state){
case TelephonyManager.CALL_STATE_IDLE:
//待機
textView.setText("待機");
break;

case TelephonyManager.CALL_STATE_OFFHOOK:
//通話中
textView.setText("通話中");
break;

case TelephonyManager.CALL_STATE_RINGING:
//來電
textView.setText(incomingNumber+"來電");

break;
}
Toast.makeText(context, textView.getText().toString(), Toast.LENGTH_SHORT).show();

}

public void setTextView(TextView tv){
textView = tv;
textView.setText("待機");
}

}

========================================================================

package com.demo.android.PhoneStateListener;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class PhoneStateListenerActivity extends Activity {
private PhoneState phoneState;
private TextView phoneStateTv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        phoneStateTv = (TextView)findViewById(R.id.phoneStateTv);
        phoneStateTv.setText("123");
        
        phoneState = new PhoneState(this);
        phoneState.setTextView(phoneStateTv);
        
        TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        telMgr.listen(phoneState, PhoneState.LISTEN_CALL_STATE);
    }
}