2013-04-24 33 views
1

如果有人能幫助我,我將非常高興,因爲我是對象編程的新手。我的問題是:我正在用藍牙通信寫一些應用程序。我編寫了所有方法,並在MainActivity.class中的設備之間成功連接和傳輸數據。我也有一個SearchActivity.class它顯示列表中範圍內的所有設備,所以用戶可以選擇一個。設備然後通過意圖傳遞到MainActivity,其中連接開始。但由於我的應用程序的性質,我必須創建單獨的類,僅用於藍牙通信,稱爲BluetoothService.class。我將藍牙和其他東西的所有方法移至BluetoothService.class。 現在我甚至無法編譯我的項目,因爲我在創建Intent for SearchActivity時出錯,我也收到錯誤startActivityForResult和onActivityResult方法。無法啓動intent startActivityForResult類

第一錯誤是:構造意圖(BluetoothService,類)是未定義

第二錯誤:方法startActivityForResult(意向,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);    
} 

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

} 

在MainActivity我做:

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

構造函數,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); 
    } 
} 
+0

您是否在SearchActivity中調用startDiscovery? – 2013-04-24 07:24:02

+0

您的BluettoothService類是否擴展Service?還必須顯示RESULT_OK屬於哪個類,比如SomeClass.RESULT_OK,如果RESULT_OK是靜態的。 – wrecker 2013-04-24 07:24:30

+0

是的,我在SearchActivity中調用startDiscovery。 – anze87 2013-04-24 07:27:45

回答

3

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


} 

而且你可以從任何活動創建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(); 
} 
+0

我創建了類BluetothService就像你說的,添加到構造函數this.context = context;我仍然在startActivityForResult(intent,REQUEST_DISCOVERY)上出錯; – anze87 2013-04-24 09:07:05

+0

ERORR是:方法startActivityForResult(Intent,int)未定義類型BluetoothService – anze87 2013-04-24 09:07:29

+0

對不起,我的壞!嘗試context.startActivityForResult(intent,REQUEST_DISCOVERY);如果失敗請讓我知道 – wrecker 2013-04-24 09:35:22

2

不能使用的this服務到聖藝術品ActivityForResult

+0

我需要使用什麼? – anze87 2013-04-24 07:21:43

0

您應該爲onActivityResult()指定@override

你的代碼應該放入一個擴展'activity'(android.app.Activity)的類中。 這對你也有這樣的:

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

這不能得到解決,因爲類不擴展「活動」

0

//創建這個類保持應用程序上下

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    
    } 


} 
+0

我也試過這個,但我仍然在startActivityForResult(intent,REQUEST_DISCVERY)上出錯。錯誤:方法startActivityForResult(Intent,int)未定義類型BluetoothService ...請幫助! – anze87 2013-04-24 09:35:21

+0

public class BluettoothService { static Context context = Application_Manager.getAppContext(); public void startConnection(){ Intent intent = new Intent(context,SearchActivity.class); context.startActivityForResult(intent,REQUEST_DISCOVERY); } } – 2013-04-24 09:38:15

+0

查看我在startactivity中所做的更改call-context.startActivityForResult(intent,REQUEST_DISCOVERY);希望這會解決您的問題 – 2013-04-24 09:38:43

相關問題