虽然简单,独扣文档收获还是不小~
service服务类:
package com.example.mobliesoft.service;
import com.example.mobliesoft.Activity.DB.AddressDao;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Switch;
import android.widget.Toast;
public class AttributionService extends Service {
private TelephonyManager tm;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
System.out.println("AttributionService");
tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
MyListener listener = new MyListener();
tm.listen(listener, listener.LISTEN_CALL_STATE);
}
class MyListener extends PhoneStateListener{
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
String address = AddressDao.getAddress(incomingNumber);
Toast.makeText(AttributionService.this, address, Toast.LENGTH_LONG).show();
System.out.println("有一个新电话 :"+incomingNumber);
System.out.println("归属地是 :"+address);
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
在AndroidManifest中添加权限以及注册服务。
<service android:name="com.example.mobliesoft.service.AttributionService"></service>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
开启服务:
startService(new Intent(this,AttributionService.class));