获取来电号码?

时间:2013-07-02 21:40:52

标签: java android

我正在开发一个获取来电号码的应用。

这是我正在尝试执行此操作的代码。

package com.example.callchecker;

import android.os.Bundle;
import android.app.Activity ;
import android.content.Context;
import android.telephony.*;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Activity extends Activity {
    String number;
    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        tv1=(TextView) findViewById(R.id.textView1);

        TelephonyManager telephonymanager =
            (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        //register phone state
        PhoneStateListener callstatelestener = new PhoneStateListener() {
            public void OnCallStateChanged(int state , String incomingNumber) {
                number = incomingNumber;
                tv1.setText(number);
                // If phone ringing
                if(state==TelephonyManager.CALL_STATE_RINGING)
                {
                    Toast.makeText(getApplicationContext(), "Phone Is Riging",
                            Toast.LENGTH_LONG).show();
                }
            }
        };

        telephonymanager.listen(callstatelestener,
                PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main_layout, menu);
            return true;
    }
}

但是当我在这个应用程序中时,即使打电话也没有做任何事情...... 天气我必须让它一直在后台工作????? 如果这是获得传入号码的正确方法???

1 个答案:

答案 0 :(得分:0)

在这个广泛的教程中,您将找到解决问题所需的所有答案: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html