Android IntentService not receiving extra - android

I am starting the service , and I put a message in extra,
Intent mServiceIntent = new Intent(this, TextToSpeechService.class);
mServiceIntent.putExtra(Intent.EXTRA_TEXT, "a message");
mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE);
this.startService(mServiceIntent);
but running , the service starts and the log shows a message = null...
public class MyService extends IntentService {
static final String TAG = "MyService";
public MyService() {
super("My Service");
}
#Override
protected void onHandleIntent(Intent intent) {
String message = intent.getStringExtra("message");
Log.d(TAG, "received message, should say: " + message);
}
could it be related to the MIME TYPE, when I state mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE);
( using import org.apache.http.protocol.HTTP;)

As #Squonk already mentioned your code doesn't really go together. To start your Service you have to use an Intent like this:
// The class you set here determines where the Intent will go.
// You want it to start MyService so we write MyService.class here.
Intent intent = new Intent(this, MyService.class);
intent.putExtra(Intent.EXTRA_TEXT, "a message");
startService(intent);
You can very well use the Intent.EXTRA_TEXT constant as key for your extra, but you have to use the same key to retrieve the message in your Service:
#Override
protected void onHandleIntent(Intent intent) {
String message = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.d(TAG, "received message, should say: " + message);
}
The code in your MyService doesn't really show if you actually use the mime type in your MyService so I removed it from my example above.

Related

Starting an ActivityRecognitionService from within another active Service

I am having an issue getting my ActivityRecognition Service to remain running. I currently have a service (GService) that runs continuously in the background. I want to start the ActivityRecognition service within GService, and have the ActivityRecognition service broadcast the activity result back to GService. I am able to start the service and receive feedback that it is running, and I also get one result from the intent handler (no actual data), but never again.
Here is the section of code from my continuous service setting up the intent, pending intent:
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
//start process to receive activity updates
Intent intent = new Intent(this, DetectedActivitiesIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, ActivityConstants.DETECTION_INTERVAL_MILLISECONDS_MOVING,
mActivityRecognitionPendingIntent).setResultCallback(this);
startService(intent); // this should start the DetectedActivitiesIntentService
This is the Broadcast receiver within GService:
public class ActivityDetectionBroadcastReceiver extends BroadcastReceiver {
protected static final String TAG_AR = "ADRR";
#Override
public void onReceive(Context context, Intent intent){
//ArrayList<DetectedActivity> updatedActivities =
// intent.getParcelableArrayListExtra(ActivityConstants.ACTIVITY_EXTRA);
//updateDetectedActivitiesList(updatedActivities);
String action = intent.getAction();
if(action.equals("com.gt.useractivity"))
{
Log.d(TAG_AR, "received broadcast from Activity service");
// below line should grab the resulting string activity from the intent and log it.
Log.d(TAG_AR, "activity is : " + intent.getExtras().getString(ActivityConstants.ACTIVITY_EXTRA));
}
}
}
Here is the ActivityRecognition Service code:
public class DetectedActivitiesIntentService extends IntentService {
protected static final String TAG = "ADIS";
/**
* This constructor is required, and calls the super IntentService(String)
* constructor with the name for a worker thread.
*/
public DetectedActivitiesIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
Log.d(TAG, "Activity service started....");
}
#Override
public void onCreate() {
super.onCreate();
}
/**
* Handles incoming intents.
* #param intent The Intent is provided (inside a PendingIntent) when requestActivityUpdates()
* is called.
*/
#Override
protected void onHandleIntent(Intent intent) {
if(ActivityRecognitionResult.hasResult(intent))
{
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
Intent localIntent = new Intent(ActivityConstants.BROADCAST_ACTION);
// Get the list of the probable activities associated with the current state of the
// device. Each activity is associated with a confidence level, which is an int between
// 0 and 100.
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
// Log each activity.
Log.i(TAG, "activities detected");
for (DetectedActivity da: detectedActivities) {
Log.i(TAG, ActivityConstants.getActivityString(da.getType()) + " " + da.getConfidence() + "%");
}
String activity = result.getMostProbableActivity().toString(); // get the activity and convert to string
// Broadcast the list of detected activities.
//localIntent.putExtra(ActivityConstants.ACTIVITY_EXTRA, detectedActivities);
//localIntent.setAction("com.gt.useractivity");
localIntent.putExtra(ActivityConstants.ACTIVITY_EXTRA, activity); // set the activity string to be transmitted
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
else{
Log.d(TAG, "Intent had no activity data....");
}
}
}
This Activity recognition sample is based from the Google Github sample.
All the examples I have found when using the PendingIntent is being called from a main activity, not from a service. I'm obviously doing something incorrect, but I can't figure it out. Any advice would be appreciated. I should also note that I have 2 broadcast receivers within my GService. I don't know if this would cause an issue or not.
It looks like I have solved the problem. I have a second intent within my GService used for broadcasting. From what I can tell from this thread (Pending intent works correctly for first notification but not for the rest) if there are multiple intents being used, they have to be unique. Thus, I added one line of code when declaring my intent intent.setAction(Long.toString(System.currentTimeMillis())); which is enough to differentiate it from the other intent to the system. Once I did that, I began to receive the Activity broadcasts from the intent service, as well as still receiving the location requests from within the GService routine.

Send integer value using Broadcast receiver in Android

How to pass a integer value from Service class using a Broadcast intent to a Activity. Below is my code but getting some errors,
Sending side
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
int dataJNI = BioLIb.intFromJNI();
intent.putExtra("mykey", dataJNI);
sendBroadcast(intent);
}
Receiving side
private Intent intent;
the above is a global variable. In my onCreate I will call BroadcastReceiver class like below.
intent = new Intent(this, BroadCastService.class);
onReceive of BroadcastReceiver i will call
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
int time = intent.getINtExtra("mykey", 1);
But I am not getting my exact value of dataJNI in a receiving side. I am always getting value is 1, How to get resolve this.
When you're sending you're putting an integer into the Intent Bundle. When receiving you0re trying to extract a long. Did you try using the same type in both sides?
use the intent that you received as a parameter of onReceive method
int time;
public void onReceive(Context context, Intent intent) {
updateUI(intent);
time = intent.getLongExtra("mykey", 1);
}

How do i get data from the gcm?

Can someone show me the hierarchy that stands behind the process when I'm getting a new data from the GCM? The process that happened only in the client. Example: First the data is getting to the displayMessage function in CommonUtilities class. Seconds the data is transmitted to the onMessage function in GCMIntentService class, and so on.
Thanks!
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
If all the process with registering the device and getting the registrationId is passes as it should be, getting the data in your onMessage() should be something similar to this :
#Override
protected void onMessage(Context arg0, Intent intent) {
Log.d(TAG, "MESSAGE RECEIVED : "+intent.getExtras().toString());
String action = intent.getStringExtra("action");
int extra = 0;
try {
extra = Integer.parseInt(intent.getStringExtra("action_id"));
} catch (Exception e){
/* ignore */
}
String message = intent.getStringExtra("message");
generateNotification(getApplicationContext(), message, action, extra);
}
Of course this is in my app, the keys which you will use to get the right data depends on what kind of data is sending your server to the client device. And after receiving this portion of data you can do whatever you like with it, maybe create a notification and alert the user about the message.
Edit :
If you want to show some kind of message in your activity using BroadcastReceiver you can do something like this : In your onMessage after receiving the message send broadcastIntent
Intent intent = new Intent("messageReceived");
sendBroadcast(intent);
and add
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(messageReceived);
to your activity and register your broadcast receiver like :
registerReceiver(myReceiver, intentFilter);
and handler the message in your receiver like this :
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("messageReceived")) {
// Do your stuff here.
}
}

Passing Data from Broadcast Receiver to another Activity

Hi I've been having an issue with Broadcast Receivers and passing information to another activity. I'm trying to create an application that will capture incoming SMS messages, look for a website in the text, then pop up an Alert Dialog box asking if the user wants to go to the website.
public class TextReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent)
{
// .. other code that
// sets received SMS into message
Toast toast = Toast.makeText(context,
"Received Text: " + message.getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
So that code works fine, receive a text it pops up a toast with the message. The toast is useless but it shows the receiver works. But I want to communicate with an activity to show an Alert Dialog and start up a webView. I already programmed the code that will take a string search for the website and open the webView. Is it possible to get the string from the broadcast receiver and do something like this?:
public class ReceiveText extends Activity{
public void onCreate(Bundle savedInstanceState) {
// Somehow pass the string from the receiver into this activity,
//stored in variable messages
findOpen(messages);
// is that possible?
}
public class findOpen(string messages){
// do stuff ... open alert...open site if OK
}
So basically I just want to pass a string from a Broadcast Receiver to another activity that will use that string. The rest of the code is basically in place all I need is that string... I'm new to this and Java and any help would be much appreciated. Thanks
Instantiate a BroadcastReceiver in the activity you want to get your data to, for example:
private BroadcastReceiver mServiceReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent)
{
//Extract your data - better to use constants...
String IncomingSms=intent.getStringExtra("incomingSms");//
String phoneNumber=intent.getStringExtra("incomingPhoneNumber");
}
};
Unregister your receiver on onPause():
#Override
protected void onPause() {
super.onPause();
try {
if(mServiceReceiver != null){
unregisterReceiver(mServiceReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Register it on onResume():
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SmsReceiver");
registerReceiver(mServiceReceiver , filter);
}
Broadcast your data from the service via an Intent, for Example:
Intent i = new Intent("android.intent.action.SmsReceiver").putExtra("incomingSms", message);
i.putExtra("incomingPhoneNumber", phoneNumber);
context.sendBroadcast(i);
and that's it! goodLuck!
If you have your activity named ReceiveText, then in your BroadcastReceiver, you should do the following:
Intent i = new Intent(context, ReceiveText.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", message.getMessageBody());
context.startActivity(i);
Then, in your activity, you will need to getExtra as so:
Intent intent = getIntent();
String message = intent.getStringExtra("message");
And then you will use message as you need.
If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="#android:style/Theme.Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.
EDIT: This restarts your activity. this answer is likely a better solution for most people.
We can send the data from onReceive to another activity using LocalBroadcastManager.
It means you are again broadcasting the data using the context
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Broadcast", "wifi ConnectivityReceiver");
Bundle extras = intent.getExtras();
Intent intent = new Intent("broadCastName");
// Data you need to pass to another activity
intent .putExtra("message", extras.getString(Config.MESSAGE_KEY));
context.sendBroadcast(intent );
}

How call an Intent switch from a c2dm message reciever

I have a simple c2dm message receiver class which is called whenever the device receives a c2dm message. In one case, I want to have the message receiver class perform an intent switch to load a different activity. Android throws an exception when this happens
01-07 02:28:52.480: E/AndroidRuntime(440): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I guess I could investigate this flag suggested in the exception, but i'm wondering if maybe i'm taking the wrong approach and there is a better way to do this?
c2dm message receiver class:
public class C2DMMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("C2DM", "Message Receiver called");
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
Log.w("C2DM", "Received message");
final String payload = intent.getStringExtra("payload");
Log.d("C2DM", "dmControl: payload = " + payload);
// Message handling
if(payload.equals("RdyRoom::join")) {
Intent rIntent = new Intent(context.getApplicationContext(), ReadyRoomActivity.class);
context.startActivity(rIntent);
}
}
}
}
Thanks for any ideas
Add this to your intent
Intent.FLAG_ACTIVITY_NEW_TASK

Categories

Resources