通往Android的神奇之旅之service监听电话状态

service作为Android四大组件之一注意创建类之后需要在mainfest文件中注册

<service android:name=".service.MyServiceForPhoneState"/>

另外监听电话状态也是需要申请系统权限的

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

service类,负责描述具体的service服务内容

package com.example.jack.servicetest.service;


/**
 * 监听通话状态
 */

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyServiceForPhoneState extends Service{

    private final String TAG = "MyServiceForPhoneState";

    @Nullable
    //这个onBind方法是必须重写的
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //service生命周期方法,oncreat、onstartcommand、ondestory
//    创建service
    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG,"创建");
    }

    //    service运行中
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "运行");
//获得service的具体服务内容,尽量不要把具体的东西写到生命周期方法中
        getService();
        return super.onStartCommand(intent, flags, startId);
    }

    private void getService() {
    //获得telephone管理器,通过获得系统服务,指定telephone_service
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        //给telephone添加监听器,并指定监听内容
        tm.listen(new MyPhoneStateListener(),PhoneStateListener.LISTEN_CALL_STATE);
    }
//自定义监听器,继承电话状态监听器
    class MyPhoneStateListener extends PhoneStateListener{
        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            super.onCallStateChanged(state, phoneNumber);

            switch (state){
//                电话空闲
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.i(TAG,"电话空闲");
                    break;
//                    正在响铃
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.i(TAG,"正在响铃");
                    break;
//                    正在通话
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.i(TAG,"电话通话");
                    break;
            }
        }
    }

    //    service销毁
    @Override
    public void onDestroy() {

        Log.i(TAG,"销毁");
        super.onDestroy();
    }


}
package com.example.jack.servicetest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.jack.servicetest.service.MyServiceForPhoneState;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        启动Service
        startService(new Intent(this,MyServiceForPhoneState.class));
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_42428357/article/details/82562238
今日推荐