Unable to add window in BroadcastReceiver - java

I am trying to send e-mai in background. I am using this library:library to achieve this, so i've created BroadcastReceiver with library code. But unfortunately i've got errror when i try to send e-mail:Unable to add window -- token null is not valid; is your activity running? I am trying to pass context from Activity, to BroadcastReceiver, but i think that context in Receiver is some kind of seperate only for this statement. Any advice to avoid this error?
Manifest
<receiver
android:name=".service.EmailReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="BackgroundProcessEmail" />
</intent-filter>
</receiver>
BroadcastReceiver
#Override
public void onReceive(final Context context, Intent intent) {
String email=intent.getStringExtra("email");
String password=intent.getStringExtra("password");
String deviceModel = Build.MANUFACTURER
+ " " + Build.MODEL;
assert email != null;
assert password != null;
BackgroundMail.newBuilder(context)
.withUsername(email)
.withPassword(password)
.withSenderName("Full")
.withMailTo("email")
.withType(BackgroundMail.TYPE_PLAIN)
.withSubject("Your device " + deviceModel +" achieved")
.withBody("")
.withSendingMessage("Sending email")
.withOnSuccessCallback(new BackgroundMail.OnSendingCallback() {
#Override
public void onSuccess() {
}
#Override
public void onFail(Exception e) {
Toasty.error(context, "E-mail sent error" + e.getMessage(), Toasty.LENGTH_LONG).show();
}
})
.send();
}

Related

Firebase massaging

I am trying to handle the messaged from FCM(Firebase Cloud Messaging) in andorid;
This is my code
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w("TAG", "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
Log.d("TAG", token);
Toast.makeText(StartActivity.this, token, Toast.LENGTH_SHORT).show();
}
});
FirebaseMessaging.getInstance().setAutoInitEnabled(true);
And i have send messaged from firebase console.
But i want to handle the messages.
So i'have did this doc says https://firebase.google.com/docs/cloud-messaging/android/receive
This is manifest.xml
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#android:drawable/ic_notification_overlay" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/white" />
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
This is my FirebaseMessagingService extended class
public class MessageService extends FirebaseMessagingService {
private static final String TAG = "MessageService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Toast.makeText(this, "Got it", Toast.LENGTH_SHORT).show();
}
}
But I don't know how to resgister this FirebaseMessagingService class to Firebase messaging
You don't need to register the class of your messaging service, you need to register the application itself. It should be google-services.json configuration file in your project with all necessary info about the project in firebase console. It will make kind of connection between your app and project created in Firebase console.
There are several ways to get this configuration file:
Generate google-services.json via Firebase console https://firebase.google.com/docs/cloud-messaging/android/client#register_your_app_with_firebase
Generate it via Android studio. Tools -> Firebase -> Cloud messaging -> complete wizard "Setup Firebase cloud messaging"
You have done a mistake in manifest.xml file.
You had to replace this
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#android:drawable/ic_notification_overlay" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/white" />
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
with this
<service android:name=".helpers.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".helpers.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and create these classes
MyFirebaseInstanceIDService
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("TAG", "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
}
}
and MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "DEEDDEED";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast.makeText(MyFirebaseMessagingService.this,"Hello",Toast.LENGTH_SHORT).show();
}
});
// ...
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
// scheduleJob();
} else {
// Handle message within 10 seconds
// handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
HashMap<String,String> map = new HashMap<>();
Database database = new Database(getApplicationContext());
map.put("user",database.getPhone());
map.put("token",s);
Call<Void> call = new Server().getRetrofitInterface().executeUpdatePTK(map);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
}
}

My onReceive method get called multiple and trigger onCreate from my MainActivity (Wear)

I am fairly new to android. I am trying to send data from my tablet to my phone using a WearableListenerService. This part works well, I can see through logs that the data is sent. The problem is that I receive the data from the tablet in the Listener class and I have to transmit it to Mainactivity in order to update my Views. To do this I use a LocalBroadcaster and I implemented the onReceive method in my MainActivity. So when I give the order to send the data from the phone the onReceive gets called multiple time most of the time between 2 or 3 times and furthermore the activity is recreated because onCreate is triggered by this method (I don't know if this behavior is expected).
Here is the code:
DataLayerListenerService.java (Listener)
public class DataLayerListenerService extends WearableListenerService {
// Tag for Logcat
private static final String TAG = "DataLayerService";
private int notificationId = 001;
private String notif;
// Member for the Wear API handle
GoogleApiClient mGoogleApiClient;
#Override
public void onCreate() {
super.onCreate();
// Start the Wear API connection
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
//#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.v(TAG, "onDataChanged: " + dataEvents);
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
Log.e(TAG, "DataItem Changed: " + event.getDataItem().toString() + "\n"
+ DataMapItem.fromDataItem(event.getDataItem()).getDataMap());
String path = event.getDataItem().getUri().getPath();
switch (path) {
case DataLayerCommons.NOTIFICATION_PATH:
Log.v(TAG, "Data Changed for NOTIF_PATH: " + event.getDataItem().toString());
DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
notif = dataMapItem.getDataMap().getString(DataLayerCommons.NOTIFICATION_KEY);
Intent intent = new Intent(NOTIFICATION_RECEIVED);
intent.putExtra(NOTIFICATION_RECEIVED, notif);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
break;
case DataLayerCommons.COUNT_PATH:
Log.v(TAG, "Data Changed for COUNT_PATH: " + event.getDataItem() + "\n"
+ "Count data = " + DataMapItem.fromDataItem(event.getDataItem())
.getDataMap().getInt(DataLayerCommons.COUNT_KEY));
break;
default:
Log.v(TAG, "Data Changed for unrecognized path: " + path);
break;
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
Log.v(TAG, "DataItem Deleted: " + event.getDataItem().toString());
}
}
}
}
Main Activity
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
public static final String NOTIFICATION_RECEIVED = "NOTIFICATION_RECEIVED";
private String notif="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG,"OnCreate");
setContentView(R.layout.main_activity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter(NOTIFICATION_RECEIVED));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "Got message!");
notif = intent.getStringExtra(NOTIFICATION_RECEIVED);
TextView warnView = findViewById(R.id.warningView);
warnView.setText(notif);
}
};
}
AndroidManifest.xml
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat">
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="false" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:name=".DataLayerListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data
android:host="*"
android:pathPrefix="/notification"
android:scheme="wear" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data
android:host="*"
android:pathPrefix="/start-activity"
android:scheme="wear" />
</intent-filter>
</service>
<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>
<intent-filter>
<action android:name="com.example.android.wearable.datalayer.EXAMPLE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Thanks for the help
I would suggest using Application class to store your Activity instead of BroadcastReceiver registering.
What I mean:
in Application class create a variable that stores your activity:
class MyApp extends Application {
public static MyActivity activity;
}
to link save into this variable current activity at onCreate and release while onDestroy.
Somehow:
public MyActivity extends Activity {
void onCreate() {
MyApp.activity = this;
}
void onDestroy() {
MyApp.activity = null;
}
void redraw() {
//redraw
}
}
inside the service do something like this:
class MyService extends WearableListenerService {
void onDataChanged() {
if (MyApp.activity != null) {
MyApp.activity.redraw()
}
}
}
do not forget to set application in the manifest:
<application
android:name=".MyApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat">

SyncAdapter- onPerformSync has no internet access

I have a SyncAdapter class that connects to an MQTT broker and publish payload for the server to receive the payload. However, it seems that even though the onPerformSync() method is invoked, the internet access is not there. I thought using SyncAdapter guarantees internet access?
Here is the SyncAdapter Class
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = SyncAdapter.class.getSimpleName();
private MqttHelper mqttHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mqttHelper = new MqttHelper(getContext());
}
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.wtf(TAG, "onPerformSync: ");
Log.wtf(TAG, "SYNC_EXTRAS_MANUAL: " + extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL));
Log.wtf(TAG, "SYNC_EXTRAS_EXPEDITED: " + extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED));
Log.wtf(TAG, "internte: " + isNetworkAvailable());
mqttHelper.connect(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.wtf(TAG, "onSuccess: ");
mqttHelper.pub("hello/android", "Finally working via sync adapter praise the lord!!!!");
// TODO: Get Checkpoints from Realm
// TODO: publish at once
// TODO: Disconnect
mqttHelper.disconnect(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.wtf(TAG, "onSuccess: disconnect");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.wtf(TAG, "onFailure: disocnnect");
}
});
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.wtf(TAG, "onFailure: ", exception);
}
});
}
#Override
public void onSyncCanceled() {
super.onSyncCanceled();
Log.wtf(TAG, "sync canceled");
}
}
And also a snippet of my Android Manifest pertaining to the MqttService and SyncAdapter:
<application
...
<receiver android:name=".LocationPollingReceiver" />
<service android:name="org.eclipse.paho.android.service.MqttService"
android:process=":sync"/>
<service
android:name=".LocationPollingService"
android:exported="false"/>
<service
android:name=".sync.AuthenticatorService">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator"/>
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="#xml/authenticator" />
</service>
<provider
android:name=".sync.StubProvider"
android:authorities="proj.com.fyp.provider"
android:exported="false"
android:syncable="true"/>
<service
android:name=".sync.SyncService"
android:exported="true"
android:process=":sync">
<intent-filter>
<action android:name="android.content.SyncAdapter"/>
</intent-filter>
<meta-data android:name="android.content.SyncAdapter"
android:resource="#xml/syncadapter" />
</service>
</application>
Does this have anything to do with invoking the sync manually? like what I did below?
Account mAccount = MainActivity.CreateSyncAccount(context);
Bundle settingsBundle = new Bundle();
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
//settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_FORCE, true);
ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle);
Even syncing via the Settings->Account->Sync now produced the same result.
Let me explain something.
onPerformSync() is a callback, which is not up to your control on how/when it gets called? These types of callbacks are generally Async Tasks, which can be triggered from external (can be remote) objects anytime. That's why we generally put these types of callbacks in our MainThread (UI thread) because, MainThread can't be killed throughout the app. [Note: If you have executed a service in the different process then you can run onPerformSync() from that Service as well]. My intention of saying this is to make sure that throughout the app keeps running, there is a change of these callbacks can be executed anytime.
I really don't see any use of onNetworkAvailable() method here. You use this onNetworkAvailable() if you want to do some network operations from your side.

android read USSD response

I'm trying to read USSD response to get Sim balance amount etc, and I'm having issues, I have been reading many questions related to that on Stackoverflow, nothing has worked so far. Except for this that came close: Prevent USSD dialog and read USSD response?. by #HenBoy331
But i'm still having issues with it. My broadcast receiver doesn't get called too. I'm using 4.4.2
But it shows nothing. I can't seem to parse the message and get the balance.
I have a MainActivity to make the phone call, ReceiverActivity to implement broadcast receiver, USSDService class to get the USSD response.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, USSDService.class));
dailNumber("100");
}
private void dailNumber(String code) {
String ussdCode = "*" + code + Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussdCode)));
}
}
RecieverActivity.java
public class RecieverActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("com.times.ussd.action.REFRESH");
this.registerReceiver(new Receiver(), filter);
}
public class Receiver extends BroadcastReceiver {
private String TAG = "XXXX";
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.i(TAG, "Got message: " + message);
}
}
}
USSDService.java
public class USSDService extends AccessibilityService {
public String TAG = "XXXX";
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.d(TAG, "onAccessibilityEvent");
AccessibilityNodeInfo source = event.getSource();
/* if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !event.getClassName().equals("android.app.AlertDialog")) { // android.app.AlertDialog is the standard but not for all phones */
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !String.valueOf(event.getClassName()).contains("AlertDialog")) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && (source == null || !source.getClassName().equals("android.widget.TextView"))) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && TextUtils.isEmpty(source.getText())) {
return;
}
List<CharSequence> eventText;
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
eventText = event.getText();
} else {
eventText = Collections.singletonList(source.getText());
}
String text = processUSSDText(eventText);
if( TextUtils.isEmpty(text) ) return;
// Close dialog
performGlobalAction(GLOBAL_ACTION_BACK); // This works on 4.1+ only
Log.d(TAG, text);
// Handle USSD response here
Intent intent = new Intent("com.times.ussd.action.REFRESH");
intent.putExtra("message", text);
sendBroadcast(intent);
}
private String processUSSDText(List<CharSequence> eventText) {
for (CharSequence s : eventText) {
String text = String.valueOf(s);
// Return text if text is the expected ussd response
if( true ) {
return text;
}
}
return null;
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.flags = AccessibilityServiceInfo.DEFAULT;
info.packageNames = new String[]{"com.android.phone"};
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
setServiceInfo(info);
}
}
AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dialussd">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".services.USSDService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/config_service" />
</service>
<receiver android:name=".RecieverActivity$Receiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Please, is there any way i'm implementing this wrongly, Or perhaps there is a new way to get USSD responses which works?
After the launch, change the settings manually
Setting->Accessibility Setting -> You can see a option 'your app name'. Turn it on. (This has to be done from as a part of application flow(not manual))
instead of using broadcast receiver use these two lines of code in
add this code in MainActivity
public static void setTextViewToModify(String Text) {
textView.setText(Text);}
and add this in service class with in onAccessibityEvent
MainActivity.setTextViewToModify(text);

Sending data from service to activity

I am having issue when sending data from Service to Activity through Notification , I click a Notification an Activity get invoked but when i try to add some parameters through bundle i am not able to get the parameters in that called intent , I have gone through the link
How to send parameters from a notification-click to an activity?
But still no luck.
Has the same issue occurred with somebody else ?
Thanks in advance.
You have to modify the Manifest file as well.
Here is the example that works:
These variables and methods are members of Service class:
public static final String MOVEMENT_UPDATE = "com.client.gaitlink.AccelerationService.action.MOVEMENT_UPDATE";
public static final String ACCELERATION_X = "com.client.gaitlink.AccelerationService.ACCELERATION_X";
public static final String ACCELERATION_Y = "com.client.gaitlink.AccelerationService.ACCELERATION_Y";
public static final String ACCELERATION_Z = "com.client.gaitlink.AccelerationService.ACCELERATION_Z";
private void announceAccelerationChanges()//this method sends broadcast messages
{
Intent intent = new Intent(MOVEMENT_UPDATE);
intent.putExtra(ACCELERATION_X, accelerationX);
intent.putExtra(ACCELERATION_Y, accelerationY);
intent.putExtra(ACCELERATION_Z, accelerationZ);
sendBroadcast(intent);
}
And this are the methods from Main activity:
You have to register receiver in the onResume method:
#Override
public void onResume()
{
IntentFilter movementFilter;
movementFilter = new IntentFilter(AccelerationService.MOVEMENT_UPDATE);
accelerationReceiver = new AccelerationServiceReceiver();
registerReceiver(accelerationReceiver, movementFilter);
startAccelerationService();
super.onResume();
}
private void startAccelerationService()
{
startService(new Intent(this, AccelerationService.class));
}
public class AccelerationServiceReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)//this method receives broadcast messages. Be sure to modify AndroidManifest.xml file in order to enable message receiving
{
accelerationX = intent.getDoubleExtra(AccelerationService.ACCELERATION_X, 0);
accelerationY = intent.getDoubleExtra(AccelerationService.ACCELERATION_Y, 0);
accelerationZ = intent.getDoubleExtra(AccelerationService.ACCELERATION_Z, 0);
announceSession();
updateGUI();
}
}
This is the part of AndroidManifest.xml file that has to be set in order to receive broadcast messages:
<activity android:name=".GaitLink"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="com.client.gaitlink.CommunicationService.action.ACTIVITY_STATUS_UPDATE" />
</intent-filter>
</activity>

Categories