calling method of one activity from other activity - android

I have two activities Main nd AvaiableDevices in Main activity i have a button btnAdvc in AvailableDevices
public class MainActivity extends Activity
{
Button btnAdvc;
Button btnPdvc;
Button btnDdvc;
Button btnMdvc;
public BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public static final int REQUEST_ENABLE_BT = 1;
public static UUID MY_UUID=null;
public BluetoothServerSocket mmServerSocket;
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Function enbling Bluetooth
enableBluetooth();
///Function to initialize components
init();
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
btnAdvc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
call();
}
});
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
public void init()
{
btnAdvc=(Button)findViewById(R.id.btnAdvc);
btnPdvc=(Button)findViewById(R.id.btnPdvc);
btnDdvc=(Button)findViewById(R.id.btnDdvc);
btnMdvc=(Button)findViewById(R.id.btnMdvc);
}
public void call()
{
Intent intent=new Intent(this,AvailableDevices.class);
startActivity(intent);
}
}
I have a method searchDevices() in AvailableDevices activity
public class AvailableDevices extends Activity
{
public BluetoothAdapter mBluetoothAdapter;
public BluetoothDevice device;
public ListView lv;//for Available Devices
public ArrayList<String> s=new ArrayList<String>();
public HashSet<String> hs = new HashSet<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_devices);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, s);
lv=(ListView)findViewById(R.id.listView1);
Intent intent=getIntent();
}
public AvailableDevices(BluetoothAdapter bt)
{
mBluetoothAdapter =bt;
}
public void searchDevice()
{
if(mBluetoothAdapter.isEnabled())
{
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
try{
// Get the BluetoothDevice object from the Intent
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
s.add(device.getName()+ "\n" + "#"+ device.getAddress());
//To avoid duplicate devices put it in to hash set which doesn't allow duplicates
hs.addAll(s);
//Clear all the devices in String array S
s.clear();
//Replace with hash set
s.addAll(hs);
//
lv.setAdapter(adapter);
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
//A local bluetooth device to Hold the selected device to connect
BluetoothDevice devtoconnect;
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id)
{
try{
mBluetoothAdapter.cancelDiscovery();
//A local String array to hold the Name and address of the selected bluetooth device
String[] separated = adapter.getItem(position).split("#");
if(mBluetoothAdapter.checkBluetoothAddress(separated[1])==true)
{
devtoconnect = mBluetoothAdapter.getRemoteDevice(separated[1]);
}
// Create object of Connect Thread Class to get connection
// ConnectThread t1=new ConnectThread(devtoconnect);
}catch(Exception e){}
}//Closes onItemClick(AdapterView<?> parentAdapter, View view, int position, long id)
}); //Closes lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
}//Coses function onReceive
};//Closes BroadcastReceiver
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
}//if
}// function searchDevices
}
when i click in btnAdvc of main the searchDevices() method of AvailableDevices activity should be called how can i do it?

you can use broadcast messages. after the button click send a broadcast. and in the other activity register a BroadcastReceiver which will handle the brodcast. so whenever you have got the desired message then call the method in second activity.

From the code provided, it looks like searchDevices() method is not a kind of independent method and uses variables/properties decalred in AvaiableDevices class. So probably what you can try is some like
Intent intent=new Intent(this,AvailableDevices.class);
intent.putExtra("CallSearchDevices", true);
startActivity(intent);
And in AvailableDevices at the end of the onCreate method,
Intent intent=getIntent();
boolean flag = intent.getBooleanExtra("CallSearchDevices", false);
if (flag){
searchDevices();
}
I hope this helps

You should declare your method static so you can call it like that AvailableDevices.searchDevices() from your other activity

Related

Why my bluetooth app does not work on my mobile phone and works in another phone

I am developing a bluetooth chat following a Youtube tutorial, saveral days ago the function of search bluetooth devices availables around me, worked but suddenly to the next day, it did not nothing.
I tried search information and videos, maybe i changed something but nothing, after this for last chance i tried my app in a friendĀ“s mobile phone, and it worked well. So i do not know how can I proceed or how can i fix this.
I am using a Honor 9X (STK-LX1) with Android 10 and EMUI 10.0.0, the API is 30.
Now I test the app in another friendĀ“s mobile, and it worked.
public class DeviceListActivity extends AppCompatActivity {
private Context context;
private ListView listPairedDevices, listAvailableDevices;
private ArrayAdapter<String> adapterPairedDevices, adapterAvailableDevices;
private BluetoothAdapter bluetoothAdapter;
private ProgressBar progressScanDevices;
private Set<BluetoothDevice> foundDevices = new HashSet<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
context = this;
init();
}
private void init(){
listPairedDevices = findViewById(R.id.list_paired_devices);
listAvailableDevices = findViewById(R.id.list_available_devices);
progressScanDevices = findViewById(R.id.progress_scan_devices);
adapterPairedDevices = new ArrayAdapter<String>(context,R.layout.device_list_item);
adapterAvailableDevices = new ArrayAdapter<String>(context, R.layout.device_list_item);
listPairedDevices.setAdapter(adapterPairedDevices);
listAvailableDevices.setAdapter(adapterAvailableDevices);
listAvailableDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String info = ((TextView)view).getText().toString();
String mac = info.substring(info.length()-17);
Intent intent = new Intent();
intent.putExtra("deviceAddress",mac);
setResult(RESULT_OK,intent);
finish();
}
});
listPairedDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String info = ((TextView)view).getText().toString();
String address = info.substring(info.length()-17);
Intent intent = new Intent();
intent.putExtra("deviceAddress",address);
setResult(RESULT_OK,intent);
finish();
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if(pairedDevices != null && pairedDevices.size()>0){
for( BluetoothDevice device: pairedDevices){
adapterPairedDevices.add(device.getName() + "\n"+ device.getAddress());
}
}
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothDeviceListener,intentFilter);
IntentFilter intentFilter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(bluetoothDeviceListener,intentFilter1);
IntentFilter intentFilter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(bluetoothDeviceListener,intentFilter2);
}
private BroadcastReceiver bluetoothDeviceListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
String deviceName = device.getName();
if(deviceName!=null){
if(foundDevices.contains(device))
return;
foundDevices.add(device);
adapterAvailableDevices.add(device.getName() + "\n" + device.getAddress());
}
}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
progressScanDevices.setVisibility(View.GONE);
if(adapterAvailableDevices.getCount() == 0){
Toast.makeText(context, "No new devices found",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Click on the device to start the chat",Toast.LENGTH_SHORT).show();
}
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_device_list, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menu_scan_devices:
scanDevices();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void scanDevices(){
progressScanDevices.setVisibility(View.VISIBLE);
adapterAvailableDevices.clear();
//Toast.makeText(context, "Scan Devices",Toast.LENGTH_SHORT).show();
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
}
Edit 1: I put Log.e("Tag 1", "Start search") at the end of the function scanDevices and another Log.e("Tag2","BroadcastReceiver") inside the onReceive function of BroadcastReceiver
When i use the Honor 9x, only appears the first Log.e, but when i use the anothers mobile phones, it appears the first and second.
Edit 2: I have the uses permission on my manifest, BLUETOOTH_ADMIN, BLUETOOTH, ACCESS_FINE_LOCATION.
I would appreciate any help.

Android update ListFragment's listView from another fragment

I have a question about updating my ListView in ListFragment from my Map fragment. Each time I will call this method I will assign different values to String Array. And what should I put into that Update method to refresh the listview ?
In ListFragment create and register BroadcastReceiver :
static final String ACTION_CUSTOM = "action";
BroadcastReceiver mReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new BroadcastReceiver(){
public void onReceive(android.content.Context context, Intent intent) {
//Check for action you need
if (intent.getAction() == ACTION_CUSTOM ){
//Do stuff with data from intent
intent.getExtras().getString("data");
}
}
};
}
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(receiver, new IntentFilter(ACTION_CUSTOM ));
}
#Override
protected void onPause() {
super.onPause();
getActivity().unregisterReceiver(receiver);
}
In MapFragment send broadcast intent, when you need to change data:
Intent intent = new Intent();
//Set action you need to send
intent.setAction(ACTION_CUSTOM);
//Add data to send
intent.putExtra("data", "data_value");
//Send broadcast intent
getActivity().sendBroadcast(intent);

Android broadcast receiver get registered multiple times when activity minimise and maximise

Hi I am working with android.I am looking to update ui from service data. So that I get data from service via broadcast receiver succesfully and I updated listview when value changes.My problem is that during activity running, if i minimise the activity and then maximise, the another receiver is get registered and which will repeats my listview data.How can I set only one receiver when after maximise ? here is my code
public class MainActivity extends Activity {
ListView l1;
ArrayList<String> t1=new ArrayList<String>();
ArrayList<String> d1=new ArrayList<String>();
ArrayList<Integer> i1=new ArrayList<Integer>();
MyReceiver myReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
//l1.setAdapter(new dataListAdapter(t1,d1,i1));
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Intent intent = new Intent(MainActivity.this,
com.example.androidservice.MyService.class);
startService(intent);
super.onStart();
}
#Override
protected void onStop() {
unregisterReceiver(myReceiver);
stopService(new Intent(MainActivity.this,MyService.class));
super.onStop();
}
#Override
protected void onPause() {
//unregisterReceiver(myReceiver);
stopService(new Intent(MainActivity.this,MyService.class));
super.onPause();
}
private class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
String datapassed1 = arg1.getStringExtra("DATAPASSED1");
String datapassed2 = arg1.getStringExtra("DATAPASSED2");
Toast.makeText(MainActivity.this,
"Triggered by Service!\n"
+ "Data passed: " + String.valueOf(datapassed1),
Toast.LENGTH_SHORT).show();
t1.add(datapassed1);
d1.add(datapassed2);
for(int i=0;i<t1.size();i++)
{
i1.add(R.drawable.ic_launcher);
}
l1.setAdapter(new dataListAdapter(t1,d1,i1));
}
}
class dataListAdapter extends BaseAdapter {
ArrayList<String> Title, Detail;
ArrayList<Integer> imge;
dataListAdapter() {
Title = null;
Detail = null;
imge=null;
}
public dataListAdapter(ArrayList text, ArrayList text1,ArrayList text3) {
notifyDataSetChanged();
Title = text;
Detail = text1;
imge = text3;
}
public int getCount() {
// TODO Auto-generated method stub
return Title.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.custom, parent, false);
TextView title, detail;
ImageView i1;
title = (TextView) row.findViewById(R.id.title);
detail = (TextView) row.findViewById(R.id.detail);
i1=(ImageView)row.findViewById(R.id.img);
title.setText(Title.get(position));
detail.setText(Detail.get(position));
i1.setImageResource(imge.get(position));
return (row);
}
}
}
Register the broadcast receiver and start the service in onCreate(), and
unRegister the receiver and stop the service in onDestroy().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
//l1.setAdapter(new dataListAdapter(t1,d1,i1));
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Intent intent = new Intent(MainActivity.this,
com.example.androidservice.MyService.class);
startService(intent);
}
#Override
protected void onDestroy() {
unregisterReceiver(myReceiver);
stopService(new Intent(MainActivity.this,MyService.class));
super.onDestroy();
}
You should register your BroadcastReceiver in onResume and unregister it in onPause. After that, you don't need to register/unregister it in any of the other activity's lifecycle methods.
#Override
protected void onResume() {
super.onResume();
registerReceiver(myReceiver, new IntentFilter(MyService.MY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
I hope this helps.
There should be something missing here (Perhaps your manifest). It seemed correct to me how to handle your receivers (you don't necesarily to use onPause-onResume to register/unregister).
Please make sure you don't also register the receiver # the manifest file as well.

How to refresh a ListView from a BroadcastReceiver?

If I call notifyDataSetChanged() on the custom adapter associated to my ListView, all the views should refresh themself (getView() will be called).
Now I have a BroadcastReceiver that is listening to an event. When the event fires, the ListView must be refreshed. How can I achieve this?
Thanks!
If you refresh listview from receiver you'll have code like this:
BroadcastReceiver br;
public final static String BROADCAST_ACTION = "BROADCAST_ACTION";
br = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//code refreshing...
}
};
IntentFilter intFilt = new IntentFilter(BROADCAST_ACTION);
registerReceiver(br, intFilt);
And you call it with code:
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
If you need the refresh to be another action you just need to add (after action):
Intent intent = new Intent(BROADCAST_ACTION);
sendBroadcast(intent);
As requested, please see the sample code below:
public interface OnDataUpdateListener {
void onDataAvailable(ArrayList<String> newDataList);
}
public class MyTestReceiver extends BroadcastReceiver {
public static final String DATA_LIST = "DATA_LIST";
private OnDataUpdateListener mDataUpdateListener = null;
public MyTestReceiver(OnDataUpdateListener dataUpdateListener) {
mDataUpdateListener = dataUpdateListener;
}
#Override
public void onReceive(Context ctx, Intent intent) {
// assuming data is available in the delivered intent
ArrayList<String> dataList = intent.getSerializableExtra(DATA_LIST);
if (null != mDataUpdateListener) {
mDataUpdateListener.onDataAvailable(dataList);
}
}
}
public class MyActivity extends FragmentActivity implements OnDataUpdateListener {
public static final String ACTION_DATA_UPDATE_READY = "ACTION_DATA_UPDATE_READY";
private MyTestReceiver mTestReceiver = null;
private <SomeAdapterClass> mAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// other required initialization
mTestReceiver = new MyTestReceiver(this);
}
#Override
public void onResume() {
super.onResume();
if (null != mTestReceiver) {
registerReceiver(mTestReceiver, new IntentFilter(ACTION_DATA_UPDATE_READY));
}
}
void onDataAvailable(ArrayList<String> newDataList) {
// assuming you want to replace existing data and not willing to append to existing dataset
mAdapter.clear();
mAdapter.addAll(newDataList);
mAdapter.notifyDataSetChanged();
}
}
In the code where your data is updated, fire off a message signalling that data has been changed...
(You will need access to either the Activity or the Application context to do this)
Intent intent = new Intent("ListViewDataUpdated");
LocalBroadcastManager.getInstance(context.sendBroadcast(intent));
Then just catch the catch the message using the following code in your activity, and tell your ListAdapter to update...
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
myListAdapter.notifyDataSetChanged();
}
};
#Override
public void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("ListViewDataUpdated"));
myListAdapter.notifyDataSetChanged();//in case our data was updated while this activity was paused
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
Credit: adapted from Vogella
LocalBroadcastManager.getInstance(context.sendBroadcast(intent));
change to
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
I might be wrong but it works for me...

Android Getting continuously Bluetooth signal strength of paired devices

i am listing all paired devices,and it well work but now want to get Bluetooth signal strength of paired devices...i know it will get by use rssi but cannot implement get it continuously in my app..
plz me by giving suitable code as my code...my code is here...
public class Security extends Fragment implements OnClickListener{
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ArrayList<String> mylist = new ArrayList<String>();
//private Object ImageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.security, null);
BA = BluetoothAdapter.getDefaultAdapter();
/* starting the bluetooth*/
on(v);
pairedDevices = BA.getBondedDevices();
//length=4;
// int j=1;
for(BluetoothDevice bt : pairedDevices) {
mylist.add(bt.getName());
length=j;
j++;
bt.getBondState();
}
return v;
}
#Override
public void onResume() {
super.onResume();
// Toast.makeText(getActivity(), "On resume", Toast.LENGTH_LONG).show();
}
/*************************Bluetooth function****************************/
public void on(View view){
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getActivity(),"Turned on"
,Toast.LENGTH_LONG).show();
} else{
// Toast.makeText(getActivity(),"Already on",
// Toast.LENGTH_LONG).show();
}
}
public void Discovery(View view) {
if(BA.isDiscovering()) {
BA.cancelDiscovery();
}
}
public void list(View view){
Toast.makeText(getActivity(),"Showing Paired Devices",
Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
for(int j=0;j<length;j++) {
if(v.getId()==j)
Toast.makeText(getActivity(), mylist.get(j), Toast.LENGTH_LONG).show();
//hand.update(run,1000);
}
}
}
You can get the signal from following code.
Code your activity
#Override
public void onCreate(Bundle savedInstanceState) {
.....
// Registering Broadcast. this will fire when Bluetoothdevice Found
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
}
private final BroadcastReceiver BroadcastReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String mIntentAction = intent.getAction();
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(mIntentAction)) {
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String mDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
}
}
};
This broadcast will execute when your device will be connected to the remote device.
There are several other action on which you can fire this broadcast. have a look at here(BluetoothDevice)
Check following link for constant reading of RSSI
Tutorial to continuously measure the Bluetooth RSSI of a connected Android device (Java)
Output of link :
Then if you want to do it in continuously, you need to run it in a service or in a thread. So that you can even add time slots or sleep (waits) measuring the RSSI.

Categories

Resources