How to find steps with Google Fit API for Android? - java

I have done a couple of days of research regarding this. All I need is a Simple TextView area in my application to display today's steps.
I have managed to get the Authentication working with the code below. It pops up asks for permission and think I have the right one selected.
But I can not figure out how to simple gain the Step Count information. I hope this is only a couple of lines of code. Any help would be appreciated. Thanks
EDIT 1: I just need to get the Step count number. I can figure out how to display it later. I also have Toasts in just to help me figure out what is going on.
private void buildFitnessClient() {
if (mClient == null) {
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs.
Toast.makeText(getBaseContext(), "Connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
Toast.makeText(getBaseContext(), "Connection lost. Cause: Network Lost.", Toast.LENGTH_LONG).show();
} else if (i
== GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG,
"Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Google Play services connection failed. Cause: " +
result.toString());
Toast.makeText(getBaseContext(), "Google Play services connection failed. Cause: " +
result.toString(), Toast.LENGTH_LONG).show();
}
})
.build();
}
}

GoogleApiClient is deprecated according to the new updates. As well as the HistoryApi is also deprecated. So first have to use the GoogleSignInAccount instead of GoogleApiClient and also use HistoryClient of Google Fit instead of HistoryApi.
Setting Fitness Options
val fitnessOptions: GoogleSignInOptionsExtension = FitnessOptions.builder()
.addDataType(TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ).build()
Setting Google SignIn Option
val googleSignInOptions =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.addExtension(fitnessOptions).requestEmail().build()
val googleSignInClient = GoogleSignIn.getClient(requireActivity(), googleSignInOptions)
val signIntent = googleSignInClient.signInIntent
startActivityForResult(signIntent, 0)
Getting Account
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val account = task.getResult(ApiException::class.java)
if (account != null) {
getGoogleFitData(account)
}
}
}
Now for getting step data
val response: Task<DataReadResponse> =
Fitness.getHistoryClient(mContext, mSignInAccount)
.readData(
DataReadRequest.Builder()
.read(TYPE_STEP_COUNT_DELTA)
.setTimeRange(
startTime,
endTime,
TimeUnit.MILLISECONDS
)
.build()
)
val readDataResult: DataReadResponse? = Tasks.await(response)
val dataSet: DataSet = readDataResult!!.getDataSet(TYPE_STEP_COUNT_DELTA)
var total = 0
if (!dataSet.isEmpty) {
val dataPoints = dataSet.dataPoints
if (dataPoints.size > 0) {
for (i in 0 until dataPoints.size) {
total += dataSet.dataPoints[i].getValue(Field.FIELD_STEPS).asInt()
}
Log.e(TAG, "Total Steps : $total")
}
}
Here startTime and endTime are timemills of any date and time.
Thank You.

Check out this official documentation from Google on how to read the data from Fit:
// Setting a start and end date using a range of 1 week before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
java.text.DateFormat dateFormat = getDateInstance();
Log.i(TAG, "Range Start: " + dateFormat.format(startTime));
Log.i(TAG, "Range End: " + dateFormat.format(endTime));
DataReadRequest readRequest = new DataReadRequest.Builder()
// The data request can specify multiple data types to return, effectively
// combining multiple data queries into one call.
// In this example, it's very unlikely that the request is for several hundred
// datapoints each consisting of a few steps and a timestamp. The more likely
// scenario is wanting to see how many steps were walked per day, for 7 days.
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
// Analogous to a "Group By" in SQL, defines how data should be aggregated.
// bucketByTime allows for a time span, whereas bucketBySession would allow
// bucketing by "sessions", which would need to be defined in code.
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
History API Sample app on GitHub:
Check the sample project on GitHub here.
Direct link to MainActivity.java (in the above sample project) containing the required code: Link

Related

Firebase not getting new Data, after Android app was idle

Info:
I am doing an application where multiple Users need to work on one project. There are a few tasks that need to be completed.
Problem:
When a user turns off his screen, and turns it on around 5 minutes later (Or he went to the Homescreen or any other app for around 5 min ), firebase takes up to a Minute to get the new Data into the App (I have offline storing off btw). It frustrates the Users, because the Data needs to be up to date all the time so they can work with updated Tasks.
EDIT: THIS IS HAPPENING EVERYWHERE IN ALL IMPLEMENTATIONS LIKE THE EXAMPLE BELOW
Question:
Why is it like this?
How can I solve it???
EDIT: Example:
final FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference doc = db.collection("user").document(email).collection("dates").document(date);
doc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
HashMap CodeMap = (HashMap) document.getData();
Set keySet = CodeMap.keySet();
Object[] key = keySet.toArray();
for (int i = 0; i < keySet.size(); i++) {
if (!key[i].equals("clockIn") && !key[i].equals("clockOut") && !key[i].equals("completeTime") && !key[i].equals("clockPauseFrom") && !key[i].equals("clockPauseTo")) {
userWorkList.add(new User_Work_View_Row(key[i].toString(), email, date, i));
System.out.println(key[i] + " FOUND");
}
}
}else{
Log.d(TAG, "get failed with ", task.getException());
getActivity().finish();
}
}
}
});
SOLUTION:* (Kind of)
I have Implemented the solution of the answer below and did some Testing with the Battery options.
I found out that disabling Battery Optimizations and Background restrictions(if its even there) works! The Data is coming right away. I don't think its a good solution but it works for my App.
What you're observing is likely a result of an exponential backoff in the frequency of connection retries performed by the Firestore SDK. This backoff saves much battery compared to always retrying immediately in a tight loop.
If you want to force a retry, then you could try manually calling disableNetwork() followed by enableNetwork() to get it to retry immediately.

How to know if a value in firebase has increased or decreased?

I'm developing an android app in which there is this option to Follow/Unfollow a user. Whenever someone follows him, the counter in FirebaseDatabase gets increased by 1 and when someone unfollows him, the counter gets decreased by 1.
I'm trying to notify user every time someone follows him by starting a service as soon as he leave the app and writing the code in the Service.
Here's the code in onCreate() of the Service:
firebaseDatabaseFollowers.child("***").child("***").child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
b = sharedPref2.getBoolean(SettingsActivity.KEY_PREF_NOTIF_FOLLOW, true);
Toast.makeText(getBaseContext(), "b: " + String.valueOf(b), Toast.LENGTH_SHORT).show();
if (dataSnapshot.getValue() != null) {
if (String.valueOf(b).equals("true")) {
final int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationService());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);
}
} else {
Toast.makeText(getBaseContext(), "database is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The notification part is working fine. The only problem is that the notification is delivered even when someone unfollows the user and I don't want this to happen.
So, is there any way to know that if the counter in FirebaseDatabase increased or decreased so that I can notify accordingly?
Please let me know.
I would store a global variable in your app that holds the number of followers that the user currently has. When the database sends down new info, you can compare it to the number you have saved by using if new number > or < than saved number. This could be problematic, however, in case the user goes offline and comes back online after, say 1 user unfollowed and 2 others followed. In this case, the user would just get a +1 follower notification. What I might recommend is sending down the username of the user that followed, just like Instagram does. For example, "John Smith followed you!" or "James Smith unfollowed you!".

Google fit history API won't retrieve dataset?

I am currently trying to display today's current steps through my application. I have the following code below which Authenticates most of the time alright. I have added the SHA1 certificate to the developers console as well.
I keep getting the error "There was a problem inserting the dataset." in my log through with nothing else after that showing up and i'm a bit confused as to why?
Also this seems to be temperamental, sometimes it works and shows 7 data sets with random numbers (not my step count) so my second question is how do I get it to display just today's?
Authentication
private void buildFitnessClient() {
if (mClient == null) {
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs.
new InsertAndVerifyDataTask().execute();
}
#Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
Toast.makeText(getBaseContext(), "Connection lost. Cause: Network Lost.", Toast.LENGTH_LONG).show();
} else if (i
== GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG,
"Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Google Play services connection failed. Cause: " +
result.toString());
Toast.makeText(getBaseContext(), "Google Play services connection failed. Cause: " +
result.toString(), Toast.LENGTH_LONG).show();
}
})
.build();
}
}
Where I think the issue resides.
private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
//First, create a new dataset and insertion request.
DataSet dataSet = insertFitnessData();
// [START insert_dataset]
// Then, invoke the History API to insert the data and await the result, which is
// possible here because of the {#link AsyncTask}. Always include a timeout when calling
// await() to prevent hanging that can occur from the service being shutdown because
// of low memory or other conditions.
Log.i(TAG, "Inserting the dataset in the History API");
com.google.android.gms.common.api.Status insertStatus =
Fitness.HistoryApi.insertData(mClient, dataSet)
.await(1, TimeUnit.MINUTES);
// Before querying the data, check to see if the insertion succeeded.
if (!insertStatus.isSuccess()) {
Log.i(TAG, "There was a problem inserting the dataset.");
return null;
}
// At this point, the data has been inserted and can be read.
Log.i(TAG, "Data insert was successful!");
// [END insert_dataset]
// Begin by creating the query.
DataReadRequest readRequest = queryFitnessData();
// [START read_dataset]
// Invoke the History API to fetch the data with the query and await the result of
// the read request.
DataReadResult dataReadResult =
Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
// [END read_dataset]
// For the sake of the sample, we'll print the data so we can see what we just added.
// In general, logging fitness information should be avoided for privacy reasons.
printData(dataReadResult);
return null;
}
}
private DataSet insertFitnessData() {
Log.i(TAG, "Creating a new data insert request");
// [START build_insert_data_request]
// Set a start and end time for our data, using a start time of 1 hour before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();
// Create a data source
DataSource dataSource = new DataSource.Builder()
.setAppPackageName(this)
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setName(TAG + " - step count")
.setType(DataSource.TYPE_RAW)
.build();
// Create a data set
int stepCountDelta = 1000;
DataSet dataSet = DataSet.create(dataSource);
// For each data point, specify a start time, end time, and the data value -- in this case,
// the number of new steps.
DataPoint dataPoint = dataSet.createDataPoint()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
dataSet.add(dataPoint);
// [END build_insert_data_request]
return dataSet;
}
Got it working with the following code gets todays steps:
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 00);
long startTime = cal.getTimeInMillis();
int steps = 0;
DataSource ESTIMATED_STEP_DELTAS = new DataSource.Builder()
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setType(DataSource.TYPE_DERIVED)
.setStreamName("estimated_steps")
.setAppPackageName("com.google.android.gms").build();
// fill result with just the steps from the start and end time of the present day
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.AGGREGATE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(60, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
steps = totalSet.isEmpty() ? -1 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
}
s = String.valueOf(steps);
DataReadRequest readRequest = queryFitnessData();
DataReadResult dataReadResult =
Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
feedItemList.clear();
printData(dataReadResult);
return null;
Sometime, we also want to get data step in a specific time range, and here it's a reason in that case.
There're some probable causes:
1) Have you subscribed this type of data yet?
2) Your app doesn't connect properly with google service. Have you created OAuth Client ID from Google develop console? This's compulsory in instruction of google to connect to its GG Fit service (Please notice that, if you clone another app, on the same computer or not, you need to re-create another OAuth Client ID and one more thing you need 2 separated account, one to login Google develop console to create OAuth Client ID and one to sign in after starting your app, and it will ask you to sign in to accept its permission,... not sure why it's is, but it would work)
Note: Btw you can make a search about Google setting in your device (Setting --> Google), Here you can find which app connects to google service (including GG Fit service). I recommend you disconnect all and delete OAuth Client ID, your app, then re-create all of them!
Mttdat.

Get Mobile number from user device in android not using TeliphonecManager class TelephonyManager [duplicate]

How can I programmatically get the phone number of the device that is running my android app?
Code:
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
Required Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Caveats:
According to the highly upvoted comments, there are a few caveats to be aware of. This can return null or "" or even "???????", and it can return a stale phone number that is no longer valid. If you want something that uniquely identifies the device, you should use getDeviceId() instead.
There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).
I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.
Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.
There is actually an alternative solution you might want to consider, if you can't get it through telephony service.
As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.
Permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Code:
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
for (Account ac : accounts) {
String acname = ac.name;
String actype = ac.type;
// Take your time to look at all available accounts
System.out.println("Accounts : " + acname + ", " + actype);
}
Check actype for WhatsApp account
if(actype.equals("com.whatsapp")){
String phoneNumber = ac.name;
}
Of course you may not get it if user did not install WhatsApp, but its worth to try anyway.
And remember you should always ask user for confirmation.
So that's how you request a phone number through the Play Services API without the permission and hacks. Source and Full example.
In your build.gradle (version 10.2.x and higher required):
compile "com.google.android.gms:play-services-auth:$gms_version"
In your activity (the code is simplified):
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.CREDENTIALS_API)
.build();
requestPhoneNumber(result -> {
phoneET.setText(result);
});
}
public void requestPhoneNumber(SimpleCallback<String> callback) {
phoneNumberCallback = callback;
HintRequest hintRequest = new HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), PHONE_NUMBER_RC, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Logs.e(TAG, "Could not start hint picker Intent", e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHONE_NUMBER_RC) {
if (resultCode == RESULT_OK) {
Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
if (phoneNumberCallback != null){
phoneNumberCallback.onSuccess(cred.getId());
}
}
phoneNumberCallback = null;
}
}
This will generate a dialog like this:
As posted in my earlier answer
Use below code :
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
In AndroidManifest.xml, give the following permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.
Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!
Suggested Workaround:
Get the user's phone number as manual input from the user.
Send a code to the user's mobile number via SMS.
Ask user to enter the code to confirm the phone number.
Save the number in sharedpreference.
Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.
There is a new Android api that allows the user to select their phonenumber without the need for a permission. Take a look at:
https://android-developers.googleblog.com/2017/10/effective-phone-number-verification.html
// Construct a request for phone numbers and show the picker
private void requestHint() {
HintRequest hintRequest = new HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
apiClient, hintRequest);
startIntentSenderForResult(intent.getIntentSender(),
RESOLVE_HINT, null, 0, 0, 0);
}
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s != null && s.length() > 2 ? s.substring(2) : null;
}
Code taken from http://www.androidsnippets.com/get-my-phone-number
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".
Sometimes, below code returns null or blank string.
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
With below permission
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.
Try below code:
String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
main_data, "mimetype=?",
new String[]{"vnd.android.cursor.item/phone_v2"},
"is_primary DESC");
if (object != null) {
do {
if (!((Cursor) (object)).moveToNext())
break;
// This is the phoneNumber
String s1 = ((Cursor) (object)).getString(4);
} while (true);
((Cursor) (object)).close();
}
You will need to add these two permissions.
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
Hope this helps,
Thanks!
First of all getting users mobile number is against the Ethical policy, earlier it was possible but now as per my research there no solid solution available for this, By using some code it is possible to get mobile number but no guarantee may be it will work only in few device. After lot of research i found only three solution but they are not working in all device.
There is the following reason why we are not getting.
1.Android device and new Sim Card not storing mobile number if mobile number is not available in device and in sim then how it is possible to get number, if any old sim card having mobile number then using Telephony manager we can get the number other wise it will return the “null” or “” or “??????”
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
TelephonyManager tel= (TelephonyManager)this.getSystemService(Context.
TELEPHONY_SERVICE);
String PhoneNumber = tel.getLine1Number();
Note:- I have tested this solution in following device Moto x, Samsung Tab 4, Samsung S4, Nexus 5 and Redmi 2 prime but it doesn’t work every
time it return empty string so conclusion is it's useless
This method is working only in Redmi 2 prime, but for this need to add
read contact permission in manifest.
Note:- This is also not the guaranteed and efficient solution, I have tested this solution in many device but it worked only in Redmi 2 prime
which is dual sim device it gives me two mobile number first one is
correct but the second one is not belong to my second sim it belong to
my some old sim card which i am not using.
String main_data[] = {"data1", "is_primary", "data3", "data2", "data1",
"is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().
query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
main_data, "mimetype=?",
new String[]{"vnd.android.cursor.item/phone_v2"},
"is_primary DESC");
String s1="";
if (object != null) {
do {
if (!((Cursor) (object)).moveToNext())
break;
// This is the phoneNumber
s1 =s1+"---"+ ((Cursor) (object)).getString(4);
} while (true);
((Cursor) (object)).close();
}
In my research i have found earlier it was possible to get mobile number using WhatsApp account but now new Whatsapp version doesn’t storing user's mobile number.
Conclusion:- Android doesn’t have any guaranteed solution to get
user's mobile number programmatically.
Suggestion:- 1. If you want to verify user’s mobile number then ask to
user to provide his number, using otp you can can verify that.
If you want to identify the user’s device, for this you can easily get device IMEI number.
TelephonyManager is not the right solution, because in some cases the number is not stored in the SIM. I suggest that you should use the shared preference to store the user's phone number for the first time the application is open and the number will used whenever you need.
This is a more simplified answer:
public String getMyPhoneNumber()
{
return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getLine1Number();
}
Here's a combination of the solutions I've found (sample project here, if you want to also check auto-fill):
manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
build.gradle
implementation "com.google.android.gms:play-services-auth:17.0.0"
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var googleApiClient: GoogleApiClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tryGetCurrentUserPhoneNumber(this)
googleApiClient = GoogleApiClient.Builder(this).addApi(Auth.CREDENTIALS_API).build()
if (phoneNumber.isEmpty()) {
val hintRequest = HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build()
val intent = Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest)
try {
startIntentSenderForResult(intent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0);
} catch (e: IntentSender.SendIntentException) {
Toast.makeText(this, "failed to show phone picker", Toast.LENGTH_SHORT).show()
}
} else
onGotPhoneNumberToSendTo()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_PHONE_NUMBER) {
if (resultCode == Activity.RESULT_OK) {
val cred: Credential? = data?.getParcelableExtra(Credential.EXTRA_KEY)
phoneNumber = cred?.id ?: ""
if (phoneNumber.isEmpty())
Toast.makeText(this, "failed to get phone number", Toast.LENGTH_SHORT).show()
else
onGotPhoneNumberToSendTo()
}
}
}
private fun onGotPhoneNumberToSendTo() {
Toast.makeText(this, "got number:$phoneNumber", Toast.LENGTH_SHORT).show()
}
companion object {
private const val REQUEST_PHONE_NUMBER = 1
private var phoneNumber = ""
#SuppressLint("MissingPermission", "HardwareIds")
private fun tryGetCurrentUserPhoneNumber(context: Context): String {
if (phoneNumber.isNotEmpty())
return phoneNumber
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val subscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
try {
subscriptionManager.activeSubscriptionInfoList?.forEach {
val number: String? = it.number
if (!number.isNullOrBlank()) {
phoneNumber = number
return number
}
}
} catch (ignored: Exception) {
}
}
try {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val number = telephonyManager.line1Number ?: ""
if (!number.isBlank()) {
phoneNumber = number
return number
}
} catch (e: Exception) {
}
return ""
}
}
}
Add this dependency:
implementation 'com.google.android.gms:play-services-auth:18.0.0'
To fetch phone number list use this:
val hintRequest = HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build()
val intent = Credentials.getClient(context).getHintPickerIntent(hintRequest)
startIntentSenderForResult(
intent.intentSender,
PHONE_NUMBER_FETCH_REQUEST_CODE,
null,
0,
0,
0,
null
)
After tap on play services dialog:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent? {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PHONE_NUMBER_FETCH_REQUEST_CODE) {
data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)?.id?.let {
useFetchedPhoneNumber(it)
}
}
}
A little contribution. In my case, the code launched an error exception. I have needed put an annotation that for the code be run and fix that problem. Here I let this code.
public static String getLineNumberPhone(Context scenario) {
TelephonyManager tMgr = (TelephonyManager) scenario.getSystemService(Context.TELEPHONY_SERVICE);
#SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
return mPhoneNumber;
}
For android version >= LOLLIPOP_MR1 :
Add permission :
And call this :
val subscriptionManager =
getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
val list = subscriptionManager.activeSubscriptionInfoList
for (info in list) {
Log.d(TAG, "number " + info.number)
Log.d(TAG, "network name : " + info.carrierName)
Log.d(TAG, "country iso " + info.countryIso)
}
}
I noticed several answers posting the same thing. First of all things changed as per 2021, onActivityResult is deprecated. Here is the non-deprecated solution.
private fun requestHint() {
val hintRequest = HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build()
val intent = Credentials.getClient(this).getHintPickerIntent(hintRequest)
val intentSender = IntentSenderRequest.Builder(intent.intentSender).build()
val resultLauncher = registerForActivityResult(
ActivityResultContracts.StartIntentSenderForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val credential: Credential? = result.data?.getParcelableExtra(Credential.EXTRA_KEY)
// Phone number with country code
Log.i("mTag", "Selected phone No: ${credential?.id}")
}
}
resultLauncher.launch(intentSender)
}
Note: While many of you think this allows you to retrieve user's mobile phone number. That is usually not the case. Google Play Services has cached few phone numbers and sometimes the dialog shows phone numbers in which none belongs to user.
An important import com.google.android.gms.auth.api.credentials.Credential
Reference Documentation provides details but the code is somewhat deprecated.
Although it's possible to have multiple voicemail accounts, when calling from your own number, carriers route you to voicemail. So, TelephonyManager.getVoiceMailNumber() or TelephonyManager.getCompleteVoiceMailNumber(), depending on the flavor you need.
Hope this helps.
Wouldn't be recommending to use TelephonyManager as it requires the app to require READ_PHONE_STATE permission during runtime.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Should be using Google's Play Service for Authentication, and it will able to allow User to select which phoneNumber to use, and handles multiple SIM cards, rather than us trying to guess which one is the primary SIM Card.
implementation "com.google.android.gms:play-services-auth:$play_service_auth_version"
fun main() {
val googleApiClient = GoogleApiClient.Builder(context)
.addApi(Auth.CREDENTIALS_API).build()
val hintRequest = HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build()
val hintPickerIntent = Auth.CredentialsApi.getHintPickerIntent(
googleApiClient, hintRequest
)
startIntentSenderForResult(
hintPickerIntent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_PHONE_NUMBER -> {
if (requestCode == Activity.RESULT_OK) {
val credential = data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)
val selectedPhoneNumber = credential?.id
}
}
}
}
If I'm getting number from voiceMailNumer then it is working good -
val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
) {
Log.d("number", telephonyManager.voiceMailNumber.toString())
}
Firstly Initalize your sign in Intent like this
private val signInIntent = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
try {
val phoneNumber = Identity.getSignInClient(requireContext()).getPhoneNumberFromIntent(result.data)
// Note phone number will be in country code + phone number format
} catch (e: Exception) {
}
}
To open google play intent and show phone number associated with google account use this
val phoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder()
.build()
Identity.getSignInClient(requireContext())
.getPhoneNumberHintIntent(phoneNumberHintIntentRequest)
.addOnSuccessListener { pendingIntent ->
signInIntent.launch(IntentSenderRequest.Builder(pendingIntent).build())
}.addOnFailureListener {
it.printStackTrace()
}
Note:
This will fail if user is disabled phone number sharing. If is it so user have to enable that from Settings -> Google -> Auto-fill -> Phone Number sharing
This will not working if you are using emulated device where play services is not available
while working on a security app which needed to get the phone number of who so ever my phone might get into their hands, I had to do this;
1. receive Boot completed and then try getting Line1_Number from telephonyManager which returns a string result.
2. compare the String result with my own phone number and if they don't match or string returns null then,
3. secretly send an SMS containing the string result plus a special sign to my office number.
4. if message sending fails, start a service and keep trying after each hour until sent SMS pending intent returns successful.
With this steps I could get the number of the person using my lost phone.
it doesn't matter if the person is charged.

Android - add table rows after table loading

I am reading UDP packets and i wanna display that info on UI as table in android app.
Here is my code,
try {
byte buffer[] = new byte[10000];<br/>
InetAddress address = InetAddress.getByName("192.168.xx.xx");<br/>
int port = xxx;<br/>
Log.d("..........","What will Happen ?? ");<br/>
for(int k=0;k<50;k++) { // 50 rows are added , This i wanna make it 5000+ rows so it takes plenty of time to load that table <br/>
DatagramPacket p = new DatagramPacket(buffer, buffer.length, address, port);<br/>
DatagramSocket ds = new DatagramSocket(port);<br/>
Log.d("..........","Perfect Binding .... Waiting for Data");<br/>
ds.receive(p);<br/>
Log.d("..........","Packet Received");<br/>
byte[] data = p.getData();<br/>
String result = "";<br/>
int b[] = new int[data.length];</br>
for (int i=0; i < 150; i++) {<br/>
result += Integer.toString( ( data[i] & 0xff ) + 0x100, 16).substring( 1 );<br/>
result += "_";<br/>
}<br/>
Log.d("Result => ",result); <br/>
TableLayout tl=(TableLayout)findViewById(R.id.TableLayout01);<br/>
TableRow tr=new TableRow(this);
TextView tv= new TextView(this);
TextView tv2 = new TextView(this);
tv.setPadding(5, 0, 5, 0);
tv2.setPadding(5,0,5,0);
String k1 = Integer.toString(k);
tv.setText(k1);
tv2.setText(it_version);
tr.addView(tv);
tr.addView(tv2);
tl.addView(tr,1);
ds.close();
}
} catch (Exception e) {
Log.e("UDP", "Client error", e);
}
If i keep 50 rows am able to display it properly without any time delay, if i put 3000 rows its taking too long time and sometimes app is hanging... I wanna add 50 entries to a table and load the table and again read 50 entries and append to the table without touching any button or anything so i have a table in UI and it will update automatically by reading UDP packets ... how i can achieve that ?? Any clue appreciated.
or once i read the UDP packet i wanna display it on UI[appending to the table],How i can do this ??[Scrolling and all i will take care] please let me know
I already tried using threads but no use
Basically, you need to implement an infinite listview. There are a couple strategies to do this:
You can get all the data and store it in a database and only show the user 50 at a time.
You can fetch only 50 at first and then fetch the next 50 when the user scrolls past them.
You can fetch 100, show 50 and then show next 50 when the user scrolls past the first 50. Pre-fetch the next 100 to show next and so on.
Once you figured out your fetching strategy, you need to implement the actual adapter and listview. Here's a good technique to do this. I would recommend that you don't re-invent the wheel and use this great library called EndlessAdapter unless you want to implement it for learning purposes.
Something like this is what you might use in order to get a infinite list effect when you don't have a cursor.
Please note this is a very rough draft since I deleted the code only relevant to my app, to help for you clarity, and for my privacy and the apps privacy. Also it may not be the best way of doing everything, but it worked the first time I wrote it (which took like 10 minutes) and worked beautifully for a very complex list, so I haven't bothered coming back to it.
class AsyncGetUpdates extends AsyncTask<Void, Void, List<UpdateDTO>>
{
#Override
protected void onPreExecute()
{
showDialog();
super.onPreExecute();
}
#Override
protected List<UpdateDTO> doInBackground(Void... params)
{
return APIHelper.getUpdates(count);
}
#Override
protected void onPostExecute(List<UpdateDTO> result)
{
killDialog();
isCurrentlyUpdating = false;
setAdapterData(result);
super.onPostExecute(result);
}
}
public void setAdapterData(List<UpdateDTO> result)
{
killDialog();
if (this != null && this.getActivity() != null)
{
Log.d(TAG, "setAdapterData");
if (lvUpdatesList.getAdapter() != null)
{
// save index and top position
int index = lvUpdatesList.getFirstVisiblePosition();
View v = lvUpdatesList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
updateListAdapter = new UpdateListAdapter(this.getActivity().getLayoutInflater(), result, this);
lvUpdatesList.setAdapter(updateListAdapter);
lvUpdatesList.refreshDrawableState();
lvUpdatesList.setSelectionFromTop(index, top);
}
else
{
updateListAdapter = new UpdateListAdapter(this.getActivity().getLayoutInflater(), result, this);
lvUpdatesList.setAdapter(updateListAdapter);
lvUpdatesList.refreshDrawableState();
}
}
// add in a listener to know when we get to the bottom
lvUpdatesList.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
// we do not want to update if we already are
if (isCurrentlyUpdating == false)
{
if (lvUpdatesList.getAdapter() != null && lvUpdatesList.getAdapter().getCount() == count)
{
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount)
{
isCurrentlyUpdating = true;
// add to the count of views we want loaded
count += 20;
// start a update task
new AsyncGetUpdates().execute();
}
}
}
}
});
}
Finally I would like to say that copy pasting might get you the results you want, but it will hinder you future ability. I would say study, read, learn, try, fail, and try again.

Categories