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);
}
}
Related
I am new in android development. i want my application to directly launch MainActivity if the User has already registered. how can i do this.
this is my MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
Button btnTip, btnApp, btndos, btnAbout, btnServices;
ConnectionDetector cd;
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
public static String contact;
public static String imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Dental Application");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnTip = (Button) findViewById(R.id.tips);
btndos = (Button) findViewById(R.id.dos);
btnApp = (Button) findViewById(R.id.appointments);
btnAbout = (Button) findViewById(R.id.about);
btnServices = (Button) findViewById(R.id.services);
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please check your Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
contact = i.getStringExtra("contact");
imei = i.getStringExtra("imei");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId, contact, imei);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
btnTip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TipsActivity.class);
startActivity(intent);
}
});
btndos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DosActivity.class);
startActivity(intent);
}
});
btnApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BookAppointmennts.class);
startActivity(intent);
}
});
btnAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AboutUsActivity.class);
startActivity(intent);
}
});
btnServices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ServicesActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
//lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver", "> " + e.getMessage());
}
super.onDestroy();
}
}
and the RegisterActivity
public class RegisterActivity extends Activity {
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
// UI elements
EditText txtName;
EditText txtEmail;
EditText txtContact;
// Register button
Button btnRegister;
String imei;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if GCM configuration is set
if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
|| SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
alert.showAlertDialog(RegisterActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
txtName = (EditText) findViewById(R.id.txtName);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtContact = (EditText) findViewById(R.id.contact);
btnRegister = (Button) findViewById(R.id.btnRegister);
TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = mngr.getDeviceId();
/*
* Click event on Register button
* */
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Read EditText dat
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String contact = txtContact.getText().toString();
// Check if user filled the form
if (name.trim().length() > 0 && email.trim().length() > 0 && contact.trim().length()>0) {
// Launch Main Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Registering user on our server
// Sending registraiton details to MainActivity
i.putExtra("name", name);
i.putExtra("email", email);
i.putExtra("contact", contact);
i.putExtra("imei", imei);
startActivity(i);
finish();
} else {
// user doen't filled that data
// ask him to fill the form
alert.showAlertDialog(RegisterActivity.this, "Registration Error!", "Please enter your details", false);
}
}
});
}
}
i am using GCM. the user is first registered and MainActivity is Displayed. Next time when the user opens the application i want directly MainActivity to be displayed. how can i do this. Can anyone please help me.
You will have to make LauncherActivity like SplashScreen in which check from shared prefrences or sqlite data that user is already registered or not
then by checking this transfer to corresponding activity.
If the user is not registered then show Registration Screen and when user register then save info in Sqlite or sharedpreferences or any other way.
If the user is already registered the show HomeScreen
First of all just post only the code that needs modification, you've posted all of the code in that Java file of yours. We could be more helpful if your code isn't cluttered.
I have also posted in android Enthusiasts, not sure if its the correct place..
We have created an app to scan for wifi hotspots / AP so we can read the SSID and RSSI. We have some test phones with hotspot turned on and hard coded the SSID into the app. When the APP launches for the first time all works OK, we click the AP (checkbox) and hit start (button).When we close the app and launch it again, as soon as we click the AP (checkbox) it start scanning even though we haven't click the start button. we need to reinstall the app on the phone every time. Can anyone help us with this BUG/ unwanted feature as its slowing us up.
here is the code for the main Activity.
your help is greatly appreciated.
public class RssiMyActivity extends Activity{
// Declare global variables
private WifiManager mainWifiObj;
private WifiScanReceiver wifiReciever;
private ListView list;
private ArrayAdapter<String> adapter;
private List<String> ap_details = new ArrayList<String>();
private static String ssid;
private int testCount;
private CheckBox a1, a2, a3, a4, a5, a6;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssi_my);
list = (ListView) findViewById(R.id.listView1);
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
// Get make a connection to database to get test count
ReceiveFromDB receiver = new ReceiveFromDB();
receiver.execute();
// Update the test count
testCount = ReceiveFromDB.getCount();
testCount += 1;
// Check to see what value testCount is
Log.e("Values for testCount", String.valueOf(testCount));
Button start;
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Timer added to get new scan result once every 2 seconds
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 0, 4000);
}
});
Button pause;
pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onPause();
}
});
Button resume;
resume = (Button) findViewById(R.id.resume);
resume.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onResume();
}
});
a1 = (CheckBox) findViewById(R.id.AP1);
a2 = (CheckBox) findViewById(R.id.AP2);
a3 = (CheckBox) findViewById(R.id.AP3);
a4 = (CheckBox) findViewById(R.id.AP4);
a5 = (CheckBox) findViewById(R.id.AP5);
a6 = (CheckBox) findViewById(R.id.AP6);
}
protected void onPause()
{
unregisterReceiver(wifiReciever);
super.onPause();
}
protected void onResume()
{
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
// Timer method to run at the same time as the main activity
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
/*
* Runnable method add code to here to refresh at specified time
*/
private Runnable Timer_Tick = new Runnable()
{
#Override
public void run()
{
try
{
// start a scan of ap's
mainWifiObj.startScan();
}
catch (Exception e)
{
e.getStackTrace();
}
}
};
class WifiScanReceiver extends BroadcastReceiver
{
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent)
{
// Clear details to refresh the screen for each new scan
if (ap_details.size() > 0)
{
try
{
ap_details.clear();
adapter.clear();
adapter.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
try
{
// Get all Objects from the scan
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
List<ScanResult> temp = new ArrayList<ScanResult>();
// Run through each signal and retrieve the mac ssid rssi
for (ScanResult aWifiScanList : wifiScanList)
{
StringBuilder sb = new StringBuilder();
// Pull out the info we need
ssid = aWifiScanList.SSID;
// Check which ap's are selected
if (checkDisplay())
{
// Add info to StringBuilder
sb.append(aWifiScanList.SSID).append("\n");
sb.append(String.valueOf(aWifiScanList.level)).append("\n");
sb.append("Test: ").append(String.valueOf(testCount)).append("\n");
// Add to List that will be displayed to user
ap_details.add(sb.toString());
// Also add to a temporary ScanResult List to use later
temp.add(aWifiScanList);
}
}
// Create an String Array twice the size of the temporary
// ScanResult
// this will be the Array to use as the parameters for sending
// to the database
String[] items = new String[temp.size() + temp.size() + 1];
int num1 = 0;
int num2 = 1;
// Add the ssid and rssi of each object to the Array
for (ScanResult aTemp : temp)
{
items[num1] = aTemp.SSID;
items[num2] = String.valueOf(aTemp.level);
num1 += 2;
num2 += 2;
}
// Add the test value
items[num1] = String.valueOf(testCount);
// Pass Array to the Async method use executeOnExecutor this
// allows for the use
// of the Looper.prepare() method to stop app from crashing
new ConnectToDB().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, items);
// Display the list of all the signals on the device
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, ap_details);
list.setAdapter(adapter);
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
/*
* Method to check which AP's are been used
*/
public boolean checkDisplay()
{
if (a1.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone1"))
{
return true;
}
}
if (a2.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone2"))
{
return true;
}
}
if (a3.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone3"))
{
return true;
}
}
if (a4.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone4"))
{
return true;
}
}
if (a5.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone5"))
{
return true;
}
}
if (a6.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone6"))
{
return true;
}
}
return false;
}
You never call cancel() on your timer task to remove it from the Timer scheduler. Try inserting that in a button you use to stop it from scanning.
If that doesn't work, try calling cancel() on the timer itself.
ok got it working, not sure if its the right way but its working ok. I just unregister the reciecer and register it again by calling the two methods "onPause() and onResume()" one after the other and just before the startScan() method. see code:
private Runnable Timer_Tick = new Runnable()
{
#Override
public void run()
{
try
{
// unRegister Receiver wifiReciever
onPause();
// register Receiver wifiReciever
onResume();
// start a scan of ap's
mainWifiObj.startScan();
}
catch (Exception e)
{
e.getStackTrace();
}
}
};
would love to know if this is correct way to do it.
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);
}}
Mobile number will be entered in an edittext by user on registration page in my Android application. How can I check that user entered his/her mobile number not other's ?
I've tried this :
TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number();
And compare this variable with edittext's text. But mPhoneNumber returns NULL in my case. Is there any other options? How to solve this ?
Any help would be appreciable.
I have tried this : Check source code :
public class MainActivity extends Activity{
Button submit;
EditText contact;
String phNo;
ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact = (EditText)findViewById(R.id.mobileNumber);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
phNo = contact.getText().toString();
new CheckOwnMobileNumber().execute();
Toast.makeText(getApplicationContext(), phNo, Toast.LENGTH_LONG).show();
}
});
}
private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
{
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
if(progress.isShowing())
{
progress.dismiss();
// Check SMS Received or not after that open dialog date
/*if(SMSReceiver.str.equals(phNo))
{
Toast.makeText(getApplicationContext(), "Thanks for providing your number.", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Provide your own mobile number please.", Toast.LENGTH_LONG).show();
return;
}*/
}
}
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
String msg = phNo;
try
{
sendSMS(phNo, msg);
}
catch(Exception ex)
{
Log.v("Exception :", ""+ex);
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
progress.setIndeterminate(true);
progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
}
private void sendSMS(String phoneNumber, String message)
{
//PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
Receiver to listen SMS received or not ?
public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
// Retrieve SMS
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
String action = intent.getAction();
if(action.equals(ACTION_SMS_RECEIVED))
{
SmsMessage[] msgs = getMessagesFromIntent(mIntent);
if (msgs != null)
{
for (int i = 0; i < msgs.length; i++)
{
address = msgs[i].getOriginatingAddress();
str = msgs[i].getMessageBody().toString();
}
}
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++)
{
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
LOGCAT :
03-13 17:31:02.049: E/ActivityManager(161): ANR in com.example.test
03-13 17:31:02.049: E/ActivityManager(161): Reason: Broadcast of Intent { act=android.provider.Telephony.SMS_RECEIVED cmp=com.example.test/.SMSReceiver (has extras) }
03-13 17:31:02.049: E/ActivityManager(161): 54% 3732/com.example.test: 54% user + 0% kernel / faults: 21 minor
03-13 17:31:02.049: E/ActivityManager(161): 40% 3732/com.example.test: 40% user + 0% kernel / faults: 2 minor
03-13 17:31:30.699: I/ActivityManager(161): Killing com.example.test (pid=3732): user's request
03-13 17:31:30.799: I/ActivityManager(161): Process com.example.test (pid 3732) has died.
03-13 17:31:30.799: I/WindowManager(161): WIN DEATH: Window{40992f50 com.example.test/com.example.test.MainActivity paused=false}
03-13 17:31:30.819: E/InputDispatcher(161): channel '40818670 com.example.test/com.example.test.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x8
03-13 17:31:30.819: E/InputDispatcher(161): channel '40818670 com.example.test/com.example.test.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
03-13 17:34:59.649: I/ActivityManager(161): Start proc com.example.test for broadcast com.example.test/.SMSReceiver: pid=4037 uid=10098 gids={}
Its not guaranteed that tMgr.getLine1Number(); will always return your SIM card's number. Because it depends on the availability of number in SIM card. Like in my case, my Tre-Sweden SIM card doesn't contain my phone number.
But if you put the SIM card into an old SonyEricsson or Nokia phone, then you would get an option to edit this number (on SIM). Once its done, the android device will recognize the number and will show you.
Besides, if you do get your phone number through the code, then the best way to compare two numbers is:
boolean isSame = PhoneNumberUtils.compare(num1, num2);
Alternatively, you may implement some sort of pin-code verification logic (like Viber, WhatsApp or other application does) in which you ask the user to enter their phone number during registration. Later, that phone number is sent to the server and a pin-code is generated against that number which is sent to the user via SMS. Finally, the user has to enter that pin-code (received in SMS) to complete the registration.
Or
Simply send an SMS from user's device (with a consent) to your server/device and get to know their phone number.
Getting the phone number using getLine1Number() is not secure nor certain.
It is generally accepted because this whole "getting the phone number" is clash of multiple issues such as user's privacy, carrier's branding, and even the vendor's.
Anyway, unlike ios, android's android.provider.Telephony.SMS_RECEIVED makes the whole process very convenient and seemless to the user: You get to capture the sms and read it without any need of the user's intervention.
What is one way of doing it?
On your server, upon receiving the request to verify a phone number, you should generate a secret code, tokenSent, and send it to the app. Now, your server should send this code by sms to the specified phone number. The app by now should have a registered receiver listening for the android.provider.Telephony.SMS_RECEIVED intent. Once received, the app verifies that the tokenSent is identical to what it received from the server. At this point, phone registration is done and the server can be notified.
What could go wrong?
Generally, such apps are usually paid apps and it is not the user's good to attempt anything. Still, the user might enter a wrong number which he right now has. Then upon receiving the sms, he could forward it to the mobile where the app is registering. The app will then receive the tokenSent and wrongly verify the phone number.
How can we tackle this?
The feasibility of the solution depends on whether the sms provider allows your server to know the sender's phone number. This is probably (AFAIK) not gonna happen but if it does then you're in luck. That way, the app can, upon receiving the tokenSent, send it back to the server along with the sender of the sms. The server then can verify that this is the sms that was originated from your service provider.
Any more feasible solution? (If I am really paranoid)
In this case, the best solution, I believe, would be to request a tokenSent from your server. The server saves a generated tokenSent along with the phone number entered and sends this token to the app. The app notifies the user that registration will cost him 1 sms. Once the user accepts, you can easily send an sms in the background containing this tokenSent to a certain service. The server, once receives this tokenSent verifies the user using the token and the sender of the sms. Of course, this may seem a bit harassing and infringing to the user but it is the most secure way especially for such a paranoid (reading this part).
Formalities :P
Add Permissions in Manifest
<uses-permission android:name="android.permission.RECEIVE_SMS">
Register the receiver (Do this just before you send the sms to the phone)
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null)
{
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String from = msgs[i].getOriginatingAddress();
String body = msgs[i].getMessageBody().toString();
//here is the body
//...
unregisterReceiver(this); //If you are done with verification
}
}
}
}, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
I solved it my self. Here is my working code.
MainActivity Class :
public class MainActivity extends Activity
{
Button submit;
EditText contact;
static String phNo;
ProgressDialog progress;
static Boolean wasMyOwnNumber;
static Boolean workDone;
final static int SMS_ROUNDTRIP_TIMOUT = 30000;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact = (EditText)findViewById(R.id.mobileNumber);
submit = (Button) findViewById(R.id.button1);
wasMyOwnNumber = false;
workDone = false;
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
phNo = contact.getText().toString();
new CheckOwnMobileNumber().execute();
}
});
}
private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
{
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
if(progress.isShowing())
{
progress.dismiss();
if(wasMyOwnNumber)
{
Toast.makeText(getApplicationContext(), "Number matched.", Toast.LENGTH_LONG).show();
wasMyOwnNumber = false;
workDone = false;
}
else
{
Toast.makeText(getApplicationContext(), "Wrong number.", Toast.LENGTH_LONG).show();
wasMyOwnNumber = false;
workDone = false;
return;
}
}
super.onPostExecute(result);
}
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
String msg = phNo;
try
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phNo, null, msg, null, null);
timeout();
}
catch(Exception ex)
{
Log.v("Exception :", ""+ex);
}
return null;
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
progress.setIndeterminate(true);
progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
}
private boolean timeout()
{
int waited = 0;
while (waited < SMS_ROUNDTRIP_TIMOUT)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
waited += 100;
if(phoneNumberConfirmationReceived())
{
waited=SMS_ROUNDTRIP_TIMOUT;
workDone = true;
}
}
/*Log.v("MainActivity:timeout2: Waited: " , ""+waited);
Log.v("MainActivity:timeout2:Comparision: ", ""+ phoneNumberConfirmationReceived());
Log.v("MainActivity:timeout2: WorkDone value after wait complete : ", ""+workDone);*/
return workDone;
}
private boolean phoneNumberConfirmationReceived()
{
if(wasMyOwnNumber)
{
workDone = true;
}
return workDone;
}
}
SMSReceiver Code :
public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
boolean isSame;
// Retrieve SMS
public void onReceive(Context context, Intent intent)
{
mContext = context;
mIntent = intent;
String action = intent.getAction();
if(action.equals(ACTION_SMS_RECEIVED))
{
SmsMessage[] msgs = getMessagesFromIntent(mIntent);
if (msgs != null)
{
for (int i = 0; i < msgs.length; i++)
{
address = msgs[i].getOriginatingAddress();
str = msgs[i].getMessageBody().toString();
}
}
Log.v("Originating Address : Sender :", ""+address);
Log.v("Message from sender :", ""+str);
isSame = PhoneNumberUtils.compare(str, MainActivity.phNo);
Log.v("Comparison :", "Yes this true. "+isSame);
if(isSame)
{
MainActivity.wasMyOwnNumber = isSame;
MainActivity.workDone=true;
}
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++)
{
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
No ANR found.
public class MainActivity extends Activity{
Button submit;
EditText contact;
String phNo;
ProgressDialog progress;
Boolean wasMyOwnNumber = false;
Boolean workDone = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact = (EditText)findViewById(R.id.mobileNumber);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
phNo = contact.getText().toString();
new CheckOwnMobileNumber().execute();
Toast.makeText(getApplicationContext(), phNo, Toast.LENGTH_LONG).show();
}
});
}
private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
{
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
if(progress.isShowing())
{
progress.dismiss();
// Check SMS Received or not after that open dialog date
/*if(SMSReceiver.str.equals(phNo))
{
Toast.makeText(getApplicationContext(), "Thanks for providing your number.", Toast.LENGTH_LONG).show();
wasMyOwnNumber=true;workDone=true;
}
else
{
Toast.makeText(getApplicationContext(), "Provide your own mobile number please.", Toast.LENGTH_LONG).show();
wasMyOwnNumber=false;workDone=true;
return;
}*/
}
}
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
String msg = phNo;
try
{
sendSMS(phNo, msg);
int count=0;
while(!workDone)
{count++;}
}
catch(Exception ex)
{
Log.v("Exception :", ""+ex);
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
progress.setIndeterminate(true);
progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
}
private void sendSMS(String phoneNumber, String message)
{
//PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
// Retrieve SMS
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
String action = intent.getAction();
if(action.equals(ACTION_SMS_RECEIVED))
{
SmsMessage[] msgs = getMessagesFromIntent(mIntent);
if (msgs != null)
{
for (int i = 0; i < msgs.length; i++)
{
address = msgs[i].getOriginatingAddress();
str = msgs[i].getMessageBody().toString();
}
}
// ---send a broadcast intent to update the SMS received in the
// activity---
workDone=true;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++)
{
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
}
Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.
In my case this method didn't returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me "Unknown".
This is probably because you have ported the number from one network to other.
If you are not able to check the number from API Then:
One way of doing that is you generate a text message to the Number and send a Random Generated no to the Mobile Number. You will have to ask the user to enter this Random generated number into your Application. Once it is entered in the application then you can send it onto the server to check whether the number passed in the text is correct or not (Which you have already saved on server against that mobile number).
I hope this makes sense.
Random string works fine.
Doesn't work check now.
I enter the text to what has been EditText drawn.
But the check is not working. Why?
Code:
public static StringBuffer random() {
String str = new String(
"G12HIJdefgPQRSTUVWXYZabc56hijklmnopqAB78CDEF0KLMNO3rstu4vwxyz9");
StringBuffer sb = new StringBuffer();
sb.toString();
String ar = null;
Random r = new Random();
int te = 0;
for (int i = 1; i <= 10; i++) {
te = r.nextInt(62);
ar = ar + str.charAt(te);
sb.append(str.charAt(te));
}
return sb;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
random = random().toString();
TextView display = (TextView) findViewById(R.id.textView1);
display.setText("Random Number: " + random); // Show the random number
et = (EditText) findViewById(R.id.etNumbers);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = et.getText().toString();
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "Bla bla bla", Toast.LENGTH_LONG)
.show();
}
if (random == charsEntered) {
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
}
Try
if (random.equalsIgnoreCase(charsEntered))
Use String.equals instead of ==
You're trying to compare two strings with the == operator. This cannot compare strings until Java 7, and Android is based on Java 6. Try using:
if (random.equalsIgnoreCase(charsEntered))
If the check is case insensitive or
if (random.equals(charsEntered))
If the check is case sensitive.
You are comparing StringBuffer Class with String Class, try following,
if ( random.toString().equals(charsEntered) )
{
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}