监听手机状态变化 - Android

2023-12-03

我目前正在尝试创建一个简单的应用程序,记录您拨打电话的分钟数,然后在接近空闲时间时向您发出警告。

此时,我创建了一个名为 CallService.java 的服务,每当用户呼叫他人时都会调用该服务。该服务仅记录呼叫的开始时间和呼叫的结束时间。该服务是使用名为 OutgoingCallReciever.Java 的类启动的。该类只是等待用户呼叫某人,然后启动 CallService。

我现在尝试在用户电话未呼叫某人时停止 CallService。即(电话状态空闲、摘机或其他人正在呼叫用户)但我不知道该怎么做(我是 Java/Android 新手)。我是否使用 PhoneStateListener 的 onCallStateChanged 方法? (我不确定如何使用它..)

希望您能帮忙!

课程如下:

MainActivity.java

package com.fouadalnoor.callcounter;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.telephony.TelephonyManager;
import android.telephony.PhoneStateListener;

public class MainActivity extends Activity {

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

        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        PhoneStateListener ps =(PhoneStateListener) getSystemService(TELEPHONY_SERVICE);

         Toast.makeText(this, "Phone State = " + tm.getCallState() , Toast.LENGTH_LONG).show();


        CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if(isChecked){
                        stopService (new Intent(buttonView.getContext(),CallService.class));
                    }
                }
            });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

OutgoingCallReciever.java

package com.fouadalnoor.callcounter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class OutgoingCallReciever extends BroadcastReceiver {


     @Override
        public void onReceive(Context context, Intent intent) {
          context.startService(new Intent(context, CallService.class));
     }

}

呼叫服务.java

package com.fouadalnoor.callcounter;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.lang.String;


public class CallService extends Service {

    public long startTime,endTime, totalTime;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

        @Override
        public void onDestroy() {

            Toast.makeText(this, "Call Service stopped", Toast.LENGTH_LONG).show(); 

            endTime = System.currentTimeMillis()/1000;
            Toast.makeText(this, "endTime = " + endTime, Toast.LENGTH_LONG).show();
            totalTime =  endTime-startTime; 
            Toast.makeText(this, "totalTime = " + totalTime , Toast.LENGTH_LONG).show();

        }

        @Override
        public void onStart(Intent intent, int startid) {
            Toast.makeText(this, "Call Service started by user.", Toast.LENGTH_LONG).show();

            startTime = System.currentTimeMillis()/1000;
            Toast.makeText(this, "startTime = "+ startTime, Toast.LENGTH_LONG).show();
        }


}

是的,你需要使用 onCallStateChanged method.

把这行放在你的onCreate()方法,它将初始化对象TelephonyManager并会为你设置监听器。

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
ListenToPhoneState listener = new ListenToPhoneState()
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

内部类的类定义ListenToPhoneState会看起来像这样,

    private class ListenToPhoneState extends PhoneStateListener {

        boolean callEnded=false;
        public void onCallStateChanged(int state, String incomingNumber) {
            
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                UTILS.Log_e("State changed: " , state+"Idle");


                if(callEnded)
                {
                    //you will be here at **STEP 4**
                    //you should stop service again over here
                }
                  else
                  {
                    //you will be here at **STEP 1**
                 //stop your service over here,
                    //i.e. stopService (new Intent(`your_context`,`CallService.class`));
                    //NOTE: `your_context` with appropriate context and `CallService.class` with appropriate class name of your service which you want to stop.

                  }

                
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                UTILS.Log_e("State changed: " , state+"Offhook");
                    //you will be here at **STEP 3**
                 // you will be here when you cut call
                callEnded=true;
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                UTILS.Log_e("State changed: " , state+"Ringing");
                    //you will be here at **STEP 2**
                
                break;
                

            default:
                break;
            }
        }

    }

解释:通话时,您的听者将经历以下状态,

Step 1: TelephonyManager.CALL_STATE_IDLE

最初您的通话状态将处于空闲状态,这就是变量的原因callEnded将会有价值false.

Step 2: TelephonyManager.CALL_STATE_RINGING

现在您正在等待接听者接听您的电话

Step 3: TelephonyManager.CALL_STATE_OFFHOOK

你挂断电话

Step 4: TelephonyManager.CALL_STATE_IDLE

又闲了

NOTE:如果您不想知道通话何时结束以及结束通话后应该做什么,那么只需删除callEnded变量并在您进入以下块时停止服务TelephonyManager.CALL_STATE_IDLE

我希望它会有所帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

监听手机状态变化 - Android 的相关文章

随机推荐