Android BroadcastReceiver : get object from onReceive method - android

I'm trying to pass an array list containing Wi-Fi informations from a class that exdends from BroadcastReceiver to another class .I can pass a normal vriable between two classes with the getter. But i'm getting an empty array, because the onReceive methode is not executed .I would like to execute the onReceive methode in another class(but i can't instantiate it ) or to get the array created in the onReceive methode in another class with a getter (but i cant get the list).Please how can i get this array in the second class.
This is the WifiData class
public class WifiData extends BroadcastReceiver{
List<String[]> wifiValues = new ArrayList<String[]>();
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
int aa = 10;
int a=10 ;
List<String[]> getWifi (){
return wifiValues ;
}
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
List<ScanResult> results = wifi.getScanResults();
resultsString = results.toString() ;
for(int i=0;i<results.size();i++){
Log.i("Wifi SSID",results.get(i).level+"");
wifiValues.add(new String[] { results.get(i).level +"" });
}
}
}
}
This is SalesStackedBarChart class that have to get the wifi infomation and create a chart :
public class SalesStackedBarChart extends AbstractDemoChart {
public Intent execute(Context context) {
WifiData wi = new WifiData ();
// values.add(new double[] {wi.getWifi() });
Log.i("aaaa",wi.getWifi()+"");
}
}
Thank you.

You are trying to show the data in graph using AChartEngine right?
Create a new activity and put the chart in that layout. Read here how to use the AChartEngine.
Now when you are passing the data from the first class(activity) to the second class(activity), you can pass the data using the intent. Add extra to the Intent using intent.putExtras().First create a bundle. In that bundle put the data using appropriate method like putSerializableExtra() or putParcelableExtra() and in the second class(activity) call getIntent and catch that intent in a temp variable.
From that you can retrieve the data using intent.getExtras().getSerializableExtra() etc. And you can load the data into AChartEngine data to be displayed as a graph.

This is a working solution :
Starting with WifiActivity activity ,wich will determin wifi scan list ,and send it to the TruitonAChartEngineActivity class.
WifiActivity activity
public class WifiActivity extends Activity {
/** Called when the activity is first created. */
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
int aa = 10;
//tableau pris à partir de http://www.radio-electronics.com/info/wireless/wi-fi/80211-channels-number-frequencies-bandwidth.php
int [ ] [ ] Center_Frequency_2 = { { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 },
{ 2412, 2417, 2422, 2427, 2432,2437,2442,2447,2452 ,2457,2462,2467,2472,2484},
};
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
final List<ScanResult> results = wifi.getScanResults();
resultsString = results.toString() ;
Log.i("resultsString*****************",resultsString);
final String [ ] [ ] chanelRssi = new String [results.size()][2];
String[] tabResults = new String[results.size()];
for(int i=0;i<results.size();i++){
if (results.get(i).frequency /1000 == 2) {
for (int j =0;j<14;j++)
{ if (Center_Frequency_2[1][j] == results.get(i).frequency)
tabResults[i]=results.get(i).SSID +" (" + results.get(i).BSSID + ") \n"+ results.get(i).frequency +"\n"+ results.get(i).level +"\n"+ results.get(i).capabilities +"\n"+"canal "+Center_Frequency_2[0][j] ;
chanelRssi[i][0]=Center_Frequency_2[0][j]+"";
chanelRssi[i][1]=results.get(i).level +"";
}
}
}
Button send = (Button) findViewById(R.id.barChartButton);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click","click");
Toast.makeText(getApplicationContext(),
"Position :"+resultsString , Toast.LENGTH_LONG)
.show();
Intent intent1 = new Intent (getApplicationContext(),TruitonAChartEngineActivity.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", (Serializable) results);
intent1.putExtras(bundleObject);
startActivityForResult(intent1,0);
/* Intent intent1 = new Intent (getApplicationContext(),TruitonAChartEngineActivity.class);
startActivityForResult(intent1,0);*/
}
});
}
}
private void startActivities(Intent intent, int i) {
// TODO Auto-generated method stub
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi);
ConnectivityManager cxMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
Receiver receiver = new Receiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
registerReceiver(receiver,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
}
And the TruitonAChartEngineActivity class
public class TruitonAChartEngineActivity extends ActionBarActivity {
private static final int SERIES_NR = 2;
String message1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truiton_achart_engine);
XYMultipleSeriesRenderer renderer = getTruitonBarRenderer();
myChartSettings(renderer);
Bundle v = getIntent().getExtras();
ArrayList<ScanResult> classObject = (ArrayList<ScanResult>) v.getSerializable("key");
// message1 = v.getString("message1");
/* Toast.makeText(getApplicationContext(),
"Position :" , Toast.LENGTH_LONG)
.show();*/
/* Toast.makeText(getApplicationContext(),
"Position classObject :"+classObject , Toast.LENGTH_LONG)
.show();*/
for(int index = 0; index < classObject.size(); index++){
String Object = classObject.get(index).level+"";
Toast.makeText(getApplicationContext(), "Id is :"+Object, Toast.LENGTH_SHORT).show();
}
Intent intent = ChartFactory.getBarChartIntent(this, getTruitonBarDataset(), renderer, Type.DEFAULT);
startActivity(intent);
}}

Related

Error sending data using intent from class to MainActivity

In my MainActivity I need to know the state of a boolean type variable to hide or put an icon visible, but this variable is generated in another class called TcpClient which is called several times by the MainActivity, I am trying to use intent to send this variable from the TcpClient class but I have errors.
This is my code of my MainActivity:
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private TcpClient mTcpClient;
public boolean statusWIFI = false;
.
.
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) { //we create a TCPClient object and
publishProgress(message); //this method calls the onProgressUpdate
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//arrayList.add("RX: " + values[0]); //in the
arrayList we add the messaged received from server
mDumpTextView.append( values[0] );
mDumpTextView.append( "\n" );
mScrollView.smoothScrollTo( 0, mDumpTextView.getBottom() );
mAdapter.notifyDataSetChanged(); // notify the
adapter that the data set has changed. This means that new message
received
// from server was added to the list
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem IconWIFI = menu.findItem(R.id.bt1_wifi);
Intent intent = getIntent();
Bundle bundle = null;
bundle = getIntent().getExtras();
if (bundle !=null) {
statusWIFI = bundle.getBoolean( "mstatusWIFI");
}
if (statusWIFI == true){
IconUsbON.setVisible(true);
}else{
IconUsbON.setVisible(false);
}
return true;
}
This is the code of my TcpClient class:
public class TcpClient {
private Boolean statusWIFIX = false;
.
.
public void stopClient() {
statusWIFIX = false;
Intent intent = new Intent( this, MainActivity.class );
intent.putExtra( "mstatusWIFI", statusWIFIX );
startActivityForResult( intent, 0 );
sendMessage(Constants.CLOSED_CONNECTION+": " + Modelox);
// send message that we are closing the connection
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
Here is the error; someone could tell me how to correct this
I did't see any initialization of mTcpClient, you need to initialize it like:
mTcpClient= TcpClient();
and if your variable is in TcpClient class you can access it via mTcpClient.statusWIFIX
You also need to make statusWIFIX scope to public like this:
public Boolean statusWIFIX = false;
in your TcpClient class.
You can also send data via intent but just for accessing statusWIFIX to start an activity again is not a good approach.
You must have to pass activity context into the Intent constructor. The TCPClient is not seems any activity or service.

Update view when a push notification is received

I would like to update a view from within an open activity when the device receives a push notification.
When a push notification is received the updateBalance function is executed,
a mysql database is queried and an amount is returned.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private void updateBalance(String messageBody) {
h1 = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
bb = msg.getData();
String str = bb.getString("result");
Log.d(TAG,str);
Message msg=handler.obtainMessage()
}
};
t = new Thread(new MyRunnable(h1));
t.start();
try {
t.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I have another class
public class MyRunnable implements Runnable {
private Handler h2;
public MyRunnable(Handler h) {
this.h2 = h;
}
#Override
public void run() {
String name = "w12";
BalanceActivity NB = new BalanceActivity(name);
Message m = Message.obtain();
Bundle b = new Bundle();
b.putString("result", "10");
m.setData(b);
h2.sendMessage(m);
}
}
I have a MainActivity that I would like to update after the amount is returned. How would I do this possibly with another Handler and Runnable.
public class MainActivity extends Activity {
TextView TV = (TextView) findViewById(package.name.R.id.Balance);
}
Try to check your activity is currently in foreground. if yes then create method where you can update your view.
public static boolean isServiceRunning(Context context) {
Log.i(TAG, "Checking if service is running");
ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
boolean isServiceFound = false;
for (int i = 0; i < services.size(); i++) {
if (Constants.PACKAGE.equals(services.get(i).service.getPackageName())){
if (Constants.BACKGROUND_SERVICE_CLASS.equals(services.get(i).service.getClassName())){
isServiceFound = true;
}
}
}
Log.i(TAG, "Service was" + (isServiceFound ? "" : " not") + " running");
return isServiceFound;
}
Make use of Broadcast Receivers. Register local broadcast receiver in activity. Broadcast data when notification received.

Android SMS multi text groups

My project is a checklist of phone numbers in a recyclerView/cardView. The phone numbers/businesses can be added or subtracted by a checkBox to make individual groups. I want to be able to send a group multi-text to the selected individuals.
My problem is that only the first phone number (recipient) in a group receives the message while the rest receive nothing, but the numbers still display in the edit text (the first is the only functioning number).
I have tried a lot of different ways but nothing has worked, I am about to give up.
No one seems to know how to fix this problem. If this problem can be solved please let me know.
I don't want to loop the numbers and text individually, that was a suggested fix.
This is the phone activity:
public class ACPhone extends AppCompatActivity {
private static final String SEPARATOR = ";";
EditText txtPhoneNo;
EditText txtMessage;
TextView txtView;
Button btnsend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acphone);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
txtView = (TextView)findViewById(R.id.txtMessageMass);
btnsend = (Button) findViewById(R.id.btnSend);
Intent intent = getIntent();
if (intent != null){
ArrayList<CharSequence> selectedNumbers =
intent.getCharSequenceArrayListExtra(SELECTED_NUMBERS);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < selectedNumbers.size(); i++) {
sb.append(selectedNumbers.get(i));
if (i != selectedNumbers.size() - 1){
sb.append(SEPARATOR);
}
}
txtPhoneNo.setText(sb.toString());
}
btnsend.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
String messageView = txtView.getText().toString();
if (phoneNo.length() > 0 && message.length() > 0) {
sendMessage(phoneNo, message, messageView);
} else {
Toast.makeText(getBaseContext(), "Please enter message",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendMessage(String phoneNo,String message, String staticMessage){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message + "\n" +
staticMessage,null,null);
Toast.makeText(getApplicationContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "Unable to send. Please try again", Toast.LENGTH_SHORT).show();
}
}
}
You could create a list of all the numbers and do a for loop through the list in your onclick or in a method and call it in onclick. That's how I would do it anyway.
Following are the some steps to send one single message to multiple contact when it is checked.
Step 1 : In your MainActivity.class like this,
public class MainActivity extends AppCompatActivity {
ListView listView;
EditText editMessage;
ProgressDialog progressDialog;
Handler progresshandler;
boolean isThreadRunning;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.contactsView);
editMessage = (EditText) findViewById(R.id.editMessage);
listView.setAdapter(new ContactAdapter(this, contacts));
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Sending Messages.. Please wait!");
progresshandler = new Handler() {
public void handleMessage(Message msg) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Messages Sent",
Toast.LENGTH_LONG).show();
}
};
}
}
Step 2 : Create one class within this MainActivity.class(Put this class below onCreate() method)
class SendMessagesThread extends Thread {
Handler handler;
public SendMessagesThread(Handler handler) {
this.handler = handler;
}
public void run() {
SmsManager smsManager = SmsManager.getDefault();
// Find out which contacts are selected
for (int i = 0; i < listView.getCount(); i++) {
View item = (View) listView.getChildAt(i);
boolean selected = ((CheckBox) item.findViewById(R.id.selected)).isChecked();
if (selected) {
String mobile = ((TextView) item.findViewById(R.id.mobile)).getText().toString();
try {
smsManager.sendTextMessage(mobile, null, editMessage.getText().toString(), null, null);
} catch (Exception ex) {
Log.d("Mobile", "Could not send message to " + mobile);
}
}
}
Message m = handler.obtainMessage();
handler.sendMessage(m);
} // run
} // Thread
Step 3: Create one method(put this method below step - 2)
public void sendMessages(View v) {
if (editMessage.getText().toString().length() > 0) {
SendMessagesThread thread = new SendMessagesThread(progresshandler);
thread.start();
progressDialog.show();
} else {
Toast.makeText(this, "Please enter message!", Toast.LENGTH_LONG)
.show();
}
}
Note : According to my project, I am not using any SQLite database or webservice.Basically, I am fetching all the contact from device contact book and displaying that contact to listview. So, Try to understand and modify.
public class TextActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<CharSequence> selectedNumbers
=getIntent().getCharSequenceArrayListExtra(SELECTED_NUMBERS);;
String phNumbers = "";
for (CharSequence s: selectedNumbers) {
phNumbers += s + ";";
}
// for (int i = 0; i < selectedNumbers.size(); i++) {
// phNumbers += selectedNumbers.get(i);
// if (i != selectedNumbers.size()-1){
// phNumbers += ";";
// }
// }
phNumbers = phNumbers.substring(0, phNumbers.length() - 1);
String message = "";
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", phNumbers);
smsIntent.putExtra("sms_body",message);
startActivity(smsIntent);
}
}

Android Sms Receiver Result to Main Activity

MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.anaekran);
Thread t = new Thread(new Runnable() {
public void run() {
String smsMsj = getIntent().getStringExtra("sms");
if(smsMsj != null){
Toast.makeText(getApplication(), smsMsj, 2).show();
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle mesaj = intent.getExtras();
SmsMessage[] smsMessage = null;
String msj = "";
if(mesaj!= null){
Object[] pdus = (Object[])mesaj.get("pdus");
smsMessage = new SmsMessage[pdus.length];
for(int i = 0; i < pdus.length; i++){
smsMessage[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msj = smsMessage[i].getMessageBody();
}
Intent mIntent = new Intent(context, SmsReceiver.class);
mIntent.putExtra("sms", msj);
}
}
}
My receiver working correctly but i have one problem when message coming i want to show on my MainAcitivty toast, so i create mIntent in receiver class, and then im use putExtra method.
But not working, sory for my bad english and thank you :)
Perhaps using explicit Intent and starting it could help you, hm? :)
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.putExtra("sms", msj);
context.startActivity(mIntent);
Your mistake is that you construct your new Intent with SmsReceiver.class (but you need to launch MainActivity) and that you do not start any activity with such an intent.
Edit 1: Also, pay attention - you are trying to run a toast inside your worker thread. This is not possible. Remove your anonymous Thread and move your toast code to your onCreate(Bundle):
protected void onCreate(Bundle saveState){
....
String smsMsj = getIntent().getStringExtra("sms");
if(smsMsj != null){
Toast.makeText(getApplication(), smsMsj, 2).show();
}
....
}
Edit 2: Moreover, your duration parameter in Toast.makeText(..) is set to 2. This does not correspond to any magic constant in Toast class. You have to use one of the constants: Toast.LENGTH_LONG or Toast.LENGTH_SHORT. So, rewrite your code to:
Toast.makeText(getApplication(), smsMsj, Toast.LENGTH_SHORT);

Starting Another Activity on InfoWindowClickListener

I am simply trying to navigate on Another Activity from my FragmentActivity having GoogleMap there. I have following code for InfoWindowClickListener
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String distance[] = marker.getSnippet().split(" - ");
String distanceString = distance[0];
String idString = marker.getId();
String stationid = markershashmap.get(idString);
Toast.makeText(getApplicationContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent dockitdetailsIntent = new Intent(
getApplicationContext(), AnotherActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
dockitdetailsIntent.putExtra("stationId", stationid);
dockitdetailsIntent.putExtra("distance", distanceString);
parentActivity.startChildActivity("Activity Name",
dockitdetailsIntent);
}
});
But when I click the InfoWindow, my device hangs and then I have to force close the not responding app. When i use startActivity(dockitdetailsIntent) it works fine but Tab removes. But I want to use the Next Activity into the similar tabs. Please suggest me why my device hangs out and doesn't respond.
Create Handler and Put Intent logic into this like below:
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m1) {
// TODO Auto-generated method stub
try{
String[] str2=str.split("contactID");
Message mesg = new Message();
Bundle b = new Bundle();
b.putString("contact_id", str2[1]);
mesg.setData(b);
handler.sendMessage(mesg);
}catch(Exception e){
e.printStackTrace();
}
}
});
And now create one handler like below:
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Bundle b1 = new Bundle();
b1.putString("ContactID", b.getString("contact_id"));
b1.putBoolean("showBack", true);
Intent edit = new Intent(getParent(), ContactDetails2.class);
edit.putExtras(b1);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("ContactDetails2", edit);
}
};
Try this. It's working in my case

Categories

Resources