1

我在网上查看了许多关于如何将警报管理器设置为广播以获取系统事件的教程和问题(在我的情况下是蓝牙发现)。但是,由于某些我还不知道的原因,我未能实现这一目标。

我的接收器类如下:

公共类 MyBluetoothReceiver 扩展 BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Calendar call = Calendar.getInstance();
    call.setTimeInMillis(System.currentTimeMillis());
    Date date = call.getTime();

    Log.i("BlueTestm: ", "" + action);


    if(BluetoothDevice.ACTION_FOUND.equals(action)) 
    {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.i("\nDevice: ",  device.getName() + ", " + device + ", T: " + date.toLocaleString() );
        String t1 = "\nDevice: "+  device.getName() + ", " + device + ", T: " + date.toLocaleString();

        Toast.makeText(context, t1, Toast.LENGTH_SHORT).show();


    } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) 
    {
        String t2 = "Discovery Started";
        Log.i("BlueTest: ", "" + t2);

        Toast.makeText(context, t2, Toast.LENGTH_SHORT).show();

    } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
    {
        String t3 = "Discovery finished"; 
        Log.i("BlueTest: ", "" + t3);

        Toast.makeText(context, t3, Toast.LENGTH_SHORT).show();
    }   
}

}

我在我的主要活动中调用这个方法:

更新:

public void startAlert() {
    int i = Integer.parseInt("15");
    IntentFilter filter;

    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_UUID);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(blueReciver, filter);

    Intent intent = new Intent(this, MyBluetoothReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    long triggerAtTime = cal.getTimeInMillis()+ (i * 1000); // starts in 30 minutes
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), triggerAtTime, pendingIntent);

    //alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000),  pendingIntent);
    Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
}

我在这里尝试做的是每 15 秒进行一次蓝牙发现。更新代码后,现在警报工作正常,但我的蓝牙接收器仅第一次接收“动作”,然后每当警报触发接收器时,“动作”字符串在警报调用中返回 null。据我了解,该应用程序没有从第二次扫描中进行任何发现。实际上,在第一次通话后它根本没有进行任何扫描。到目前为止,我正试图找出为什么会发生这种情况。

任何帮助将不胜感激。谢谢。

4

0 回答 0