Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java can';t从课堂上开始意向startActivityForResult_Java_Android - Fatal编程技术网

Java can';t从课堂上开始意向startActivityForResult

Java can';t从课堂上开始意向startActivityForResult,java,android,Java,Android,如果有人能帮助我,我会非常高兴,因为我是对象编程新手。我的问题是:我正在写一些蓝牙通信的应用程序。我在MainActivity.class中编写了所有方法,并成功地在设备之间连接和传输数据。我还有一个SearchActivity.class,它显示列表中范围内的所有设备,所以用户可以选择一个。然后,设备通过意图传递到MainActivity,连接从这里开始。但由于我的应用程序的性质,我必须创建单独的类,只用于蓝牙通信,名为BluetoothService.class。我将Bluetooth和其他

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

第一个错误是:构造函数意图(BluetoothService,类)未定义

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

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

public class BluettoothService{

    static Context context=Application_Manager.getAppContext();
    public void startConnection() {
    Intent intent = new Intent(context, SearchActivity.class);
    context.startActivityForResult(intent, REQUEST_DISCOVERY);//change edited              
    } 


}
下一个错误在onActivityResult方法中:*结果\u确定无法解析为变量*

//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();
    }

}
BluetoothService中的构造函数是:

 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);
    } 
}

您不能使用服务的
来启动
ActivityForResult

您应该为
onActivityResult()指定
@覆盖

你的代码应该放在一个扩展“activity”(android.app.activity)的类中。 这是因为你也有这个:

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

无法解决此问题,因为您的类不扩展“活动”

您的
BlueToothService
类不是上下文,要初始化意图,您需要上下文。因此,请尝试按如下方式创建类:

    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);              
    } 


}
您可以通过以下方式从任何活动创建
BlueToothService
类:

BluettoothService bluetooth=new BluettoothService(this);
编辑:


//创建包含应用程序上下文的此类

public class Application_Manager extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        Application_Manager.context = getApplicationContext();

    }

    public static Context getAppContext() {
        return Application_Manager.context;
    }
}
//使用此类getAppcontext()获取非活动类中的上下文

public class BluettoothService{

    static Context context=Application_Manager.getAppContext();
    public void startConnection() {
    Intent intent = new Intent(context, SearchActivity.class);
    context.startActivityForResult(intent, REQUEST_DISCOVERY);//change edited              
    } 


}

您是否在SearchActivity中调用startDiscovery?您的BlueToothService类是否扩展了服务?当然,如果RESULT\u OK是静态的,那么还必须显示您的RESULT\u OK属于哪个类。是的,我在SearchActivity中调用startDiscovery。不,我的BluetoothService.class不扩展服务…现在我编辑为:公共类BluetoothService扩展服务,并添加BluetoothService.RESULTK\u OK,这两个错误消失了。现在我仍然只有第二个错误。我创建了类BluetothService,就像你说的,添加到构造函数this.context=context;我仍然在startActivityForResult(意图、请求和发现)上出错;ERORR是:类型BluetoothService抱歉,我的错!try context.startActivityForResult(意图、请求和发现);如果失败,请让我知道它再次失败…错误:方法startActivityForResult(Intent,int)对于类型ContextThank是未定义的。非常感谢,它可以工作…现在我只遇到了一个问题,当程序在finish()方法上退出SearchActivity时,它在ActivityResult方法上不连续,正如我在Debugger中看到的…我必须找出原因…也许你知道原因是什么?又是tnx!我也尝试过这个,但在startActivityForResult(intent,REQUEST\u disvery)中仍然出现错误;错误:类型BluetoothService的startActivityForResult(Intent,int)方法未定义…请提供帮助!公共类BluettoothService{static Context Context=Application_Manager.getAppContext();public void startConnection(){Intent Intent Intent=new Intent(Context,SearchActivity.class);Context.startActivityForResult(Intent,REQUEST_DISCOVERY);}查看我在startactivity调用上下文中所做的更改;希望这能解决您的问题,即context.startActivityForResult(intent,REQUEST\u DISCOVERY);但仍然有错误:方法startActivityForResult(Intent,int)未定义类型Contextcheck的上下文值是否为null。从哪里使用bluetoothservice类位于活动中。如果是,则将该活动的上下文传递给bluetooth类构造函数的构造函数,并使用该上下文启动活动thr bluetooth服务。
public class Application_Manager extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        Application_Manager.context = getApplicationContext();

    }

    public static Context getAppContext() {
        return Application_Manager.context;
    }
}
public class BluettoothService{

    static Context context=Application_Manager.getAppContext();
    public void startConnection() {
    Intent intent = new Intent(context, SearchActivity.class);
    context.startActivityForResult(intent, REQUEST_DISCOVERY);//change edited              
    } 


}