This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have developed an app that sends the user's location via SMS. When I starting building it there were no errors, but when it is being tested with an actual phone it crashes ... It would not open.
public class MainActivity extends AppCompatActivity {
EditText phone;
Button emergency;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone= (EditText) findViewById(R.id.number);
emergency= (Button) findViewById(R.id.emergency);
emergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GPStracker g = new GPStracker(getApplicationContext());
Location l = g.getLocation();
if (l != null) {
double lat = l.getLatitude();
double lon = l.getLongitude();
String message = "http://maps.google.com/maps?saddr=" + lat + "," + lon;
String number = "number";
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append(Uri.parse(message));
android.telephony.SmsManager.getDefault().sendTextMessage(number, null, smsBody.toString(), null, null);
}
}
});
}
AND ALSO HERE IS MY CLASS FOR GPS TRACKING
public class GPStracker implements LocationListener {
Context context;
public GPStracker(Context c){
context = c;
}
public Location getLocation(){
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,this);
Location l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return l;
}else{
Toast.makeText(context,"Please enable GPS", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
}
}
AND MY MANIFEST FILE
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.research.sos.smshelpcaller">
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
<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>
</application>
I ALREADY TRY EVERYTHING BUT I DON'T KNOW WHAT IS WRONG IN MY CODES OR IS THERE SOMETHING MISSING.
LASTLY HERE IS THE LOGS IN LOGCAT
04-03 13:55:56.472 31224-31224/com.research.sos.smshelpcaller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.research.sos.smshelpcaller, PID: 31224
java.lang.NullPointerException: Attempt to get length of null array
at android.os.Parcel.readException(Parcel.java:1546)
at android.os.Parcel.readException(Parcel.java:1493)
at com.android.internal.telephony.ISms$Stub$Proxy.sendText(ISms.java:1430)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:320)
at com.research.sos.smshelpcaller.MainActivity$1.onClick(MainActivity.java:37)
at android.view.View.performClick(View.java:5052)
at android.view.View$PerformClick.run(View.java:20162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5753)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
where is your layout file,
Give your xml reference to activity after super.onCreate(savedInstanceState);.
for example..
setContentView(R.layout.activity_main);
According to your log you try to invoke method on Null Pointer:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.research.sos.smshelpcaller.MainActivity.onCreate(MainActivity.java:23)
It means, that the code below does not resolve the R.id.emergency asset. It simply can't find it and the first line is set to null:
emergency= (Button) findViewById(R.id.emergency);
emergency.setOnClickListener(new View.OnClickListener() {...}
You should check if the name of the button you try to use is correct, if there is no spell mistakes, or even if the resource file (for example xml with view) exists.
Related
I have my main activity that start a service (Location service) and I want that service to broadcast the new location each time a new location is found.
Thanks to the log I know the service is working and I have new locations every seconds or so, but I never get the broadcast.
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = "mainActivity";
private CMBroadcastReceiver mMessageReceiver = new CMBroadcastReceiver();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// Start Service
startService(new Intent(this, LocationService.class));
super.onCreate(savedInstanceState);
}
#Override
public void onResume()
{
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE));
super.onResume();
}
#Override
public void onPause()
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
}
CMBroadcastReceiver.java
public class CMBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CMBroadcastReceiver";
public static final String RECEIVE_LOCATION_UPDATE = "LOCATION_UPDATES";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received broadcast");
String action = intent.getAction();
if (action.equals(RECEIVE_LOCATION_UPDATE))
{
Log.i(TAG, "Received location update from service!");
}
}
}
LocationService.java
/**
* Callback that fires when the location changes.
*/
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i(TAG, "onLocationChanged " + location);
Intent intent = new Intent(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.i(TAG, "Broadcast sent");
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cyclemapapp.gpstracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".LocationService" android:process=":location_service" />
</application>
I the log I can see that "Broadcast Sent" But I never get the "Broadcast Received"
Any help will would be greatly appreciated.
EDIT:
Edited how the intent was created in the location service as Shaishav suggested.
Still doesn't work.
LocalBroadcastManager does not work across processes. Your Service is running in a separate process.
You can either run your Service in the same process as the Activity - by removing the process attribute from the <service> element - or use some sort of IPC instead - e.g., by sending and receiving the broadcasts on a Context instead of LocalBroadcastManager.
In your LocationService, send local broadcast using:
Intent intent = new Intent(CMBroadcastReceiver.RECEIVE_LOCATION_UPDATE);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
<service android:name=".LocationService" android:process=":location_service" />
Your service is in a separate process from the activity. LocalBroadcastManager is only for use in one process. Either remove android:process from the <service>, or use some IPC mechanism (e.g., system broadcasts, properly secured).
I'm trying to create a service with an IPC connection defined in an .aidl file.
The service starts and the service connection can bind to it, but when the IPC API is called from the same thread it causes a NullPointerException.
When the call to the IPC API is put in an event on a button press it works.
How can this be fixed so that the call can be done without having a button event to start it.
My MainActivicty
public class MainActivity extends AppCompatActivity {
public final String TAG = "Main Activity";
IMyAidlInterface iMyAidlInterface;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
iMyAidlInterface = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent interFaceServiceIntent = new Intent(this, IMyAidlService.class);
bindService(interFaceServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
Intent sigGenIntent = new Intent(this, signalGenerator.class);
startService(sigGenIntent);
Button b = findViewById(R.id.button);
/*
* The following block is what I want to be able to execute. Currently it causes * a NullPointerException
* Caused by: java.lang.NullPointerException: Attempt to invoke interface method * 'int com.aidltest.IMyAidlInterface.getPid()' on a null object reference
*/
try {
iMyAidlInterface.getPid();
} catch (RemoteException e) {
e.printStackTrace();
}
/*
* The block below using the same interface from within a button event works
* without problem.
*/
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
iMyAidlInterface.getPid();
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
For reference my Aidl:
package com.aidltest;
interface IMyAidlInterface {
int getPid();
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
And my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aidltest">
<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=".IMyAidlService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
This is happening because iMyAidlInterface is null in your onCreate call. It is not set until your connection listener calls you back via onServiceConnected. Binding is an async operation.
I am building a voice recognition app that does something when I say a specific word such as "open" and it opens something etc. but the problem is that my app keep crashing when I run it on my phone (real device) and I tap the speak button. I don't know what else to do? I tried giving it internet and voice recognition permission but it still doesn't help
here is the code in java (android studio)
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.SpeakButton);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
startVoiceRecognitionActivity();
}
});
}
void startVoiceRecognitionActivity(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult (int requestCode,int resultCode, Intent data){
String wordStr = null;
String[] words = null;
String firstWord = null;
String secondWord = null;
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK)
{
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
wordStr = matches.get(0);
words = wordStr.split(" ");
firstWord = words[0];
secondWord = words[1];
}
if (firstWord.equals("open"))
{
resultText = (TextView)findViewById(R.id.ResultText);
resultText.setText("Results: Open Command Works");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starlinginteractivesoftworks.musiccompanion">
<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">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I look at the log and it said:
08-07 20:12:57.813 14350-14350/? E/BoostFramework: BoostFramework() :
Exception_1 = java.lang.ClassNotFoundException: Didn't find class
"com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib64,
/vendor/lib64]] 08-07 20:12:58.509
14350-14350/com.starlinginteractivesoftworks.musiccompanion
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.starlinginteractivesoftworks.musiccompanion, PID: 14350
android.content.ActivityNotFoundException: No Activity found to handle
Intent { act=android.speech.action.RECOGNIZE_SPEECH
launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } (has
extras) }
at
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1839)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1531)
at android.app.Activity.startActivityForResult(Activity.java:4399)
at android.app.Activity.startActivityForResult(Activity.java:4358)
at
com.starlinginteractivesoftworks.musiccompanion.MainActivity.startVoiceRecognitionActivity(MainActivity.java:55)
at
com.starlinginteractivesoftworks.musiccompanion.MainActivity$1.onClick(MainActivity.java:43)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
The boost framework log is just a warning, no worry about it. The real problem is the
ActivityNotFoundException: No Activity found to handle Intent
It can come from:
a poor connectivity
the voice app is missing on your phone
Possible solutions
Ensure you have a recognition app installed (see ActivityNotFoundException: No Activity found to handle Intent (RECOGNIZE_SPEECH) for more details).
Try to enable offline mode as explained here:
On your device go to Settings -> Language and Input. Click on icon on Google voice input.
Under ALL tab select the language you want to download.
Once the language package downloaded, you can see it under INSTALLED tab.
Workarounds
Catch the exception and open a webview to download a recognition app:
try{
...
}
catch(ActivityNotFoundException e) {
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://market.android.com/details?id=APP_PACKAGE_NAME"));
startActivity(i);
}
Check that a recognition app is available before the startActivity (see https://stackoverflow.com/a/35290037/2667536):
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
//Then there is application can handle your intent
}else{
//No Application can handle your intent
}
I am new to android programming and I am trying to build an app which changes the profile on receiving a message from the user. The app basically has one activity and a broadcast receiver. I am prompting the user to set a password for changing the profile and the password is saved in a Shared Preference which I am using inside MainActivity. I am not able to retrieve the password stored in shared preference in the broadcast receiver class.Also, I can only use Shared Preference for storing the password.The code for MainActivity , Broadcast Receiver , layout and Android manifest file is given below. Thanks a lot for your help.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public EditText setPass;
public Button submit;
public static String password;
SharedPreferences sharedPreferences;
boolean b=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setPass=(EditText)findViewById(R.id.setPassEditId);
submit=(Button)findViewById(R.id.submitButtonId);
sharedPreferences= getApplicationContext().getSharedPreferences("Pritom",Context.MODE_PRIVATE);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
password=setPass.getText().toString();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("password",password);
editor.commit();
Toast.makeText(getApplicationContext(),"Password saved successfully"+password,Toast.LENGTH_LONG).show();
//b=sharedPreferences.contains("password")?true:false;
//Toast.makeText(getApplicationContext(),"b:"+b,Toast.LENGTH_LONG).show();
}
});
}
}
Here,in MainActivity class the variable b returns true which means that the shared preference exists.
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
public AudioManager audioManager;
public String me = "";
public String last = "";
public static final String SMS_BUNDLE = "pdus";
public SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
boolean b = false;
#Override
public void onReceive(Context context, Intent intent) {
sharedPreferences = context.getSharedPreferences("Pritom", context.MODE_PRIVATE);
String pass3 = sharedPreferences.getString("password", null);
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "n";
String smsBody = msgs[i].getMessageBody().toString();
if (smsBody.equals("#general" + pass3)) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(audioManager.RINGER_MODE_NORMAL);
}
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
The problem here is that pass3 which retrieves the value from shared preference returns nothing for which the if statement for checking the message does not work.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<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>
<receiver
android:name=".MyReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
Please help me. Thank you.
//Inside onReceive method
sharedPreferences = context.getSharedPreferences("Pritom", context.MODE_PRIVATE);
// Instead of this line, use
sharedPreferences= getApplicationContext().getSharedPreferences("Pritom", Context.MODE_PRIVATE);
There is possibility that you receives broadcast before setting up password.
Broadcast receiver registered on SMS received that means it calls when SMS received.
What when sms is received and you still don't assign password to shared preference? In that case you are not able to get password from preference.
Please check that scenario and make some changes to that.
I have tried to simplify my code as much as possible, basically hte issue is that the ActivityRecognitionIntentService appears to be called a couple of times, then stalls out. It appears to be related to the requestCode in the PendingIntent, but I am not sure, can someone please advise me as to what is going wrong? Thanks.
Dashboard.java
public class Dashboard extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private BroadcastReceiver receiver;
private TextView tvActivity;
private GoogleApiClient mGoogleApiClient;
//String Locationp = "null";
//private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tvActivity = (TextView) findViewById(R.id.tvActivity);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
//.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle arg0) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 2000, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.e("MAIN", "Connected to ActRec");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 1000, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
Log.e("MAIN", "Connection suspended to ActRec");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("MAIN", "Not Connected to ActRec");
}
ActivityRecognitionIntentService.java
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbAct = result.getMostProbableActivity();
int confidence = mostProbAct.getConfidence();
String mostProbActName = getActivityName(mostProbAct.getType());
Intent i = new Intent("com.xxx.abc.ACTIVITY_RECOGNITION_DATA");
i.putExtra("act", mostProbActName);
i.putExtra("confidence", confidence);
Log.e("ARS", mostProbActName + "," + confidence);
//sendBroadcast(i);
} else
Log.e("ARS", "Intent had no ActivityRecognitionData");
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tigerblood.com.node" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<service android:enabled="true" android:name="com.xxx.abc.ActivityRecognitionIntentService"></service>
<activity
android:name="com.tigerblood.node.Dashboard"
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>