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

无法从类开始intent startActivityForResult

方承弼
2023-03-14

如果有人能帮助我,我会非常高兴,因为我是对象编程的新手。我的问题是:我正在编写一些带有蓝牙通信的应用程序。我编写了所有方法并在MainActivity.class.中成功地在设备之间连接和传输数据我也有一个SearchActivity.class它显示了List上范围内的所有设备,因此用户可以选择一个。然后将设备通过Intent传递到Main Active,从那里开始连接。但由于我的应用程序的性质,我必须创建单独的类,只是为了称为蓝牙通信BluetoothService.class.我将蓝牙和其他东西的所有方法移动到BluetoothService.class.现在我甚至不能编译我的项目,因为我在创建Intent for SearchActive时出错,我也得到错误start ActivityForResult和onActivityResult方法。

第一个错误是:构造函数意图(BluetoothService,Class)未html" target="_blank">定义

第二个错误:BluetoothService类型的方法startActivityForResult(Intent,int)未定义

public void startConnection() {
    // Create an intent for SearchActivity 
    Intent intent = new Intent(this, SearchActivity.class);
    //start SearchActivity through intent and expect for result. 
    //The result is based on result code, which is REQUEST_DISCOVERY
    startActivityForResult(intent, REQUEST_DISCOVERY);              
}  

当我从MainActivity调用方法startConnection()时,一切都正常,但现在不行了。我认为问题是,我不能从非活动类中创建新的活动。

下一个错误在onActivityResult方法中:*RESULT_OK无法解析为变量*

//on ActivityResult method is called, when other activity returns result through intent!
//when user selected device in SearchActivity, result is passed through intent with //requestCode, resultCode (intent data + requestCode + resultCode)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode != REQUEST_DISCOVERY) {
    Log.d("Debug", ">>intent REQUEST_DISCOVERY failed!");
    return;
    }
    if (resultCode != RESULT_OK) {
    Log.d("Debug", ">>intent RESULT_OK failed!");
    return;
    }
    Log.d("Debug", ">>onActivityResult!");
    final BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

    Log.d(device.getName(), "Name of Selected Bluetoothdevice");


    new Thread () {
        public void run() {
        //call connect function with device argument
        connect(device);
        };
    }.start();
    }

请告诉我如何解决这个问题。如果你需要更多的信息或代码告诉我。谢了。

public class SearchActivity  extends ListActivity
{
    //name of LxDevices, that will be shown on search
    private String nameOfLxDevice = "DEBUG";

    private Handler handler = new Handler();
    /* Get Default Adapter */
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    /* Storage the BT devices */
    private List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
    /* Discovery is Finished */
    private volatile boolean discoveryFinished;


    /* Start search device */ 
    private Runnable discoveryWorker = new Runnable() {
        public void run() 
        {
            //To start discovering devices, simply call startDiscovery(). The process is asynchronous and the method will 
            //immediately return with a boolean indicating whether discovery has successfully started.
            mBluetoothAdapter.startDiscovery();
            Log.d("debug", ">>Starting Discovery");
            for (;;) 
            {
                if (discoveryFinished) 
                {
                    Log.d("debug", ">>Finished");
                    break;
                }
                try 
                {
                    Thread.sleep(100);
                } 
                catch (InterruptedException e){}
            }
        }
    }; 

    /* when discovery is finished, this will be called */
    //Your application must register a BroadcastReceiver for the ACTION_FOUND Intent in order to receive information about each device discovered.
    //For each device, the system will broadcast the ACTION_FOUND Intent. This Intent carries the extra fields EXTRA_DEVICE and EXTRA_CLASS,
    //containing a BluetoothDevice and a BluetoothClass, respectively

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            /* get the search results */
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);               
                //add it on List<BluetoothDevice>
                devices.add(device);
                //show found LxDevice on list
                showDevices();
            }           
        }
    };

    private BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent)  
        {
            /* unRegister Receiver */
            Log.d("debug", ">>unregisterReceiver");
            unregisterReceiver(mBroadcastReceiver);
            unregisterReceiver(this);
            discoveryFinished = true;
        }
    };

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        /* BT isEnable */
        if (!mBluetoothAdapter.isEnabled())
        {
            Log.w("debug", ">>BT is disable!");
            finish();
            return;
        }
        /* Register Receiver*/
        IntentFilter discoveryFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(discoveryReceiver, discoveryFilter);
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver, foundFilter);


        /* show a dialog "Scanning..." */ 
        SamplesUtils.indeterminate(SearchActivity.this, handler, "Scanning for LX devices..", discoveryWorker, new OnDismissListener() {
            public void onDismiss(DialogInterface dialog)
            {
                for (; mBluetoothAdapter.isDiscovering();) {
                    // Discovery is resource intensive.  Make sure it isn't going on when you attempt to connect and pass your message.
                    mBluetoothAdapter.cancelDiscovery();
                }
                discoveryFinished = true;
            }
        }, true); 
    }

    /* Show devices list */
    private void showDevices()
    {
        //Create a list of strings
        List<String> list = new ArrayList<String>();
        for (int i = 0, size = devices.size(); i < size; ++i) {
            StringBuilder b = new StringBuilder();
            BluetoothDevice d = devices.get(i);
            b.append(d.getName());
            b.append('\n');
            b.append(d.getAddress());
            String s = b.toString();
            list.add(s);
        }

        Log.d("debug", ">>showDevices");
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        handler.post(new Runnable() {
            public void run()
            {
                setListAdapter(adapter);
            }
        });
    }

    /* Select device */
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Log.d("debug", ">>Click device");
        Intent result = new Intent();
        result.putExtra(BluetoothDevice.EXTRA_DEVICE, devices.get(position));
        setResult(RESULT_OK, result);
        finish();
    }

}

在主活动中,我正在做:

// Initialize the BluetoothChatService to perform bluetooth connections
    mBluetoothService = new BluetoothService(this);

蓝牙服务中的构造函数是:

 public BluetoothService(Context context) {

    }

连接方法:

protected void connect(BluetoothDevice device) {
    try {
    //Create a Socket connection: need the server's UUID number of registered
    BluetoothSocket socket = null;
    socket = device.createRfcommSocketToServiceRecord(MY_UUID);         
    socket.connect();
        //Create temporary input and output stream
         InputStreamtmpIn=socket.getInputStream();                                                      
    OutputStream tmpOut = socket.getOutputStream();

    //for use purposes
    mmSocket = socket;
    mmOutStream = tmpOut;
    mmInStream = tmpIn;

    tmpOut.write("Device connected..".getBytes());

    //start Thread for receiving data over bluetooth
    //dataReceiveThread.start();

    } catch (IOException e) {
        Log.e("Colibri2BB BT", "", e);
    } 
}

共有3个答案

夹谷星剑
2023-03-14

您应该为onActivityResult()指定@over

你的代码应该放在一个扩展“活动”(android.app.Activity)的类中。为此,你还有这个:

Next error is in onActivityResult method: *RESULT_OK cannot be resolved to a variable*

无法解决此问题,因为您的课程未扩展“活动”

邴越彬
2023-03-14

您不能使用服务的来启动活动ForResult

韩峰
2023-03-14

您的类不是上下文,要初始化Intent,您需要一个context.So尝试这样创建您的类:

    public class BluettoothService{

    Activity activity;

    BluettoothService(Activity activity){
    this.activity=activity;
    }
    public void startConnection() {
    // Create an intent for SearchActivity 
    Intent intent = new Intent(activity, SearchActivity.class);
    //start SearchActivity through intent and expect for result. 
    //The result is based on result code, which is REQUEST_DISCOVERY
    activity.startActivityForResult(intent, REQUEST_DISCOVERY);              
    } 


}

您可以从任何活动中以这种方式创建< code>BluettoothService类:

BluettoothService bluetooth=new BluettoothService(this);

编辑:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != REQUEST_DISCOVERY) {
Log.d("Debug", ">>intent REQUEST_DISCOVERY failed!");
return;
}
if (resultCode != Activity.RESULT_OK) {
Log.d("Debug", ">>intent RESULT_OK failed!");
return;
}
Log.d("Debug", ">>onActivityResult!");
final BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

Log.d(device.getName(), "Name of Selected Bluetoothdevice");


new Thread () {
    public void run() {
    //call connect function with device argument
    connect(device);
    };
}.start();
}
 类似资料:
  • 我在做计算器(顺便说一句,我是个初学者)。我几乎完成了它,直到我需要格式化我的电脑,并且在第一次重新打开Android Studio之后,它才打开,但现在它没有打开,并且显示了这个例外: 失败:生成失败,出现异常。 哪里出了问题: 无法打开a4fwtlbt6cgvdv2n0389t2u6w的cp\U初始化重新映射类缓存(C:\Users\tambe.gradle\caches\6.1.1\scri

  • 当我在iReport 5.1.0中预览JasperReports的报告时,它执行得很好。它包含一个饼图,当我需要从jsp文件运行它时,问题就来了。 烧烤-1.5-beta1.jar commons-beanutils-1.8.2.jar Commons-Collections-3.2.1.jar commons-digester-2.1.jar commons-javaflow-20060411.

  • 问题内容: 美好的一天,我尝试从另一个开始新的活动。但是它总是崩溃。这是我的代码。这是ListView上的事件。 向清单清单添加了活动 错误消息是 所有以前的活动,我添加的活动都很好… StudentInfoActivity 问题答案: 代替 改成 例如,活动actOne = null;

  • 我正试图将HMS自动语音识别(ASR)添加到我的应用程序中。我已经实现了,但它需要GMS才能工作。 当前的HMS实现工作在安装HMS核心的非华为设备上,但不适用于我的Huawei Mediapad T5。 更新:经过@Shirley指出的一些修复后,ASR似乎可以在P30Lite上可靠地工作。但在旧的Mediapad T5上仍面临同样的问题。

  • 问题内容: 为什么这小段代码在第6行和第10行中给出非法的类型错误开始(用于循环)…。我找不到任何不匹配的花括号… 我已经实现了Stack类 问题答案: 您不能在类级别使用循环。将它们放入a 或a 另外在没有这样的构造函数。 它应该是 另一个问题 只需将其更改为

  • 注意:这大部分是Java特有的-需要语言特有的调用方法 如果没有获得Vertx对象,Vert.x做不了什么。 Vertx对象是 Vert.x 的控制中心,几乎可以做所有事,包括创建客户端和服务器,获取引用到事件总线(event bus)、 设置计时器等。 所以怎么获得Vertx实例? 如果已经嵌入了 Vert.x,然后只需创建一个实例,如下所示: Vertx vertx = Vertx.vertx