在我的应用程序中,我需要记录每个来电和去电

时间:2014-01-01 17:42:54

标签: java android

以下是接收器类的代码

package com.example.crecording;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IInterface;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class callReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

          phoneListener phonestateListener = new phoneListener(context);
          TelephonyManager telephony = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);
          telephony.listen(phonestateListener, PhoneStateListener.LISTEN_CALL_STATE);

    }

    class phoneListener extends PhoneStateListener{
        private Context context;
        phoneListener(Context c){
            super();
            context=c;
        }
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
             SharedPreferences preferences =     context.getSharedPreferences("CallReceiver", Context.MODE_PRIVATE);
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE :
                Toast.makeText(context, state+"",Toast.LENGTH_SHORT).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:

                     String phone_number = preferences.getString("phone_number",null);
                     Intent serv = new Intent(context,
                     cRecordingservice.class);
                     serv.putExtra("number", phone_number);
                     context.startService(serv);

                     Toast.makeText(context, state+"",Toast.LENGTH_SHORT).show();   
                     break;
            case TelephonyManager.CALL_STATE_RINGING :
                   SharedPreferences.Editor editor = preferences.edit();
                   editor.putString("phone_number", incomingNumber);
                   editor.commit();
                   Toast.makeText(context, state+""+incomingNumber,Toast.LENGTH_LONG).show();
                break;

            }
        }   
    }
}

以下是来电记录服务的代码

    package com.example.crecording;

import java.io.File;
import java.io.IOException;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class cRecordingservice extends Service  {
    MediaRecorder callrecorder;
    Boolean recording;
    MainActivity main=new MainActivity();
    BroadcastReceiver myreceiver=new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {

        myphonestatelistener mpl=new myphonestatelistener(context);
        TelephonyManager tm=(TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
        tm.listen(mpl,PhoneStateListener.LISTEN_CALL_STATE);

        }

        class myphonestatelistener extends PhoneStateListener{
            private Context context;

            myphonestatelistener(Context c){
                context=c;
            }

            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                // TODO Auto-generated method stub
                super.onCallStateChanged(state, incomingNumber);

                switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    if(recording){
                        stopRecording();
                        Toast.makeText(context, "stopped", Toast.LENGTH_SHORT).show();

                    }

                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    if(!recording){
                    startRecording();
                    Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case TelephonyManager.CALL_STATE_RINGING:

                    break;


                }
            }



        }
            };



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
         Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();

         IntentFilter RecFilter = new IntentFilter();
         RecFilter.addAction("android.intent.action.PHONE_STATE");
         RecFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
         registerReceiver(myreceiver, RecFilter);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(myreceiver);
        Toast.makeText(getApplicationContext(), "Service destroyed", Toast.LENGTH_LONG).show();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
//      startRecording();
        return  START_STICKY;


    }



    void startRecording(){
        String root="/sdcard/";
        String fname="rec"+System.currentTimeMillis()+".amr";
        File file=new File(root,fname);
        callrecorder=new MediaRecorder();
        callrecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
        callrecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        callrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        callrecorder.setOutputFile(file.getAbsolutePath()
                );
        try {
            callrecorder.prepare();

            callrecorder.start();
            recording=true;
//          Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_SHORT).show();  
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
//          Toast.makeText(getApplicationContext(),e.printStackTrace(),3000 ).show();
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


void stopRecording(){

        callrecorder.stop();
//      callrecorder.release();
        callrecorder.reset();
        recording=false;

    }





}

MainActivity.java

public class MainActivity extends Activity {
    Intent intent2;
    static MediaRecorder callrecorder;
    static Boolean recording=false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnStart=(Button)findViewById(R.id.button1);
        Button btnStop=(Button)findViewById(R.id.button2);
        btnStart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Start Service", 10000).show();
                intent2 = new Intent(getApplicationContext(), cRecordingservice.class);
//                getApplicationContext().startService(intent2);    

            }
        });

        btnStop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Stop Service", 10000).show();
                intent2 = new Intent(getApplicationContext(), cRecordingservice.class);
                getApplicationContext().stopService(intent2);
            }
        });
    }

}

以下是清单代码

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.crecording.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name="com.example.crecording.callReceiver" >
        <intent-filter >
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            <action android:name="android.intent.action.PHONE_STATE"/>
        </intent-filter>
    </receiver>
    <service android:name="com.example.crecording.cRecordingservice" ></service>
</application>

更改后的应用程序能够录制一个电话,但之后会生成无法识别格式的文件&amp;将文件追加到当前文件。我不知道为什么会发生这种情况

1 个答案:

答案 0 :(得分:1)

当手机状态发生变化时(例如,从“空闲”到“摘机”),您似乎开始了录制服务。但是在那个服务中你没有注册你的广播接收器来监听电话状态的变化,你也没有开始录音,所以什么都没发生。

您应该将数据传递给服务,以便在启动时告知电话状态更改,然后确保在启动时注册广播接收器。您还需要处理这样一个事实,即您现在有两个广播接收器正在侦听电话状态变化,并可能启动和停止录制。