检查未接来电

时间:2014-04-16 14:42:17

标签: android android-intent

我找到了这段代码来检查我是否有未接来电:

String[] selection = { CallLog.Calls.CACHED_NAME,
            CallLog.Calls.CACHED_NUMBER_LABEL, CallLog.Calls.TYPE };
String where = CallLog.Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE
                + " AND " + CallLog.Calls.NEW + "=1";
Cursor c = this.getContentResolver().query(CallLog.Calls.CONTENT_URI,
                selection, where, null, null);
c.moveToFirst();
if (c.getCount() >= 0) {
    mIntent.putExtra(MainActivity.PARAM_STATUS, MainActivity.STATUS_MISSCALL);
    sendBroadcast(mIntent);
}

我需要知道在哪里放置这段代码,因为我需要它连续执行...想法是执行此操作,如果有任何未接来电,代码会向MainActivity发送消息。也许是一项新活动?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我自己找到了答案。

我以这种方式使用了一个睡眠时间为1000毫秒的线程:

final Handler mhandler = new Handler();

final Runnable r = new Runnable() {
  public void run() {
    mhandler.postDelayed(this, 1000);
  }
};

Thread missedCall = new Thread() {
  @Override
  public void run() {
    try {
      while (true) {
        int a = missCall();
        if (a > 0) {
          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              mArrayAdapter.add("Missed Call...");
            }
          });
        }
        sleep(1000);
        mhandler.post(r);
      } 
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
  }
};
missedCall.start();

我定义missCall就像这样:

public int missCall() {
        String[] selection = { CallLog.Calls.CACHED_NAME,
                CallLog.Calls.CACHED_NUMBER_LABEL,
                CallLog.Calls.TYPE };
        String where = CallLog.Calls.TYPE + "="
                + CallLog.Calls.MISSED_TYPE + " AND "
                + CallLog.Calls.NEW + "=1";
        Cursor c = this.getContentResolver().query(
                CallLog.Calls.CONTENT_URI, selection, where,
                null, null);
        c.moveToFirst();
        return c.getCount();
    }

我不知道这是否是最好的方法,但它对我有用。