简体   繁体   English

蓝牙许可对话框乘法

[英]Bluetooth Permission Dialog multiplication

I have encountered strange issue. 我遇到了奇怪的问题。 From Activity I request Bluetooth activation and 300s discoverability via intent: 在“活动”中,我通过意图请求蓝牙激活和300s可发现性:

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);                        
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

I use it no matter if the Bluetooth is already activated or not. 无论蓝牙是否已激活,我都可以使用它。 By doing that, a dialog permission shows off like expected: 这样,对话框权限就会像预期的那样显示出来:

"Bluetooth permission request: An application on your phone is requesting permission to turn on Bluetooth and ..." “蓝牙许可请求:您手机上的应用程序正在请求许可以打开蓝牙并...”

But no matter if i put yes or no, the dialog persists to appear multiple times. 但是,无论我是否同意,对话框始终会多次出现。 I dont know why. 我不知道为什么。 My code: 我的代码:

public class Initial extends Activity {

 private Integer REQUEST_ENABLE_BT  = 1;
 private Integer REQUEST_ENABLE_DISCBT  = 2;
 private ListView listView;
 private  ArrayAdapter<String> mArrayAdapter;
 TextView editText;
 private Global global;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_initial);
    this.global= ((Global)this.getApplicationContext());
    editText = (TextView) findViewById(R.id.textView1);     
    global.setAdapter(BluetoothAdapter.getDefaultAdapter());
    if (global.getAdapter() == null) {
        // Device does not support Bluetooth
        editText.setText("Erro: Sistema não suporta Bluetooth!");
        finish();
    }
    listView = (ListView) findViewById(R.id.list);
    mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
    listView.setAdapter(mArrayAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.initial, menu);
    return true;
}

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first
    if(!global.getEstado()){
        if (!global.getAdapter().isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        else
            editText.setText("Bluetooth Ligado!");
        global.setReceiver(new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // When discovery finds a device
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // Get the BluetoothDevice object from the Intent
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // Add the name and address to an array adapter to show in a ListView
                    mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    Thread novocliente = new novoCliente(device);
                    novocliente.start();
                }
            }
        });
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(global.getReceiver(), filter); // Don't forget to unregister during onDestroy
        global.getAdapter().startDiscovery();
    }
    else{   
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
    }   
}

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == REQUEST_ENABLE_BT){
        switch(resultCode){
        case RESULT_OK:     editText.setText("Bluetooth Ligado!");break;
        case RESULT_CANCELED:   editText.setText("Impossivel ligar Bluetooth!");finish();break;
        }   
    }
    if(requestCode == REQUEST_ENABLE_DISCBT){
        switch(resultCode){
            case RESULT_CANCELED:   editText.setText("Bluetooth não Detetável!");break;
            default :   editText.setText("Bluetooth Detetável por "+resultCode+" segundos!");
                        Thread servidor = new ServerSocket();
                        servidor.start();
            break;
        }   
    }
}

@Override
public void onStop() {
    super.onStop();  // Always call the superclass method first
    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
    BluetoothAdapter.getDefaultAdapter().disable(); 
}

@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass method first
    unregisterReceiver(global.getReceiver()); // Don't forget to unregister during onDestroy    

}

} My variaable getEstado() is a boolean that indicates if the application will be server or client. }我的可变getEstado()是一个布尔值,指示应用程序是服务器还是客户端。 if is true it is server. 如果为true,则为服务器。 and it is in the else that is the problem. 问题就在其他方面。

Can anyone help me please? 谁能帮我吗?

Your code to enable is in onResume(). 您要启用的代码在onResume()中。 When the dialog is shown, your activity is paused, and when it is dismissed (either positively or negatively), your activity is resumed. 显示对话框时,您的活动被暂停,而被取消(肯定或否定)时,您的活动将恢复。 If the dialog is positive then it also will take a moment to enable the BT adaptor, so global.getAdapter().isEnabled() will still return false. 如果对话框是肯定的,则也将需要一点时间来启用BT适配器,因此global.getAdapter()。isEnabled()仍将返回false。 This is why you are getting the dialog repeatedly show. 这就是为什么您要反复显示对话框的原因。

To resolve this you need to either use a different trigger (why did you specificaly need to use onResume? Could you put it in onCreate), or you could possible store state. 要解决此问题,您需要使用其他触发器(为什么要专门使用onResume?您可以将其放在onCreate中),或者可以使用存储状态。 Something like: 就像是:

private boolean requestedEnable = false;

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first
    if(!global.getEstado()){
        if (!global.getAdapter().isEnabled()) {
            if(!requestedEnable){
                requestedEnable = true;
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
        else
            editText.setText("Bluetooth Ligado!");
        global.setReceiver(new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                // When discovery finds a device
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // Get the BluetoothDevice object from the Intent
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // Add the name and address to an array adapter to show in a ListView
                    mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    Thread novocliente = new novoCliente(device);
                    novocliente.start();
                }
            }
        });
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(global.getReceiver(), filter); // Don't forget to unregister during onDestroy
        global.getAdapter().startDiscovery();
    }
    else{   
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
    }   
}

I hope you find this helpful. 我希望你觉得这有帮助。

看一下蓝牙聊天示例,可能会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM