操作系统会在某些事件发生时广播它们。例如。接收短信,电话状态(发送,接收)。通过阅读您的帖子,我认为您应该使用广播接收器注册您的应用程序。这是一个示例代码。
public class PhoneCallState extends BroadcastReceiver
{
static long start_time, end_time;
@Override
public void onReceive(Context context, Intent intent)
{
final Bundle extras = intent.getExtras();
if(intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED))
{
final String state = extras.getString(TelephonyManager.EXTRA_STATE);
if ("RINGING".equals(state))
{
Toast.makeText(context, "Ringing", Toast.LENGTH_LONG).show();
}
if ("OFFHOOK".equals(state))
{
start_time = System.currentTimeMillis();
Toast.makeText(context, "Off", Toast.LENGTH_LONG).show();
}
if ("IDLE".equals(state))
{
end_time = System.currentTimeMillis();
long duration = (end_time - start_time) /1000;
Toast.makeText(context, "Duration : " + duration, Toast.LENGTH_LONG).show();
}
}
}
并在清单文件中注册您的接收器。
<receiver android:name=".PhoneCallState">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
}
最后不要伪造添加 PHONE_STATE 权限。
<uses-permission android:name="android.permission.READ_PHONE_STATE" />