注册一个服务获取来电号码

虽然简单,独扣文档收获还是不小~


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));






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值