如何在android中的listview中分隔传入和传出的呼叫记录文件

时间:2014-08-08 09:03:12

标签: android listview

我正在开发录音应用程序。因为它将记录所有传入和传出的呼叫,并在ListView中显示这些调用。我想为传入和传出的录制文件显示单独的符号。我该如何分开呢?请提供解决方案。如果可能,提供源代码。 谢谢。

CallBroadCastReceiver.java

public class CallBroadcastReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        Log.d("CallRecorder", "CallBroadcastReceiver:onReceive got Intent: " + intent.toString());

        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            String numberToCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            Log.d("CallRecorder", "CallBroadcastReceiver intent has EXTRA_PHONE_NUMBER: " + numberToCall);
        }
        PhoneListener phoneListener = new PhoneListener(context);
        TelephonyManager telephony = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        Log.d("PhoneStateReceiver:onReceive", "set PhoneStateListener");
    }
}

PhoneListener.java

public class PhoneListener extends PhoneStateListener {
    private Context context;

    public PhoneListener(Context c) {
        Log.i("CallRecorder", "PhoneListener constructor");
        context = c;
    }

    public void onCallStateChanged(int state, String incomingNumber) {
        Log.d("CallRecorder", "PhoneListener::onCallStateChanged state:" + state + " incomingNumber:" + incomingNumber);

        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                Log.d("CallRecorder", "CALL_STATE_IDLE, stoping recording");
                Boolean stopped = context.stopService(new Intent(context, RecordService.class));
                Log.i("CallRecorder", "stopService for RecordService returned " + stopped);
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                Log.d("CallRecorder", "CALL_STATE_RINGING");
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Log.d("CallRecorder", "CALL_STATE_OFFHOOK starting recording");
                Intent callIntent = new Intent(context, RecordService.class);
                ComponentName name = context.startService(callIntent);
                if (null == name) {
                    Log.e("CallRecorder", "startService for RecordService returned null ComponentName");
                } else {
                    Log.i("CallRecorder", "startService returned " + name.flattenToString());
                }
                break;
        }
    }
}

CallLog.java

public class CallLoglist extends Activity {
    private final String TAG = "CallRecorder";
    private ListView fileList = null;
    //public static ArrayAdapter<String> fAdapter = null;
    private SeekBar seekbar;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    public static ImageButton pauseButton;
    public TextView startTimeField, endTimeField;
    AudioManager audioManager;
    public static final String STORAGE_LOCATIONN = Environment.getExternalStorageDirectory() + "/Android/data/com.callrecorder/favourites";
    Handler seekHandler = new Handler();
    Dialog seekDialog;
    private Utilities utils;
    long totalDuration, currentDuration;
    public static ImageView img;
    String[] dlist;
    String recordlist;
    private list fAdapter;
    ArrayList<String> alist;
    Cursor managedCursor;
    StringBuffer sb;
    public String name;
    public String number;
    File source;
    CallLoglist cc;
    public static boolean ss;
    String phNumber;
    public static int a;
    public static Editor ed;
    public static SharedPreferences pref;

    public static ArrayList<Boolean> arr = new ArrayList<Boolean>();

    private class CallItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            view.showContextMenu();

            CharSequence s = (CharSequence) parent.getItemAtPosition(position);
            Log.w(TAG, "CallLog just got an item clicked: " + s);

            //File f = new File(RecordService.DEFAULT_STORAGE_LOCATION + "/" + s.toString());


            /*boolean useMediaController = true;

            if (useMediaController) {
                Intent playIntent = new Intent(getApplicationContext(), CallPlayer.class); //Intent.ACTION_VIEW);
                Uri uri = Uri.fromFile(f);
                playIntent.setData(uri);
                startActivity(playIntent);

            } else {
                playFile(s.toString());
            }*/


        }
    }


    @SuppressLint("ShowToast")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        setContentView(R.layout.call_log);
        fileList = (ListView) findViewById(R.id.play_file_list);
        img = (ImageView) findViewById(R.id.image);
        Context context = getApplicationContext();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        utils = new Utilities();
        File dir = new File(RecordService.LOCATION);
        dlist = dir.list();
        alist = new ArrayList<String>(Arrays.asList(dlist));
        Log.v("fille", "recording file" + recordlist);
        fAdapter = new list(this, alist);
        fileList.setAdapter(fAdapter);
        fileList.setOnItemClickListener(new CallItemClickListener());
        registerForContextMenu(fileList);
        pref = getSharedPreferences("mm", MODE_PRIVATE);
        ed = pref.edit();
        /* ed.putString("rr", "R.drawable.arrow");
        ed.putString("re", "R.drawable.arroww");*/
        ed.commit();

        ////////////////

        /*String[] projection = new String[] {android.provider.CallLog.Calls.NUMBER, android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.CACHED_NAME};
         Uri contacts =  android.provider.CallLog.Calls.CONTENT_URI;

         Cursor managedCursor = managedQuery(contacts, projection, null, null, android.provider.CallLog.Calls.DATE + " ASC");
         getColumnData(managedCursor);

         }

          private void getColumnData(Cursor cur){
           try{
            if (cur.moveToFirst()) {

                long date;
                int nameColumn = cur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
                int numberColumn = cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
                int dateColumn = cur.getColumnIndex(android.provider.CallLog.Calls.DATE);

                System.out.println("Reading Call Details: ");
                do {
                    name = cur.getString(nameColumn);
                    number = cur.getString(numberColumn);
                    date = cur.getLong(dateColumn);
                    System.out.println(number + ":"+ new Date(date) +":"+name);


                } while (cur.moveToNext());
                }
               }

              finally{
                  cur.close();
              }*/
    }


    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater m = getMenuInflater();
        m.inflate(R.menu.nn, menu);

    }


    @SuppressLint({"ShowToast", "SdCardPath"})
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;
        recordlist = alist.get(index);

        //pp=dlist.
        switch (item.getItemId()) {

            case R.id.play:

                seekDialog = new Dialog(this);
                seekDialog.setTitle("play");
                seekDialog.setContentView(R.layout.dialog);
                startTimeField = (TextView) seekDialog.findViewById(R.id.textView1);
                endTimeField = (TextView) seekDialog.findViewById(R.id.textView2);
                pauseButton = (ImageButton) seekDialog.findViewById(R.id.imageButton2);
                seekbar = (SeekBar) seekDialog.findViewById(R.id.seek);
                seekDialog.show();

                Log.v("file", "" + index);
                if (mediaPlayer != null) {

                    mediaPlayer.release();
                }

            /*mediaPlayer=MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() 
                    + "/Android/data/com.callrecorder/recordings/" +pathh ));*/
                mediaPlayer = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/Android/data/com.callrecorder/recordings/" + recordlist));
                mediaPlayer.start();
                seekUpdation();
                totalDuration = mediaPlayer.getDuration();
                seekbar.setMax((int) totalDuration);

                pauseButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if (mediaPlayer.isPlaying()) {
                            mediaPlayer.pause();
                            pauseButton.setImageResource(R.drawable.play);
                            Toast.makeText(getApplicationContext(), "pause", 1000).show();
                        } else {
                            mediaPlayer.start();
                            pauseButton.setImageResource(R.drawable.pause);
                            Toast.makeText(getApplicationContext(), "play", 1000).show();
                        }

                    }
                });

                seekDialog.setOnDismissListener(new OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        // TODO Auto-generated method stub
                        mediaPlayer.release();

                    }
                });

                seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress,
                                                  boolean fromUser) {
                        // TODO Auto-generated method stub
                        if (fromUser) {
                            mediaPlayer.pause();
                            seekbar.setProgress(mediaPlayer.getCurrentPosition());
                            seekbar.setMax(mediaPlayer.getDuration());
                            mediaPlayer.seekTo(progress);
                            mediaPlayer.start();
                            pauseButton.setImageResource(R.drawable.pause);
                            seekUpdation();
                        }
                    }
                });

                break;
            case R.id.delete:
                Toast.makeText(getApplicationContext(), "delete", 1000).show();
                //new File(Environment.getExternalStorageDirectory()+"/callrecorder/" + pathh).delete();
                new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.callrecorder/recordings/" + recordlist).delete();
                alist.remove(index);
                alist.clear();
                fAdapter.notifyDataSetChanged();
                fAdapter.notifyDataSetInvalidated();

                break;

            case R.id.favorites:

                Toast.makeText(getApplicationContext(), "favouraties", 1000).show();
                source = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.callrecorder/recordings/" + recordlist);

                File dir = new File(STORAGE_LOCATIONN);

                if (!dir.exists()) {
                    try {

                        dir.mkdir();

                    } catch (Exception e) {
                        // TODO: handle exception

                    }
                }

                try {
                    InputStream in = new FileInputStream(source);
                    OutputStream out = new FileOutputStream(STORAGE_LOCATIONN + "/" + recordlist);

                    // Transfer bytes from in to out
                    byte[] buf = new byte[1024];
                    int len;

                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();


                } catch (Exception e) {
                    // TODO: handle exception
                    Log.v("copyyy", "errorrrrr");
                }
                source.delete();
                alist.remove(index);
                fAdapter.notifyDataSetChanged();
                fAdapter.notifyDataSetInvalidated();
                break;

            default:
        }
        return super.onContextItemSelected(item);
    }

    Runnable runn = new Runnable() {
        @Override
        public void run() {

            try {
                seekUpdation();
            } catch (Exception e) {
                // TODO: handle exception
            }

            try {
                totalDuration = mediaPlayer.getDuration();
                currentDuration = mediaPlayer.getCurrentPosition();
                // Displaying Total Duration time
                endTimeField.setText("" + utils.milliSecondsToTimer(totalDuration));
                // Displaying time completed playing
                startTimeField.setText("" + utils.milliSecondsToTimer(currentDuration));
                seekbar.setProgress((int) currentDuration); //move seek bar
                // Updating progress bar
                /* int progress = (int)(utils.getProgressPercentage(currentDuration,totalDuration));
                      //Log.d("Progress", ""+progress);
                      seekbar.setProgress(progress);*/
                // seekHandler.postDelayed(this, 100);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    };

    public void seekUpdation() {

        //seekbar.setProgress(mediaPlayer.getCurrentPosition());

        //mHandler.postDelayed(mUpdateTimeTask, 100); 
        seekHandler.postDelayed(runn, 1000);

    }

    public void onStart() {
        super.onStart();
        Log.i(TAG, "CallLog onStart");
    }

    public void onRestart() {
        super.onRestart();
        Log.i(TAG, "CallLog onRestart");
    }

           /*public void onResume()
             {
            super.onResume();
              //Log.i(TAG, "CallLog onResume about to load recording list again, does this work?");

               loadRecordingsFromDir();

                }*/

    @Override
    protected void onDestroy() {
                /*if(null!=mediaPlayer){
              mediaPlayer.release();
               }*/
        super.onDestroy();
        if (mediaPlayer != null) {
            //mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;

        }

    }


    ///////////////////////////////////////////


    private class list extends BaseAdapter {

        private CallLoglist callLog;
        private ArrayList<String> alist;

        public list(CallLoglist callLog, ArrayList<String> alist) {
            // TODO Auto-generated constructor stub
            this.callLog = callLog;
            this.alist = alist;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return alist.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View v, ViewGroup parent) {
            // TODO Auto-generated method stub


            LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.calllist, parent, false);
            TextView textView = (TextView) v.findViewById(R.id.text);
            ImageView imageView = (ImageView) v.findViewById(R.id.image);
            textView.setText(alist.get(position));
            String aa = pref.getString("rr", "");
            String dd = pref.getString("re", "");

            if (aa.equals("0")) {
                imageView.setImageResource(R.drawable.arrow);
            } else {
                imageView.setImageResource(R.drawable.arroww);
            }
            //imageView.setImageResource(R.drawable.arrow);

            //TextView text=(TextView)v.findViewById(R.id.namee);


            /*if(arr.get(position))
            {
                imageView.setImageResource(R.drawable.arrow);
            }
            else {
                imageView.setImageResource(R.drawable.arroww);
            }*/


            return v;
        }

    }
}

Recordservice.java

public class RecordService
        extends Service
        implements MediaRecorder.OnInfoListener, MediaRecorder.OnErrorListener {
    private static final String TAG = "CallRecorder";
    //public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/callrecorder";
    public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/Android/data/com.callrecorder/recordings";
    private static final int RECORDING_NOTIFICATION_ID = 1;
    private MediaRecorder recorder = null;
    private boolean isRecording = false;
    private String incoming;
    private Toast size;
    public static File recording = null;
    ;
    Intent intent;

    private File makeOutputFile(SharedPreferences prefs) {
        File dir = new File(DEFAULT_STORAGE_LOCATION);
        // test dir for existence and writeability
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                Log.e("CallRecorder", "RecordService:makeOutputFile unable to create directory " + dir + ": " + e);
                Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create the directory " + dir + " to store recordings: " + e, Toast.LENGTH_LONG);
                t.show();
                return null;
            }
        } else {
            if (!dir.canWrite()) {
                Log.e(TAG, "RecordService:makeOutputFile does not have write permission for directory: " + dir);
                Toast t = Toast.makeText(getApplicationContext(), "CallRecorder does not have write permission for the directory directory " + dir + " to store recordings", Toast.LENGTH_LONG);
                t.show();
                return null;
            }
        }
        String prefix = "cal";
        //String prefix= PhoneListener.incoming;

        int audiosource = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1"));
        //prefix += "-" + audiosource ;

        prefix += "" + PhoneListener.incoming;
        String suffix = "";
        int audioformat = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_FORMAT, "1"));
        switch (audioformat) {
            case MediaRecorder.OutputFormat.THREE_GPP:
                suffix = ".3gpp";
                break;
            case MediaRecorder.OutputFormat.MPEG_4:
                suffix = ".mpg";
                break;
            case MediaRecorder.OutputFormat.RAW_AMR:
                suffix = ".amr";
                break;
        }
        try {
            return File.createTempFile(prefix, suffix, dir);
        } catch (IOException e) {
            Log.e("CallRecorder", "RecordService:makeOutputFile unable to create temp file in " + dir + ": " + e);
            Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create temp file in " + dir + ": " + e, Toast.LENGTH_LONG);
            t.show();
            return null;
        }
    }

    public void onCreate() {
        super.onCreate();
        recorder = new MediaRecorder();
        Log.i("CallRecorder", "onCreate created MediaRecorder object");
    }

    @SuppressLint("ShowToast")
    public void onStart(Intent intent, int startId) {
        Log.i("CallRecorder", "RecordService:onStartCommand called while isRecording:" + isRecording);
        if (isRecording) return;
        Context c = getApplicationContext();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
        Boolean shouldRecord = prefs.getBoolean(Preferences.PREF_RECORD_CALLS, false);
        if (!shouldRecord) {
            Log.i("CallRecord", "RecordService:onStartCommand with PREF_RECORD_CALLS false, not recording");
            return;
        }
        int audiosource = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1"));
        int audioformat = Integer.parseInt(prefs.getString(Preferences.PREF_AUDIO_FORMAT, "1"));
        recording = makeOutputFile(prefs);
        if (recording == null) {
            recorder = null;
            return; //return 0;
        }
        Log.i("CallRecorder", "RecordService will config MediaRecorder with audiosource: " + audiosource + " audioformat: " + audioformat);
        try {
            recorder.reset();
            recorder.setAudioSource(audiosource);
            Log.d("CallRecorder", "set audiosource " + audiosource);
            recorder.setOutputFormat(audioformat);
            Log.d("CallRecorder", "set output " + audioformat);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            Log.d("CallRecorder", "set encoder default");
            recorder.setOutputFile(recording.getAbsolutePath());
            Log.d("CallRecorder", "set file:" + recording);
            recorder.setOnInfoListener(this);
            recorder.setOnErrorListener(this);
            try {
                recorder.prepare();
            } catch (java.io.IOException e) {
                Log.e("CallRecorder", "RecordService:onStart() IOException attempting recorder.prepare()\n");
                Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to start recording: " + e, Toast.LENGTH_LONG);
                t.show();
                recorder = null;
                return; //return 0; //START_STICKY;
            }
            Log.d("CallRecorder", "recorder.prepare() returned");
            recorder.start();
            isRecording = true;
            Log.i("CallRecorder", "recorder.start() returned");
            updateNotification(true);
        } catch (java.lang.Exception e) {
            Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to start recording: " + e, Toast.LENGTH_LONG);
            t.show();
            Log.e("CallRecorder", "RecordService:onStart caught unexpected exception", e);
            recorder = null;
        }
        return;
    }

    public void onDestroy() {
        super.onDestroy();
        if (null != recorder) {
            Log.i("CallRecorder", "RecordService:onDestroy calling recorder.release()");
            isRecording = false;
            recorder.release();
            long length = recording.length();
            length = length / 1024;
            Log.v("call", "pathh" + recording.getAbsolutePath() + length + "KB");
            if (length == 0) {
                Log.v("sizeeee", "settings");
                Toast.makeText(getApplicationContext(), "change the audio source settings", Toast.LENGTH_LONG).show();
                recording.delete();
                Log.v("file", "delete");
            }
            Toast t = Toast.makeText(getApplicationContext(), "CallRecorder finished recording call to" + recording, Toast.LENGTH_LONG);
            t.show();
        }
        updateNotification(false);
    }

    // methods to handle binding the service
    public IBinder onBind(Intent intent) {
        return null;
    }

    public boolean onUnbind(Intent intent) {
        return false;
    }

    public void onRebind(Intent intent) {
    }

    private void updateNotification(Boolean status) {
        Context c = getApplicationContext();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        if (status) {
            int icon = R.drawable.ic_launcher;
            CharSequence tickerText = "Recording call " + prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1");
            //CharSequence tickerText = "Recording call " + prefs.getString(Preferences.PREF_AUDIO_SOURCE, "1");
            long when = System.currentTimeMillis();
            //Notification notification = new Notification(icon, tickerText, when);
            Notification notification = new Notification(icon, tickerText, when);
            Context context = getApplicationContext();
            CharSequence contentTitle = "CallRecorder Status";
            CharSequence contentText = "Recording call...";
            Intent notificationIntent = new Intent(this, RecordService.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
            mNotificationManager.notify(RECORDING_NOTIFICATION_ID, notification);
        } else {
            mNotificationManager.cancel(RECORDING_NOTIFICATION_ID);
        }
    }

    // MediaRecorder.OnInfoListener
    public void onInfo(MediaRecorder mr, int what, int extra) {
        Log.i("CallRecorder", "RecordService got MediaRecorder onInfo callback with what: " + what + " extra: " + extra);
        isRecording = false;
    }

    // MediaRecorder.OnErrorListener
    public void onError(MediaRecorder mr, int what, int extra) {
        Log.e("CallRecorder", "RecordService got MediaRecorder onError callback with what: " + what + " extra: " + extra);
        isRecording = false;
        mr.release();
    }
}

1 个答案:

答案 0 :(得分:0)

您必须创建一个广播接收器。接收器检测呼叫是呼入还是呼出。在那里你可以录制你的电话。使用TelephonyManager类。并在清单中添加权限。

链接是源代码下载的基本描述: http://www.devlper.com/2010/08/detecting-incoming-and-outgoing-calls-in-android/

如果你正常工作,你就必须创建一个Dictionary(HashMap)。在那里你可以设置字典键来保存号码和传入或传出呼叫的键值。

熟悉自定义ListView以创建带有图像的ListView。 http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

创建2张图片,传入和传出。 Lopp通过你的字典并设置正确的图像。

迎接