Java 无法从类开始意图 startActivityForResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16185694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:39:44  来源:igfitidea点击:

can't start intent startActivityForResult from class

javaandroid

提问by anze87

I will be very happy if someone can help me, because I'm new at object programming. My problem is: I'm writting some app with bluetooth communication. I wrote all methods and successfully connect and transfer data between devices in MainActivity.class. I have also one SearchActivity.classwhich shows all devices in range on List, so user can pick one. Device is then passed through Intent to MainActivity, where connection starts. But because of nature of my app I must created separate class, just for Bluetooth communication called BluetoothService.class. I moved all methods for Bluetooth and other stuff to BluetoothService.class.Now I even can't compile my project, because I get error at creating Intent for SearchActivity, I also get error startActivityForResult and onActivityResult methods.

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

First error is: The constructor Intent(BluetoothService, Class) is undefined

第一个错误是:构造函数 Intent(BluetoothService, Class) 未定义

Second error: The method startActivityForResult(Intent, int) is undefined for the type BluetoothService

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

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

When I was calling method startConnection()from MainActivity everything worked, but now I it doesn't. I think the problem is, that I can't create new Activity from non-activity class.

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

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

下一个错误出现在 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();
    }

Please, tell me how can I solve this. If you need more info or code tell me. Thanks.

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

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

}

In MainActivity I am doing:

在 MainActivity 我正在做:

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

Constructor in BluetoothService is:

BluetoothService 中的构造函数是:

 public BluetoothService(Context context) {

    }

connect method:

连接方法:

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

采纳答案by bugraoral

Your BluettoothServiceclass is not a context and to initialise an Intent you need a context.So try creating your class like this:

你的BluettoothService类不是一个上下文,初始化一个 Intent 你需要一个上下文。所以尝试像这样创建你的类:

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


}

And you can create the BluettoothServiceclass this way from any activity:

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

BluettoothService bluetooth=new BluettoothService(this);

Edit:

编辑:

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

回答by Blackbelt

You can't use thisof a Service to start an ActivityForResult

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

回答by VincentLamoute

You should to specify the @overridefor the onActivityResult().

您应该@overrideonActivityResult().

Your code should to be put into a class who extends 'activity' (android.app.Activity). It's for that you have also this :

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

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

This cannot be resolved because your class don't extends 'Activity'

这无法解决,因为您的课程没有扩展“活动”

回答by Sharad Mhaske

//create this class that hold application context.

//创建这个保存应用程序上下文的类。

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

//use this class getAppcontext() to get context in non-activity class.

//使用此类 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              
    } 


}