博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
后台服务运行示例
阅读量:6854 次
发布时间:2019-06-26

本文共 2631 字,大约阅读时间需要 8 分钟。

1、编写MainActivity.java类

package com.example.callstatuslintener;import android.os.Bundle;import android.app.Activity;import android.content.Intent;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //开启服务        Intent intent=new Intent(this, PhoneStatusService.class);        startService(intent);    }}
View Code

2、编写PhoneStatusService.java类

/** *  */package com.example.callstatuslintener;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager;/** * 长期后台运行的组件,如果用户不手动关闭,不会停止的 * * 2013-12-6 */public class PhoneStatusService extends Service {    /* (non-Javadoc)     * @see android.app.Service#onBind(android.content.Intent)     */    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate() {        // TODO Auto-generated method stub        super.onCreate();        System.out.println("服务被创建了");        //监视用户电话状态的变化        //电话管理器 电话管理服务        TelephonyManager tm=(TelephonyManager) getSystemService(TELEPHONY_SERVICE);        //监听手机的通话状态的变化        tm.listen(new MyPhoneStatusLinstener(), PhoneStateListener.LISTEN_CALL_STATE);    }    private class MyPhoneStatusLinstener extends PhoneStateListener{        @Override        public void onCallStateChanged(int state, String incomingNumber) {                        switch (state) {            case TelephonyManager.CALL_STATE_IDLE: //空闲状态,没有通话没有响铃                                break;            case TelephonyManager.CALL_STATE_RINGING:    //响铃状态                System.out.println("发现来电号码:"+incomingNumber);                if ("5566".equals(incomingNumber)) {                    System.out.println("挂断电话");                }                                break;            case TelephonyManager.CALL_STATE_OFFHOOK:    //通话状态                break;            }            super.onCallStateChanged(state, incomingNumber);        }            }    @Override    public void onDestroy() {        // TODO Auto-generated method stub        super.onDestroy();        System.out.println("服务被销毁了……");    }    }
View Code

3、注册服务AndroidManifest.xml

View Code

转载于:https://www.cnblogs.com/hyzhou/p/3461586.html

你可能感兴趣的文章