Unable to receive broadcast from Service - java

The issue I am having is in regards to receiving a broadcast from a service that is within an android library project.
Why am I unable to receive the broadcast? does it have to do with all the service/interface logic being in a seperate android library project?
Here is the broadcast from the service
broadcastReceivedMessage("THE TOPIC", "THE MESSAGE");
Here is the method within the service
private void broadcastReceivedMessage(final String topic, final String message) {
/* handler.post(new Runnable() {
#Override
public void run() {*/
Intent broadcastIntent = new Intent(CALLBACK_ACTION);
broadcastIntent.setAction(ON_MESSAGE_RECEIVED);
broadcastIntent.putExtra(TOPIC_STR, topic);
broadcastIntent.putExtra(MESSAGE_STR, message);
sendBroadcast(broadcastIntent);
/* }
});*/
}
Inside a class that implements many interfaces, this is where I am registering to listen for a specific intent filter.
#Override
public void connect(String address, int port) {
IntentFilter filter = new IntentFilter(MQTTService2.CALLBACK_ACTION);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(serviceActionReceiver, filter);
Bundle args = new Bundle();
args.putString(MQTTService2.BROKER_ADDR_STR, address);
args.putInt(MQTTService2.BROKER_PORT_INT, port);
startService(MQTTService2.ACTION_CONNECT, args);
}
Inside an Activity where I expect to receive a callback from the interfaces and get my broadcast
MQTTEventHandler mHandler = new MQTTEventHandler() {
#Override
public void onStatusChanged(CommunicatorStatus status, String message) {
// TODO Auto-generated method stub
Log.e("onStatusChanged", "----------------Status Changed------------");
Log.e("STATUS: ", status.toString());
Log.e("MESSAGE: ", message);
Log.e("onStatusChanged", "--------------------------------------------");
}
#Override
public void onMessageReceived(String topic, String message) {
// TODO Auto-generated method stub
Log.e("onMessageReceived", "----------------Message Received------------");
Log.e("TOPIC: ", topic);
Log.e("MESSAGE: ", message);
Log.e("onMessageReceived", "--------------------------------------------");
}
#Override
public void onException(String message) {
// TODO Auto-generated method stub
}
};
mComm.addEventHandler(mHandler);
BroadcastReceiver
class ServiceActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(MQTTService2.ON_EXCEPTION)) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(MQTTService2.MESSAGE_STR))
fireOnException(extras.getString(MQTTService2.MESSAGE_STR));
} else if (action.equals(MQTTService2.ON_MESSAGE_RECEIVED)) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(MQTTService2.MESSAGE_STR)
&& extras.containsKey(MQTTService2.TOPIC_STR))
fireOnMessageReceived(extras.getString(MQTTService2.TOPIC_STR),
extras.getString(MQTTService2.MESSAGE_STR));
} else if (action.equals(MQTTService2.ON_STATUS_CHANGED)) {
Bundle extras = intent.getExtras();
if (extras.containsKey(MQTTService2.STATUS_CODE)) {
MQTTService2.MQTTConnectionStatus status =
MQTTConnectionStatus.parseCode(extras.getString(MQTTService2.STATUS_CODE));
switch (status) {
case CONNECTED:
fireOnStatusChanged(CommunicatorStatus.DISCONNECTED,
extras.getString(MQTTService2.MESSAGE_STR, ""));
break;
case CONNECTING:
break;
case INITIAL:
break;
case NOTCONNECTED_DATADISABLED:
case NOTCONNECTED_UNKNOWNREASON:
case NOTCONNECTED_USERDISCONNECT:
case NOTCONNECTED_WAITINGFORINTERNET:
fireOnStatusChanged(CommunicatorStatus.DISCONNECTED,
extras.getString(MQTTService2.MESSAGE_STR, ""));
break;
default:
break;
}
}
}
}
}
Method called depending on specific intent filter ( onMessageReceived)
private void fireOnMessageReceived(String topic, String message) {
for (MQTTEventHandler eventHandler : handlers) {
eventHandler.onMessageReceived(topic, message);
}
/* for (Iterator<MQTTEventHandler> it = handlers.iterator(); it.hasNext();) {
it.next().onMessageReceived(topic, message);
}*/
}

It seems the following is causing a mismatch between the Intent being broadcast from your Service, and the IntentFilter set on the BroadcastReceiver.
Intent broadcastIntent = new Intent(CALLBACK_ACTION);
broadcastIntent.setAction(ON_MESSAGE_RECEIVED);
The IntentFilter is set for the CALLBACK_ACTION, and the Intent is being instantiated with that same action, but the second line above is resetting the Intent's action to ON_MESSAGE_RECEIVED, causing it to no longer match the Filter on the BroadcastReceiver.
One possible solution would be to add multiple actions to the IntentFilter, and check the delivered action in the Receiver's onReceive() method to determine how to handle the broadcast.
For example:
IntentFilter filter = new IntentFilter(MQTTService2.ACTION_MESSAGE_RECEIVED);
filter.addAction(MQTTService2.ACTION_OTHER);
Then, in the onReceive() method:
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action.equals(ACTION_MESSAGE_RECEIVED)) {
...
}
else if(action.equals(ACTION_OTHER)) {
...
}
...
}
You would then instantiate the broadcast Intent with the desired action, and remove the setAction() call afterward:
Intent broadcastIntent = new Intent(MQTTService2.ACTION_MESSAGE_RECEIVED);
...

Related

Can't execute task of onReceive() method of broadcast class when app is closed.

Here is my service MyServiceSMS.java
Whenever I close my app I only receive a default toast of
broadcastreceiver "Message Recieved By : xxxxxxx"
Rest of the code is not executing below onReceiceve.
I have some task inside onReceiceve method, I want them to be executed even if the user closes the app.
public class MyServiceSMS extends Service {
private IntentFilter mIntentFilter;
private SMSGetter smsGetter;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
smsGetter = new SMSGetter();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsGetter, mIntentFilter);
Toast.makeText(this, "Hello I'm a service", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onDestroy() {
super.onDestroy();
//unregisterReceiver(smsGetter);
}
public class SMSGetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
JSONObject data = new JSONObject();
try {
data.put("from", smsMessage.getDisplayOriginatingAddress());
data.put("message", smsMessage.getMessageBody());
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
if (sharedPreferences.contains(IP) && sharedPreferences.contains(IP)) {
sendSMsToServer sendTextToServer = new sendSMsToServer();
sendTextToServer.execute(data.toString(), sharedPreferences.getString(IP, ""), sharedPreferences.getString(PORT, ""));
Toast.makeText(context, "Your Ip :" + data.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Your IP is empty .. Scan to get IP Again ..", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(context, smsMessage.getDisplayMessageBody(), Toast.LENGTH_SHORT).show();
}
}
}
}
My Manifest
<service
android:name=".viewmodel.MyServiceSMS"
android:enabled="true"
android:exported="true"></service>

Single function to retrive data from Broadcast receiver

I have a function ReadConfig in non activity class which is invoked by a Service. This function uses IntentService to read data from a file.
Function in non activity class
//Start of globalVariables
public static boolean received;
public static String actionID = "ACTION_ID";
public static ArrayList<String> configData;
public static BroadcastReceiver configDataReceiver;
//End of globalVariables
public static List<String> ReadConfig(Context context, String configFileName)
{
configDataReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(intent.getAction().equals(actionID))
{
configData = intent.getStringArrayListExtra("CONFIGDATA");
received = true;
}
}
};
LocalBroadcastManager.getInstance(context)
.registerReceiver(configDataReceiver,new IntentFilter(actionID));
Intent workRequest = new Intent(context,IOConfigurations.class);
workRequest.putExtra("OPERATION","READ");
workRequest.putExtra("FILENAME",configFileName);
//Calling intentservice
context.startService(workRequest);
//Wait for broadcast receiver to get data and assign to global variables
while (!received)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
LocalBroadcastManager.getInstance(context).unregisterReceiver(configDataReceiver);
return configData;
}
Intent Service
Intent configData = new Intent(actionID);
configData.putStringArrayListExtra("CONFIGDATA",FileOperations.readFile(fileName));
LocalBroadcastManager.getInstance(this).sendBroadcast(configData);
The intent service is getting invoked and broadcasts the data but the receiver however doesn't receive any data from Broadcast manager and the while loop continues for ever.
check my comments
public static List<String> ReadConfig(Context context, String configFileName)
{
configDataReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(intent.getAction().equals(actionID))
{
configData = intent.getStringArrayListExtra("CONFIGDATA");
received = true;
}
}
};
LocalBroadcastManager.getInstance(context)
.registerReceiver(configDataReceiver,new IntentFilter(actionID));
Intent workRequest = new Intent(context,IOConfigurations.class);
workRequest.putExtra("OPERATION","READ");
workRequest.putExtra("FILENAME",configFileName);
//Calling intentservice
context.startService(workRequest);
//Wait for broadcast receiver to get data and assign to global variables
while (!received)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// Why here your unregistering the broacast listener,
// Your registering and unregistering in same call, unregiter when your work is done
LocalBroadcastManager.getInstance(context).unregisterReceiver(configDataReceiver);
return configData;
}

Passing data from BroadCastRecevier to activity

I have an SMS reader application and i am showing the senderno and message body into the Custom Listview. For the incoming messages i have registered a broadcast receiver and populating the listView.
Whenever a new message is coming in the broadcast Receiver i am able to get it but I want to this data to be passed onto the activity.
The code snippets are :
MainActvity.java
public class MainSmsActivity extends Activity{
private ListView smsList;
SmsAdapter smsAdapter;
private SmsDao smsDao;
private List<SmsDao> smsDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_demo);
smsDataList = new ArrayList<SmsDao>();
Intent intent = new Intent();
intent.setAction("com.mobile.sms.IncomingSms");
sendBroadcast(intent);
populateSms();
}
public void populateSms(){
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
smsDataList.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
smsDao = new SmsDao();
smsDao.setMessageBody(cursor.getString(1));
smsDao.setSenderNo(cursor.getString(2));
smsDao.setMessageTime(cursor.getLong(3));
smsDataList.add(smsDao);
}
smsAdapter = new SmsAdapter(this,smsDataList);
smsList.setAdapter(smsAdapter);
smsAdapter.notifyDataSetChanged();
cursor.close();
}
}
IncomingSms.Java
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG; // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
I am able to receive all the messages intially into the list view but I want that the ListView should get automatically updated as soon as new message arrives.
In your broadcasereceiver do something like this: (use that intent)
public class SMSReceiver extends BroadcastReceiver {
public static final String NOTIFICATION = "receiver_sms";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive methode", "new SMS Comming");
Bundle myBundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "", address = "";
abortBroadcast();
if (myBundle != null) {
// get message in pdus format(protocol description unit)
Object[] pdus = (Object[]) myBundle.get("pdus");
// create an array of messages
messages = new SmsMessage[pdus.length];
Log.i("onReceive methode", "new SMS Comming");
for (int i = 0; i < messages.length; i++) {
// Create an SmsMessage from a raw PDU.
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// get the originating address (sender) of this SMS message in
// String form or null if unavailable
address = messages[i].getOriginatingAddress();
// get the message body as a String, if it exists and is text
// based.
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
// show message in a Toast
}
// this is what you need
Intent broadcast = new Intent(NOTIFICATION);
broadcast.putExtra("data", strMessage);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
}
and then register ur receiver in ur activity
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(tag, "SMS Received.");
// Intent i = getIntent();
Bundle b = intent.getBundleExtra("SMS");
// String bun = b.getString("MyData");
Log.i(tag, "Bundle: " + b);
String str = intent.getStringExtra("data");
parseSMSData(str);
}
};
and then in onResume():
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(SMSReceiver.NOTIFICATION));
}
and in onDestroy() you must unregister that receiver like this:
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onDestroy();
}
and also don't forget to add this in ur manifest file in application tag:
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
register your service in OnResume() then you can access easily within your class,
#Override
public void onResume()
{
super.onResume();
this.registerReceiver(this.yourservice, new IntentFilter("your service type"));
}
and unregister the service in your onpause()
#Override
public void onPause() {
super.onPause();
try
{
this.unregisterReceiver(this.your service);
}
catch(Exception e)
{
e.printStackTrace();
}
}
add the your broadcast receiver in your activity ,
private WakefulBroadcastReceiver IncomingSms = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//use your receiver content
}
Put the following class in your MainSmsActivity so that you should be able to process your list.
private class IncomingSms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("incomingSms")) {
//your impl here
}
}
}
and in onCreate() of your MainSmsActivity activity, place the following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
IncomingSms broadcastReceiver = new IncomingSms(); // declare it outside so that it should be accessible in onDestroy()
IntentFilter intentFilter = new IntentFilter("incomingSms");
registerReceiver(broadcastReceiver , intentFilter);
}
and in onDestroy() place the following code
#Override
protected void onDestroy() {
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
super.onDestroy();
}

Launch an application in background- Launch Service in background to copy sms content into db

I am trying to develop an application that allows you to save a SQLite database of SMS on the phone as they arrive. I am using the broadcast receiver to recover the message then the activity component to insert into the database. But I'd replace activity by service for the application does not bother the user. Does anyone want to help me.Here is my code://
MainActivity.java
public class MainActivity extends BroadcastReceiver {
private final String ACTION_RECEIVE_SMS = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_RECEIVE_SMS)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] message = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
message[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (message.length > -1) {
String messageBody = message[0].getMessageBody();
String phoneNumber = message[0].getDisplayOriginatingAddress();
Toast.makeText(context, "Expediteur - numero :" + phoneNumber + " Sms : " + messageBody, Toast.LENGTH_SHORT).show();
Intent SecondeItent = new Intent(context, SmsActivity.class);
SecondeItent.putExtra("phoneNumber", phoneNumber);
SecondeItent.putExtra("messageBody", messageBody);
SecondeItent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(SecondeItent);
}
}
}
}
}
public class SmsActivity extends Activity {
smsdao.open();
smsdao.insertSms(sms);
Sms smsFromBdd = smsdao.getSmsWithNum(sms.getNum());
if (smsFromBdd != null) {
Toast.makeText(this, sms FromBdd.toString(), Toast.LENGTH_LONG).show();
}
smsdao.close();
}
}
Other file: SmsDao.java,MyBaseSQLite.java, Sms.java et AndroidManifest.xml, but there are no problems on these files.
A sample service
public class MainService extends Service {
public MainService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// your logic
return super.onStartCommand(intent, flags, startId);
}
}
Invoking service
Intent intent = new Intent(this, MainService.class);
startService(intent);
manifest
<service android:name="packageName.MainService" >
</service>

can't start intent startActivityForResult from class

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.class which 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.
First error is: The constructor Intent(BluetoothService, Class) is undefined
Second error: The method startActivityForResult(Intent, int) is undefined for the type 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.
Next error is in onActivityResult method: *RESULT_OK cannot be resolved to a variable*
//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:
// Initialize the BluetoothChatService to perform bluetooth connections
mBluetoothService = new BluetoothService(this);
Constructor in BluetoothService is:
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);
}
}
Your BluettoothService class is not a context and to initialise an Intent you need a context.So try creating your class like this:
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 BluettoothService class this way from any activity:
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();
}
You can't use this of a Service to start an ActivityForResult
You should to specify the #override for the onActivityResult().
Your code should to be put into a class who extends 'activity' (android.app.Activity).
It's for that you have also this :
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'
//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.
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
}
}

Categories

Resources