android ActivityRecognition not calling onHandleIntent - android

I have put together this piece of code to get the users activity, to see is he walking or driving or still, but its not working, onHandleIntent never called. it is connecting to GoogleApiClient.
Here is my code
Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/msg" />
MainActivity
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Context mContext;
private GoogleApiClient mGApiClient;
private BroadcastReceiver receiver;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get the textview
textView = (TextView) findViewById(R.id.msg);
//Set the context
mContext = this;
//Check Google Play Service Available
if(isPlayServiceAvailable()) {
mGApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//Connect to gPlay
mGApiClient.connect();
}else{
Toast.makeText(mContext, "Google Play Service not Available", Toast.LENGTH_LONG).show();
}
//Broadcast receiver
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String v = "Activity :" +
intent.getStringExtra("act") + " " +
"Confidence : " + intent.getExtras().getInt("confidence") + "n";
v += textView.getText();
textView.setText(v);
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("SAVVY");
registerReceiver(receiver, filter);
}
private boolean isPlayServiceAvailable() {
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext) == ConnectionResult.SUCCESS;
}
#Override
public void onConnected(Bundle bundle) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecongPendingIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d("Saquib", "connected to ActRecog " + "PI " +mActivityRecongPendingIntent.toString() );
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGApiClient, 0, mActivityRecongPendingIntent);
}
#Override
public void onConnectionSuspended(int i) {
Log.d("Saquib", "suspended to ActRecog");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("Saquib", "Not connected to ActRecog");
}
#Override
protected void onDestroy() {
super.onDestroy();
mGApiClient.disconnect();
unregisterReceiver(receiver);
}
}
ActivityRecognitionIntentService
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
/**
* Created by tutsberry on 17/03/15.
*/
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
if(ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity detectedActivity = result.getMostProbableActivity();
int confidence = detectedActivity.getConfidence();
String mostProbableName = getActivityName(detectedActivity.getType());
Intent i = new Intent("SAVVY");
i.putExtra("act", mostProbableName);
i.putExtra("confidence", confidence);
Log.d("Saquib", "mostProbableName " + mostProbableName);
Log.d("Saquib", "Confidence : " + confidence);
//Send Broadcast
this.sendBroadcast(i);
}else {
Log.d("Saquib", "Intent had no data returned");
}
}
private String getActivityName(int type) {
switch (type)
{
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.WALKING:
return "walking";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.TILTING:
return "tilting";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.RUNNING:
return "running";
}
return "n/a";
}
}
and manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutsberry.moveyours" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ActivityRecognitionIntentService">
</service>
</application>
</manifest>
Guys please help, google doc is no use for ActivityRecognition

Maybe you are missing the
<uses-permission android:name="android.permission.INTERNET" />

Make sure that you are connected to the internet beforehand. I think otherwise it will not work. The first time you connect to google play services you must be connected to the internet.

Related

How to detect phone state broadcast reciever while app is closed in android "Pie"

I am trying to get phone state using TelephoneManager class and using a job scheduler i have assigned a listener for onCallStateChangeListener() ... but still android 9 "Pie" kills every background task like my listener and jobScheduler ! so how can i solve this problem and get phone state while my app is in totally closed !
Note : I tried an app like Truecaller and it works just fine after closing the app! how can i get similar behavior on my app ?
MainActivity.java
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int JOB_ID = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleJob();
}
public void scheduleJob() {
ComponentName componentName = new ComponentName(this, ExampleJobService.class);
JobInfo info = new JobInfo.Builder(JOB_ID , componentName)
.setPersisted(true)
.setPeriodic(15 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
public void cancelJob() {
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(123);
Log.d(TAG, "Job cancelled");
}
}
JobScheduler.java
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class ExampleJobService extends JobService {
private static final String TAG = "ExampleJobService";
boolean quitLooper;
TelephonyManager telephonyManager;
public void checkForIncomingCalls() {
telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
new Thread(new Runnable() {
#Override
public void run() {
quitLooper = false;
Looper.prepare();
PhoneStateListener callStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String phoneNumber) {
if(state==TelephonyManager.CALL_STATE_RINGING){
Toast.makeText(getApplicationContext(),"Phone Is Riging",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_OFFHOOK){
Toast.makeText(getApplicationContext(),"Phone is Currently in A call",
Toast.LENGTH_LONG).show();
}
if(state==TelephonyManager.CALL_STATE_IDLE){
Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call",
Toast.LENGTH_LONG).show();
}
}
};
telephonyManager.listen(callStateListener , PhoneStateListener.LISTEN_CALL_STATE);
Looper.loop();
}
}).start();
}
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
#Override
public void run() {
checkForIncomingCalls();
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
}).start();
}
#Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
return true;
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.devteam.test231">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ExampleJobService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
Thanks!

Android Geofece Exit/Enter in geofence Events not triggerring

I am stuk with this issue for more than a week.Goefence events not triggering on entering or existing the Geofence. i have tested it several times on emulater.
Here is my MainActivity
**
package com.example.internet.ytgeofence;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.Api;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
GoogleApiClient googleApiClient = null;
protected ArrayList<Geofence> mGeofenceList;
private Context mContext ;
Button startLocationMonitoring, startGeofenceMonitoring, stopGeofenceMonitoring;
TextView t;
public List<Geofence> listGeofence;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*int resultCode =
GooglePlayServicesUtil.
isGooglePlayServicesAvailable(this);*/
mGeofenceList = new ArrayList<Geofence>();
startLocationMonitoring = (Button) findViewById(R.id.button2);
startGeofenceMonitoring = (Button) findViewById(R.id.button3);
stopGeofenceMonitoring = (Button) findViewById(R.id.button4);
t = (TextView) findViewById(R.id.textView2);
mContext=getApplicationContext();
startLocationMonitoring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartLocationMonitoring();
}
});
startGeofenceMonitoring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartGeofenceMonitoring();
}
});
stopGeofenceMonitoring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StopGeofenceMonitoring();
}
});
googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "Connected to google Api Client");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "suspended connection to google Api Client");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "Failed to connect to google api client" + connectionResult.getErrorMessage());
}
}).build();
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1234);
googleApiClient.connect();
}
#Override
protected void onStart() {
Log.d(TAG, "On start Called");
Toast.makeText(this,"On start called" ,Toast.LENGTH_LONG).show();
super.onStart();
googleApiClient.reconnect();
}
#Override
protected void onStop() {
Log.d(TAG, "On stop Called");
super.onStop();
googleApiClient.disconnect();
}
#Override
protected void onResume() {
Log.d(TAG, "On Resume Called");
super.onResume();
int response = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (response != ConnectionResult.SUCCESS) {
Log.d(TAG, "Google Paly Services not avaliable.show dialouge to download");
GoogleApiAvailability.getInstance().getErrorDialog(this, response, 1).show();
} else {
Log.d(TAG, "Google Paly Services avaliable");
}
}
private void StartLocationMonitoring() {
Log.d(TAG, "Location Monitoring Start");
try {
LocationRequest locationRequest = LocationRequest.create()
.setInterval(10000)
.setFastestInterval(5000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
t = (TextView) findViewById(R.id.textView2);
t.setText("Lat:" + location.getLatitude() + "Lng" + location.getLongitude());
Log.d(TAG, "Location Lat/Lng" + location.getLongitude() + " " + location.getLongitude());
}
});
} catch (Exception ex) {
Log.d(TAG, "Exception in location Monitoring" + ex.toString());
}
}
private void StartGeofenceMonitoring() {
Geofence geofence = new Geofence.Builder().setRequestId("SAN Loaction")
.setCircularRegion(48.848016, 2.346888, 200)
.setExpirationDuration(Geofence.NEVER_EXPIRE).setNotificationResponsiveness(1000)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT).build();
mGeofenceList.add(geofence);
GeofencingRequest geofencingRequest = getGeofencingRequest();
Intent intent = new Intent(MainActivity.this, GeofenceService.class);
PendingIntent pendingIntent = PendingIntent.getService(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
if (!googleApiClient.isConnected()) {
Log.d(TAG, "Google API Client Not Connected");
Toast.makeText(getApplicationContext()
,"Google api client not connected",Toast.LENGTH_LONG);
} else {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.GeofencingApi.addGeofences(googleApiClient, geofencingRequest, pendingIntent).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess())
{
Log.d(TAG,"Geofence added Successfully");
Toast.makeText(getApplicationContext(),"Geo fence added successfully",Toast.LENGTH_LONG).show();
}
else
{
Log.d(TAG,"Failed to add Geofence"+status.getStatus());
Toast.makeText(getApplicationContext(),"Geofence not added successfully",Toast.LENGTH_LONG);
}
}
});
}
}catch (SecurityException ex)
{
Log.d(TAG," Security Exception in api client");
Toast.makeText(getApplicationContext(),"Geofence not added successfully"+ex.toString(),Toast.LENGTH_LONG);
}
}
private void StopGeofenceMonitoring(){
Log.d(TAG,"Stop geofence called");
ArrayList<String> geofenceids=new ArrayList<String>();
geofenceids.add("SAN Loaction");
LocationServices.GeofencingApi.removeGeofences(googleApiClient,geofenceids);
}
private GeofencingRequest getGeofencingRequest() {
Log.d(TAG,"Inside Getgeofencing request");
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
}
The Activity_main.xaml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.internet.ytgeofence.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/textView" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_marginLeft="59dp"
android:layout_marginStart="59dp"
android:layout_marginTop="75dp"
android:layout_toEndOf="#+id/textView"
android:layout_toRightOf="#+id/textView"
android:text="Start Location Monitoring" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="22dp"
android:text="Start Geofence Monitoring" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button3"
android:layout_alignStart="#+id/button3"
android:layout_centerVertical="true"
android:text="Stop Geofence Monitoring" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="104dp"
android:text="Status" />
The GeofenceService is
package com.example.internet.ytgeofence;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import java.util.List;
public class GeofenceService extends IntentService {
public static final String TAG="GeofenceService";
public GeofenceService() {
super(TAG);
Toast.makeText(this,"Inside Service",Toast.LENGTH_LONG).show();
Log.d(TAG,"Inside Service Constructer");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d(TAG,"Inside IntentHandler");
GeofencingEvent event=GeofencingEvent.fromIntent(intent);
if(event.hasError())
{
}
else
{
int transition=event.getGeofenceTransition();
List<Geofence> geofences=event.getTriggeringGeofences();
Geofence geofence=geofences.get(0);
String RequestID=geofence.getRequestId();
if(transition==Geofence.GEOFENCE_TRANSITION_ENTER)
{
Log.d(TAG,"Entering Geofence Area"+RequestID);
Toast.makeText(this,"Entering Geofence Area",Toast.LENGTH_LONG);
}
else if(transition==Geofence.GEOFENCE_TRANSITION_ENTER)
{
Log.d(TAG,"Exiting Geofence Area"+RequestID);
Toast.makeText(this,"Exiting Geofence Area",Toast.LENGTH_LONG);
}
}
}
}
And the Manifest.xaml is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internet.ytgeofence">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GeofenceService"/>
</application>
Any Help is Highly Apperciated.
Your code is fine just use real device, and enable GPS, also give app location permission, that set, I use emulater before it's not worked with me.
Update
I try your code, there is some point to fix this issue, first add this code in manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- add this -->
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".MainActivity">
in your service remove Toast and use log just because it's crashing app, this is the result
I add GeofencingRequest.INITIAL_TRIGGER_EXIT for GeofencingRequest just to ensure it will work perfectly
private GeofencingRequest getGeofencingRequest() {
Log.d(TAG,"Inside Getgeofencing request");
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT);
builder.addGeofences(mGeofenceList);
return builder.build();
}
in the manifest I add this permission -I think you already add it, put just in case- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Android Service With Google Play Services Location Causing App to Open Randomly

I have a service which should capture the user's location and current battery level and send it to my firebase backend. For some reason it seems like whenever I have this service enabled in my app, my app will randomly open without any user interaction (even if the user is in another app, my app will pop open). Does anyone have any idea why this is happening?
Here is my code for the service:
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.server.converter.StringToIntConverter;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static android.R.attr.lines;
import static com.package.R.id.location;
import static com.package.R.id.view;
public class LocationBatteryService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private String currentUser;
private String city;
private String country;
private float batteryLevel;
private int batteryLevelInt;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
List<Address> addresses;
Geocoder geocoder;
#Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected synchronized void buildGoogleApiClient() {
Log.i("TAG", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String locationSyncSettings = prefs.getString("location_sync_time", "");
long intervalTime = 5;
if(locationSyncSettings.equals("5 minutes")) {
intervalTime = 5;
}
if (locationSyncSettings.equals("10 minutes")) {
intervalTime = 10;
}
if (locationSyncSettings.equals("15 minutes")) {
intervalTime = 15;
}
if (locationSyncSettings.equals("30 minutes")) {
intervalTime = 30;
}
if (locationSyncSettings.equals("1 hour")) {
intervalTime = 60;
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(TimeUnit.MINUTES.toMillis(intervalTime));
mLocationRequest.setFastestInterval(60000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i("TAG", "Connected to GoogleApiClient");
try {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
onLocationChanged(mCurrentLocation);
}
catch (SecurityException e){
Log.d("TAG", "Error: " + e);
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("TAG", "You got destoryed mate");
}
#Override
public void onLocationChanged(Location location) {
updateLocationBackend(mCurrentLocation);
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i("TAG", "Connection suspended");
mGoogleApiClient.connect();
}
public void onTaskRemoved (Intent rootIntent){
this.stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i("TAG", "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
public float getBatteryLevel() {
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
// Error checking that probably isn't needed but I added just in case.
if(level == -1 || scale == -1) {
return 50.0f;
}
return ((float)level / (float)scale) * 100.0f;
}
private void updateLocationBackend(final Location location) {
Log.i("TAG", "Location and battery being updated");
batteryLevel = getBatteryLevel();
batteryLevelInt = Math.round(batteryLevel);
// Get current user
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
currentUser = sharedPrefs.getString("Username", "");
// Get users added by you
DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(Passwords.FB_URL).child("Relations").child(currentUser);
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
for (DataSnapshot ds : dataSnapshot.getChildren()) {
final String contactNumber = ds.getKey();
// Check to see if users added you
final DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(Passwords.FB_URL).child("Contacts").child(contactNumber).child(currentUser);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child("name").exists()) {
// User has not added you so do not update location
}
// User has added you so update location
else {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean contactLocationSetting = sharedPrefs.getBoolean(contactNumber + "_location_pref", true);
Log.d("TAG", "ContactLocationSetting for " + contactNumber + " is equal to: " + contactLocationSetting);
if (location != null && contactLocationSetting == true) {
Map updateLocation = new HashMap();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
Log.e("TAG", "error is: " + e);
}
if (addresses.size() == 0) {
// Do nothing
} else {
city = addresses.get(0).getLocality();
country = addresses.get(0).getCountryName();
// String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
}
updateLocation.put("battery", batteryLevelInt);
updateLocation.put("latitude", latitude);
updateLocation.put("longitude", longitude);
updateLocation.put("city", city);
updateLocation.put("country", country);
updateLocation.put("lastUpdated", System.currentTimeMillis());
ref.updateChildren(updateLocation);
Log.d("TAG", "Updated location for: " + contactNumber);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG", "getUser:onCancelled", databaseError.toException());
}
});
}
}
Here is the code where I start the service:
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
public static ViewPager viewPager;
public static ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String currentUser = sharedPrefs.getString("Username", null);
if (currentUser == null) {
// Take user to log in screen
Log.d("TAG", "user needs to login");
Intent intent = new Intent(this, MyIntro.class);
startActivity(intent);
finish();
}
else {
// User already logged in
setupMainActivity();
}
}
#Override
public void onResume() {
super.onResume();
return;
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ChalkboardFragment(), getString(R.string.chalkboard_label));
adapter.addFragment(new ContactsFragment(), getString(R.string.contacts_label));
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChalkboardFragment();
case 1:
return new ContactsFragment();
}
return null;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setupMainActivity() {
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean locationSetting = prefs.getBoolean("location_pref", false);
Log.d("TAG", "location_pref " + locationSetting);
if (isMyServiceRunning(LocationBatteryService.class) == false && locationSetting == true) {
startService(new Intent(this, LocationBatteryService.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Application Start:
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.digits.sdk.android.Digits;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterCore;
import io.fabric.sdk.android.Fabric;
public class ApplicationStart extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this.getApplicationContext();
/*if (!FirebaseApp.getApps(this).isEmpty()) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}*/
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String currentUser = sharedPrefs.getString("Username", null);
if (currentUser == null) {
// Take user to log in screen
Log.d("TAG", "user needs to login");
Intent intent = new Intent(this, MyIntro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
// User already logged in
Log.d("TAG", "user logged in: " + currentUser);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY,TWITTER_SECRET);
Fabric.with(this, new TwitterCore(authConfig),new Digits.Builder().build());
}
public static Context getAppContext(){
return mContext;
}
}
Complete manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" android:protectionLevel="signature" />
<application android:name=".ApplicationStart" android:allowBackup="false" android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" android:supportsRtl="true" android:theme="#style/AppTheme">
<activity android:name=".MainActivity" android:label="#string/app_name" android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity" android:label="#string/title_activity_login"
android:parentActivityName=".MainActivity" />
<activity android:name=".ContactsSettingsActivity" android:label="Contact Settings"
android:launchMode="singleTop">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.ContactsChalkboard" />
</activity>
<activity android:name=".MyIntro" />
<activity android:name=".ContactsChalkboard" />
<activity android:name=".AlarmActivity" />
<activity android:name=".AddContactActivity" android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.MainActivity" />
</activity>
<activity android:name=".PictureNameActivity" android:label="#string/title_activity_picture_name"
android:parentActivityName=".LoginActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.LoginActivity" />
</activity>
<activity android:name=".Test" />
<activity android:name=".SettingsActivity" android:label="Settings">
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.package.MainActivity" />
</activity>
<activity android:name="com.package.GeofenceActivity" android:label="#string/title_activity_geofence">
</activity>
<service android:name=".LocationBatteryService" android:enabled="true" android:exported="true" />
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".GeofenceTransitionsIntentService" />
<receiver android:name=".AlarmReceiver" android:enabled="true" android:exported="true" />
<receiver android:name=".BootReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.android.geo.API_KEY" android:value="API KEY VALUE" />
<meta-data android:name="io.fabric.ApiKey" android:value="API KEY VALUE" />
</application>
</manifest>
Well, there is no guarantee that the system keeps running your service all the time. When the application is killed, and a new location has to be delivered the play services lib will instantiate the application and start your service. You have to remove startActivity from your application class.

how to use ussdinterceptor in android

How to use ussdinterceptor service in android is question which is asked a lot. and the responses for it are poor.
this is my response.
first the service it self.
classes for the package com.example.ussdcodes
BootReceiver.java
package com.example.ussdcodes;
//import com.example.ussdcodes.R;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("USSDService", context.getString(R.string.service_started));
context.startService(new Intent(context,USSDDumbExtendedNetworkService.class));
}
}
USSDDumbExtendedNetworkService.java
package com.example.ussdcodes;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.os.PatternMatcher;
import android.os.RemoteException;
import android.util.Log;
import com.android.internal.telephony.IExtendedNetworkService;
//import com.android.internal.telephony.IExtendedNetworkService;
import com.example.ussdcodes.R;
/**
* Service implements IExtendedNetworkService interface.
* USSDDumbExtendedNetworkService
* Service must have name "com.android.ussd.IExtendedNetworkService" of the intent declared
* in the Android manifest file so com.android.phone.PhoneUtils class bind
* to this service after system rebooted.
* Please note service is loaded after system reboot!
* Your application must check is system rebooted.
* #see Util#syslogHasLine(String, String, String, boolean)
*/
public class USSDDumbExtendedNetworkService extends Service {
public static final String TAG = "CommandusUSSDExtNetSvc";
public static final String LOG_STAMP = "*USSDTestExtendedNetworkService bind successfully*";
public static final String URI_SCHEME = "ussdcodes";
public static final String URI_AUTHORITY = "android.com";
public static final String URI_PATH = "/";
public static final String URI_PAR = "return";
public static final String URI_PARON = "on";
public static final String URI_PAROFF = "off";
public static final String MAGIC_ON = ":ON;)";
public static final String MAGIC_OFF = ":OFF;(";
public static final String MAGIC_RETVAL = ":RETVAL;(";
public static final String RESULT = "result";
private static boolean mActive = true;
private static CharSequence mRetVal = null;
private Context mContext = null;
private String msgUssdRunning = "USSD running...";
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_INSERT.equals(intent.getAction())) {
mContext = context;
if (mContext != null) {
msgUssdRunning = mContext.getString(R.string.USSD_run);
mActive = true;
Log.d(TAG, "activate");
}
} else if (Intent.ACTION_DELETE.equals(intent.getAction())) {
mContext = null;
mActive = false;
Log.d(TAG, "deactivate");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {
#Override
public void setMmiString(String number) throws RemoteException {
Log.d(TAG, "setMmiString: " + number);
Intent intent =new Intent("com.example.ussdcodes.setmmistring") ;
intent.putExtra("ussdCode", number);
sendBroadcast(intent);
}
#Override
public CharSequence getMmiRunningText() throws RemoteException {
Log.d(TAG, "getMmiRunningText: " + msgUssdRunning);
return msgUssdRunning;
}
#Override
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
/* if (MAGIC_ON.contentEquals(text)) {
mActive = true;
Log.d(TAG, "control: ON");
return text;
} else {
if (MAGIC_OFF.contentEquals(text)) {
mActive = false;
Log.d(TAG, "control: OFF");
return text;
} else {
if (MAGIC_RETVAL.contentEquals(text)) {
mActive = false;
Log.d(TAG, "control: return");
return mRetVal;
}
}
}
if (!mActive) {
Log.d(TAG, "getUserMessage deactivated: " + text);
return text;
} */
String s = text.toString();
// store s to the !
Uri uri = new Uri.Builder()
.scheme(URI_SCHEME)
.authority(URI_AUTHORITY)
.path(URI_PATH)
.appendQueryParameter(URI_PAR, text.toString())
.build();
// Intent intent =new Intent(Intent.ACTION_GET_CONTENT, uri) ;
// Intent intent =new Intent("com.example.ussdcodes", uri) ;
Intent intent =new Intent("com.example.ussdcodes.getusermsg") ;
intent.putExtra("result", s);
sendBroadcast(intent);
mActive = false;
mRetVal = text;
Log.d(TAG, "getUserMessage: " + text + "=" + s);
return null;
}
#Override
public void clearMmiString() throws RemoteException {
Log.d(TAG, "clearMmiString");
}
};
/**
* Put stamp to the system log when PhoneUtils bind to the service
* after Android has rebooted. Application must call {#link Util#syslogHasLine(String, String, String, boolean)} to
* check is phone rebooted or no. Without reboot phone application does not bind tom this service!
*/
#Override
public IBinder onBind(Intent intent) {
// Do not localize!
Log.i(TAG, LOG_STAMP);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(URI_SCHEME);
filter.addDataAuthority(URI_AUTHORITY, null);
filter.addDataPath(URI_PATH, PatternMatcher.PATTERN_LITERAL);
registerReceiver(mReceiver, filter);
return mBinder;
}
public IBinder asBinder() {
Log.d(TAG, "asBinder");
return mBinder;
}
}
the aidl for com.android.internal.telephony
IExtendedNetworkService.aidl
package com.android.internal.telephony;
/**
* Interface used to interact with extended MMI/USSD network service.
*/
interface IExtendedNetworkService {
/**
* Set a MMI/USSD command to ExtendedNetworkService for further process.
* This should be called when a MMI command is placed from panel.
* #param number the dialed MMI/USSD number.
*/
void setMmiString(String number);
/**
* return the specific string which is used to prompt MMI/USSD is running
*/
CharSequence getMmiRunningText();
/**
* Get specific message which should be displayed on pop-up dialog.
* #param text original MMI/USSD message response from framework
* #return specific user message correspond to text. null stands for no pop-up dialog need to show.
*/
CharSequence getUserMessage(CharSequence text);
/**
* Clear pre-set MMI/USSD command.
* This should be called when user cancel a pre-dialed MMI command.
*/
void clearMmiString();
}
the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ussdcodes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.example.ussdcodes.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".USSDDumbExtendedNetworkService" >
<intent-filter android:icon="#drawable/ic_launcher">
<action android:name="com.android.ussd.IExtendedNetworkService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
</manifest>
now the activity that uses the service (don't forgot to reboot the phone after installing the service)
MainActivity.java
package com.example.usingussdservice;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
UssdMsg ussdMsg = new UssdMsg();
UssdsetMmi ussdsetMmi = new UssdsetMmi();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ussdMsg.setMainActivityHandler(this);
ussdsetMmi.setMainActivityHandler(this);
// com.example.ussdcodes
IntentFilter fltr_ussdmsg = new IntentFilter("com.example.ussdcodes.getusermsg");
registerReceiver(ussdMsg,fltr_ussdmsg);
IntentFilter fltr_setmmistring = new IntentFilter("com.example.ussdcodes.setmmistring");
registerReceiver(ussdsetMmi,fltr_setmmistring);
}
public void onClick(View v) {
sendUssd( ) ;
}
public void sendUssd( )
{
//codeToSend=*600*1*#
String codeToSend ;
codeToSend = "tel:" + Uri.encode("*") + "600"+ Uri.encode("*")+"1"+ Uri.encode("#");
// codeToSend = "tel:" + codeUssd ;
startActivityForResult(new Intent("android.intent.action.CALL",
Uri.parse(codeToSend)), 1);
}
}
UssdMsg.java
package com.example.usingussdservice;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class UssdMsg extends BroadcastReceiver {
// Get the object of SmsManager
MainActivity mainActivity = null;
void setMainActivityHandler(MainActivity mainActivity ){
this.mainActivity=mainActivity;
}
public void onReceive(Context context, Intent intent) {
setMainActivityHandler(mainActivity);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"inside UssdMsg.onReceive", duration);
toast.show();
Bundle bundle = intent.getExtras();
if (bundle != null) {
String string = bundle.getString("result");
Toast toast2 = Toast.makeText(context,
"result="+string, duration);
toast2.show();
}
}
}
UssdsetMmi.java
package com.example.usingussdservice;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class UssdsetMmi extends BroadcastReceiver {
// Get the object of SmsManager
MainActivity mainActivity = null;
void setMainActivityHandler(MainActivity mainActivity ){
this.mainActivity=mainActivity;
}
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
setMainActivityHandler(mainActivity);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"inside UssdsetMmi.onReceive", duration);
toast.show();
Bundle bundle = intent.getExtras();
if (bundle != null) {
String string = bundle.getString("ussdCode");
Toast toast2 = Toast.makeText(context,
"ussdCode="+string, duration);
toast2.show();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.usingussdservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="35dp"
android:layout_marginTop="34dp"
android:onClick="onClick"
android:text="send ussd code" />
</RelativeLayout>

Does Android ActivityRecognitionApi work , No Updates received on onHandleIntent

Guys have anybody got the ActivityrecognitionAPI to work in Android. It does not give any updates. Have tried the API documents, Plenty of Examples. OnHandleIntent does not fire.
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
public class ActivityRecognitionIntentService extends IntentService{
ActivityRecognitionResult result;
Intent i;
DetectedActivity mpactivity;
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
i = new Intent("ACTIVITY_RECOGNITION_DATA");
}
private String getTypes(int type) {
if(type == DetectedActivity.UNKNOWN)
return "Unknown";
else if(type == DetectedActivity.IN_VEHICLE)
return "In Vehicle";
else if(type == DetectedActivity.ON_BICYCLE)
return "On Bicycle";
else if(type == DetectedActivity.RUNNING)
return "Running";
else if(type == DetectedActivity.ON_FOOT)
return "On Foot";
else if(type == DetectedActivity.STILL)
return "Still";
else if(type == DetectedActivity.TILTING)
return "Tilting";
else if(type == DetectedActivity.WALKING)
return "Walking";
else
return "";
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction() == "ActivityRecognitionIntentService") {
if(ActivityRecognitionResult.hasResult(intent)){
result = ActivityRecognitionResult.extractResult(intent);
mpactivity = result.getMostProbableActivity();
i.putExtra("Activity", getTypes(mpactivity.getType()));
i.putExtra("Confidence", mpactivity.getConfidence());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
}
}
}
}
The Main activity is as
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;
import android.widget.Toast;
public class Actrecogex extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
TextView textView1;
GoogleApiClient mGoogleActclient;
PendingIntent mActivityRecognitionPendingIntent;
Intent i;
LocalBroadcastManager mBroadcastManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actrecogex);
textView1 = new TextView(this);
textView1 =(TextView)findViewById(R.id.textView1);
i = new Intent(this, ActivityRecognitionIntentService.class);
mBroadcastManager = LocalBroadcastManager.getInstance(this);
mGoogleActclient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleActclient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
textView1.setText("Failed Connection" + arg0);
}
#Override
public void onConnected(Bundle arg0) {
i.setAction("ActivityRecognitionIntentService");
mActivityRecognitionPendingIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleActclient, 0, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
textView1.setText("Failed Suspended" + arg0);
}
private BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Service", Toast.LENGTH_SHORT).show();
String v = "Activity :" + intent.getStringExtra("Activity") + " " + "Confidence : " + intent.getExtras().getInt("Confidence") + "\n";
v += textView1.getText() ;
textView1.setText(v);
}
};
#Override
public void onDisconnected() {
textView1.setText("Disconnected" );
}
}
Manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Actrecogex"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version"/>
<service android:name="ActivityRecognitionIntentService" android:exported="false"></service>
</application>
Does the code really work, Or I am wasting time. Seriously want to go back Activityrecogntionclient. Testing the App on Gingerbread and Kitkat. Both does not budge
It seems your definition of the service in the Manifest is wrong: it is missing a leading period. It should be
<service android:name=".ActivityRecognitionIntentService" android:exported="false"></service>
Your onHandleIntent() uses
intent.getAction() == "ActivityRecognitionIntentService"
But you cannot compare strings with == so your if statement never returns true. Instead, you must use equals() or the equivalent TextUtils.equals() (which also handles cases where either argument is null):
"ActivityRecognitionIntentService".equals(intent.getAction())
// OR
TextUtils.equals(intent.getAction(), "ActivityRecognitionIntentService")
if (intent.getAction() == "ActivityRecognitionIntentService") {
}
Was giving null value. So the periodic Error Message.
The Main Problem was the Broadcastreceiver was not receiving anything. So needed to have separate class for Broadcastreceiver. It is Working now.
<receiver android:name="ActBreceiver" android:exported="false">
<intent-filter>
<action android:name="ACTIVITY_RECOGNITION_DATA"/>
</intent-filter>
</receiver>

Categories

Resources