当前位置: 首页 > 知识库问答 >
问题:

我正在尝试使用JAVA在Android Studio上启用和禁用蓝牙;但startActivityForResult已被弃用。我能做什么?[副本]

东方志尚
2023-03-14

我想授予从Android Studio启用和禁用蓝牙的权限。我还假装使用蓝牙的其他功能作为设备列表,并连接到以前的pared设备等等。

由于starActivityForResult已被弃用,我很难用午餐来吃弹出式活动,该活动要求用户提供折扣。

这是我的货单

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.bluetoothonofftest"
    tools:ignore="CoarseFineLocation">

    <!-- Request legacy Bluetooth permissions on older devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH"
        android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
        android:maxSdkVersion="30"
        tools:ignore="CoarseFineLocation" />

    <!-- Needed only if your app looks for Bluetooth devices.
         If your app doesn't use Bluetooth scan results to derive physical
         location information, you can strongly assert that your app
         doesn't derive physical location. -->
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

    <!-- Needed only if your app makes the device discoverable to Bluetooth
         devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

    <!-- Needed only if your app communicates with already-paired Bluetooth
         devices. -->
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

    <!-- Needed only if your app uses Bluetooth scan results to derive physical location. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <uses-feature android:name="android.hardware.bluetooth" android:required="true"/>

    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BlUetoothTest">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>   

这是我的躁动

package com.example.bluetoothexamples;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;

    TextView mStatusBlueTv;
    TextView mPairedTv;

    ImageView mBlueIv;

    Button mOnBtn;
    Button mOffBtn;
    Button mDiscoverBtn;
    Button mPairedBtn;

    BluetoothAdapter mBlueAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
        mPairedTv = findViewById(R.id.pairedTv);

        mBlueIv = findViewById(R.id.bluetoothIv);

        mOnBtn = findViewById(R.id.onBtn);
        mOffBtn = findViewById(R.id.offBtn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.pairedBtn);

        // Adapter
        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Check if bluetooth is available or not
        if (mBlueAdapter == null) {
            mStatusBlueTv.setText("Bluetooth is NOT Available");
        } else {
            mStatusBlueTv.setText("Bluetooth is Available");

            // Set image according to bluetooth status (on/off)
            if (mBlueAdapter.isEnabled()) {
                mBlueIv.setImageResource(R.drawable.ic_action_on);
            } else {
                mBlueIv.setImageResource(R.drawable.ic_action_off);
            }

            mOnBtn.setOnClickListener(this);          // Turn on Bluetooth btn click
            mDiscoverBtn.setOnClickListener(this);    // Discover bluetooth btn click
            mOffBtn.setOnClickListener(this);         // Turn off Bluetooth btn click
            mPairedBtn.setOnClickListener(this);      // Get Paired devices button click
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            // Turn on Bluetooth btn click
            case R.id.onBtn:

                if (!mBlueAdapter.isEnabled()) {
                   // showToast("Turning On Bluetooth...");

//                    if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
//                    } else {
//                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
//                    }


                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    // Intent to On Bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, REQUEST_ENABLE_BT);
                }
                else {
                    showToast("Bluetooth is already on");
                }

            break;

            // Discover bluetooth btn click
            case R.id.discoverableBtn:

                if (!mBlueAdapter.isDiscovering()){
                    showToast("Making Your Device Discoverable");
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    startActivityForResult(intent ,REQUEST_DISCOVER_BT);
                }

            break;

            // Turn off Bluetooth btn click
            case R.id.offBtn:

                if (mBlueAdapter.isEnabled()) {
                    mBlueAdapter.disable();
                    showToast("Turning Bluetooth Off");
                    mBlueIv.setImageResource(R.drawable.ic_action_off);
                }
                else {
                    showToast("Bluetooth is already off");
                }

             break;
                // Get Paired devices button click
            case R.id.pairedBtn:

                if (mBlueAdapter.isEnabled()) {
                    mPairedTv.setText("Paired Devices");
                    Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
                    for (BluetoothDevice device: devices){
                        mPairedTv.append("\nDevice: " + device.getName() + ", " + device);
                    }
                }
                else {
                    //bluetooth is off so can't get paired devices
                    showToast("Turn ON Bluetooth to get paired devices");
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                showToast("Permission Granted");
            }
            else {
                showToast("Permission Denied");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case REQUEST_ENABLE_BT:

                if (resultCode == RESULT_OK) {
                    // Bluetooth is on
                    mBlueIv.setImageResource(R.drawable.ic_action_on);
                    showToast("Bluetooth is on");
                }
                else {
                    showToast("Failed to connect to bluetooth");
                }

            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Toast message function
    private void showToast (String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

这是我的XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

<!--    Display whether bluetooth is available or not-->
    <TextView
        android:id="@+id/statusBluetoothTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAlignment="center"
        android:textSize="20sp"
        android:textColor="#000" />

<!--    Bluetooth icon-->
    <ImageView
        android:id="@+id/bluetoothIv"
        android:layout_width="100dp"
        android:layout_height="100dp" />

<!--    on Button-->
    <Button
        android:id="@+id/onBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn On"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    off Button-->
    <Button
        android:id="@+id/offBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn Off"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    Discoverable button-->
    <Button
        android:id="@+id/discoverableBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Discoverable"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    Get list of paired devices button-->
    <Button
        android:id="@+id/pairedBtn"
        android:minWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Paired Devices"
        style="@style/Base.Widget.AppCompat.Button.Colored" />

<!--    Show paired devices here-->
    <TextView
        android:id="@+id/pairedTv"
        android:minWidth="200dp"
        android:text=""
        android:textColor="#000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

共有1个答案

公羊玉泽
2023-03-14

目前推荐的方法是使用ActivityResultLauncher来获得如下结果:

ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
             if (result.getResultCode() == Activity.RESULT_OK) {
                 Log.e("Activity result","OK");
                 // There are no request codes
                Intent data = result.getData();
            }
        });

所以就这样称呼它:

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activityResultLauncher.launch(intent);

对于您的情况,假设其他一切正常,您将更新为以下内容:

package com.example.bluetoothexamples;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVER_BT = 1;

    TextView mStatusBlueTv;
    TextView mPairedTv;

    ImageView mBlueIv;

    Button mOnBtn;
    Button mOffBtn;
    Button mDiscoverBtn;
    Button mPairedBtn;

    BluetoothAdapter mBlueAdapter;
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                 if (result.getResultCode() == Activity.RESULT_OK) {
                     Log.e("Activity result","OK");
                     // There are no request codes
                    Intent data = result.getData();
                }
            });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
        mPairedTv = findViewById(R.id.pairedTv);

        mBlueIv = findViewById(R.id.bluetoothIv);

        mOnBtn = findViewById(R.id.onBtn);
        mOffBtn = findViewById(R.id.offBtn);
        mDiscoverBtn = findViewById(R.id.discoverableBtn);
        mPairedBtn = findViewById(R.id.pairedBtn);

        // Adapter
        mBlueAdapter = BluetoothAdapter.getDefaultAdapter();

        //Check if bluetooth is available or not
        if (mBlueAdapter == null) {
            mStatusBlueTv.setText("Bluetooth is NOT Available");
        } else {
            mStatusBlueTv.setText("Bluetooth is Available");

            // Set image according to bluetooth status (on/off)
            if (mBlueAdapter.isEnabled()) {
                mBlueIv.setImageResource(R.drawable.ic_action_on);
            } else {
                mBlueIv.setImageResource(R.drawable.ic_action_off);
            }

            mOnBtn.setOnClickListener(this);          // Turn on Bluetooth btn click
            mDiscoverBtn.setOnClickListener(this);    // Discover bluetooth btn click
            mOffBtn.setOnClickListener(this);         // Turn off Bluetooth btn click
            mPairedBtn.setOnClickListener(this);      // Get Paired devices button click
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            // Turn on Bluetooth btn click
            case R.id.onBtn:

                if (!mBlueAdapter.isEnabled()) {
                   // showToast("Turning On Bluetooth...");

//                    if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
//                    } else {
//                        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
//                    }


                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},1);
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    // Intent to On Bluetooth
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  //  startActivityForResult(intent, REQUEST_ENABLE_BT);
                      
        activityResultLauncher.launch(intent);
                }
                else {
                    showToast("Bluetooth is already on");
                }

            break;

            // Discover bluetooth btn click
            case R.id.discoverableBtn:

                if (!mBlueAdapter.isDiscovering()){
                    showToast("Making Your Device Discoverable");
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    //startActivityForResult(intent ,REQUEST_DISCOVER_BT);
                     activityResultLauncher.launch(intent);
                }

            break;

            // Turn off Bluetooth btn click
            case R.id.offBtn:

                if (mBlueAdapter.isEnabled()) {
                    mBlueAdapter.disable();
                    showToast("Turning Bluetooth Off");
                    mBlueIv.setImageResource(R.drawable.ic_action_off);
                }
                else {
                    showToast("Bluetooth is already off");
                }

             break;
                // Get Paired devices button click
            case R.id.pairedBtn:

                if (mBlueAdapter.isEnabled()) {
                    mPairedTv.setText("Paired Devices");
                    Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
                    for (BluetoothDevice device: devices){
                        mPairedTv.append("\nDevice: " + device.getName() + ", " + device);
                    }
                }
                else {
                    //bluetooth is off so can't get paired devices
                    showToast("Turn ON Bluetooth to get paired devices");
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                showToast("Permission Granted");
            }
            else {
                showToast("Permission Denied");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode){
            case REQUEST_ENABLE_BT:

                if (resultCode == RESULT_OK) {
                    // Bluetooth is on
                    mBlueIv.setImageResource(R.drawable.ic_action_on);
                    showToast("Bluetooth is on");
                }
                else {
                    showToast("Failed to connect to bluetooth");
                }

            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Toast message function
    private void showToast (String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

对于java

   ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Log.e("Activity result", "OK");
                        // There are no request codes
                        Intent data = result.getData();
                    }
                }
            }
            );
 类似资料:
  • 我是android新手。只是尝试制作一个webview应用程序,而不是实际的移动应用程序,然后我会将我的flask应用程序用作移动应用程序。 该应用程序运行正常,没有任何问题,但startActivityForResult给了我一个警告。以下是代码:

  • 我是android新手。只是试着制作一个webview应用程序而不是一个实际的移动应用程序,然后我会将我的flask应用程序用作一个移动应用程序。 该应用程序运行良好,没有任何问题,但start ActivityForResult正在给我一个警告。代码如下: 这是onActivityResult,我仍然无法让它工作。。。

  • 我正在尝试使用ajax php和jquery上传图像,我在这里做错了什么。应在不刷新页面的情况下上载图像。我试过上面的代码。如果你看到任何问题,请帮忙!! 问题是我想将上传的文件移动到上传文件夹并将图像名称作为BLOB插入数据库。

  • 问题内容: 我在jquery文档中看到live()已被弃用。有直接替换功能吗? 问题答案: ;替换。 ;替换。 ;替换。

  • 我有一个应用程序,可以管理设备的wifi和蓝牙状态。为此,它接收到一条带有状态的消息,并且该状态是否应该被强制。然后应用状态并保存两个值。 例如:我发送消息禁用wifi并强制使用。然后我关闭无线网络,拯救国家,这是被迫的。此外,我有一个BroadcastRecector,监听无线网络状态的变化,如果收到,它首先检查是否启用了无线网络,如果这是好的。这就像一个魅力:公共类无线状态接收器扩展了广播接收