マツリさんの日記

androidプログラミング初心者の奮闘日記です。たまに統計学もしてます。

PhoneStateListenerの作成 01

 android studio 2.3がリリースされました。

 Cameraアプリは難しいので、PhoneStateListenerを使ったアプリの作成に移ります。

 まだまだ未完成ですが、一歩進めたのでMainActivityを載せておきます。

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

// TelephonyManagerインスタンスを生成
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}

public PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
phoneCallEvent(state, incomingNumber);
}
};

// 通話状態に応じて、Toastを表示する
private void phoneCallEvent(int state, String incomingNumber) {
switch (state) {
// 着信時の表示内容
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(this, "着信中!" + incomingNumber, Toast.LENGTH_LONG).show();
break;
// 通話中の表示内容
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(this, "通話中!" + incomingNumber, Toast.LENGTH_LONG).show();
break;
}
}
}

 要するに、端末に着信が入った時と、端末が通話中の時にToast表示されるという単純な仕組みです。

 当然、通話状態などの端末情報にアクセスするために、マニフェストをこのように書き換えます。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ma2ri.telephonecontrol">

<!-- 電話番号、通話の状態などの端末情報を取得するためのパーミッション -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.example.ma2ri.telephonecontrol.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 着信などを制御するBroadcastReceiver
<receiver android:name="com.example.ma2ri.telephonecontrol.MainActivity$InComingCall">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver> -->

</application>

</manifest>

 マニフェストの最後にBroadcastReceiverのコメントアウトがありますが、気にしないで下さい。まだまだ試行錯誤中です。

 ただ、この状態だと、待ち受けの状態にならないんです。そこを次に修正したいと思います。