我正在制作一个应用程序,需要在 Android 手机上有来电时运行。我希望我的应用程序仅监听传入调用并在后台运行其自己的 Activity
。实际上,我正在制作一个应用程序,其工作原理就像有来电时一样,然后是 LED在 Arduino 板上闪烁。
最佳答案
我认为 Chapter 12. Telephone Applications 在 Android Cookbook应该会有所帮助:
The short version, however, is that you need to listen to a broadcast message indicating that the phone state has change. To do that, you subclass
BroadcastReceiver
and add some code in your manifest to capture the event.
文件 AndroidManifest.xml:
<application android:icon="@drawable/icon" android:label="Incoming Call Interceptor">
<receiver android:name="IncomingCallInterceptor">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
文件IncomingCallInterceptor.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class IncomingCallInterceptor extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String msg = "Phone state changed to " + state;
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
msg += ". Incoming number is " + incomingNumber;
// TODO This would be a good place to "Do something when the phone rings" ;-)
}
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
我链接到的页面提供了有关其实际工作原理以及您可以检测到的其他内容的更多信息(例如用户何时接听或拒绝调用)。所以请务必阅读它。
关于android - Android 手机上的电话铃声响起时在后台启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11578562/