Reputation: 75
in my app i start a service to receive notifications while the app is in background - this service forces my app to start automatically after i stop it. i tried to solve the problem by using pending intent but it still happens.
Here is my intent to start the service:
Intent messageReceivingIntent = new Intent(this, MessageReceivingService.class);
messageReceivingIntent.putExtra("myUserId", myUserId);
Pending Inten messagePendingIntent = PendingIntent.getService(this, 0, messageReceivingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
// Perform the operation associated with our pendingIntent
messagePendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
if i call service via externalreceiver i get a nullpointerexception. any idea why?
this is my BroadcastReceiver call:
messageReceivingIntent = new Intent(this, MessageReceivingService.class);
messageReceivingIntent.putExtra("myUserId", myUserId);
messageReceivingIntent.setAction("com.example.androidtest");
sendBroadcast(messageReceivingIntent);
Here is my Broadcast receiver:
public class ExternalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent!=null){
Bundle extras = intent.getExtras();
if(!MapsActivity.inBackground){
MessageReceivingService.sendToApp(extras, context);
}
else{
MessageReceivingService.saveToLog(extras, context);
}
}
}
}
and this is MessageReceivingService
public class MessageReceivingService extends Service {
private GoogleCloudMessaging gcm;
public static SharedPreferences savedValues;
public static final String INSTANCE_ID_SCOPE = "GCM";
final String BASE_URL = "http://www.example.com/";
public String myUserId;
public String registeredUserId;
public String token;
static PendingIntent pendingIntent;
public static void sendToApp(Bundle extras, Context context) {
Intent newIntent = new Intent();
newIntent.setClass(context, MapsActivity.class);
newIntent.putExtras(extras);
ShortcutBadger.applyCount(Content.getAppContext(), 0);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
public void onCreate() {
super.onCreate();
final String preferences = getString(R.string.preferences);
savedValues = getSharedPreferences(preferences, Context.MODE_PRIVATE);
// In later versions multi_process is no longer the default
if (VERSION.SDK_INT > 9) {
savedValues = getSharedPreferences(preferences, Context.MODE_MULTI_PROCESS);
}
gcm = GoogleCloudMessaging.getInstance(getBaseContext());
// Let AndroidMobilePushApp know we have just initialized and there may be stored messages
sendToApp(new Bundle(), this);
}
protected static void saveToLog(Bundle extras, Context context) {
SharedPreferences.Editor editor = savedValues.edit();
String numOfMissedMessages = context.getString(R.string.num_of_missed_messages);
int linesOfMessageCount = 0;
for (String key : extras.keySet()) {
String line = String.format("%s=%s", key, extras.getString(key));
editor.putString(key, line);
linesOfMessageCount++;
}
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(numOfMissedMessages, savedValues.getInt(numOfMissedMessages, 0) + 1);
editor.commit();
String type = extras.getString("model");
String id = extras.getString("id");
String userId = extras.getString("user_id");
//postNotification(new Intent(context, MapsActivity.class), context);
if(type != null) {
if (type.equals("content")) {
Intent contentIntent = new Intent(context, ContentDetailActivity.class);
Log.v("userID", userId);
contentIntent.putExtra("contentId", id);
if (userId != null) {
contentIntent.putExtra("userId", userId);
}
postNotification(contentIntent, context);
} else if (type.equals("user")) {
Intent userIntent = new Intent(context, ProfileActivity.class);
userIntent.putExtra("userId", id);
postNotification(userIntent, context);
}
} else {
postNotification(new Intent(context, NotificationsActivity.class), context);
}
ShortcutBadger.applyCount(Content.getAppContext(), Integer.valueOf(savedValues.getInt(Content.getAppContext().getString(R.string.num_of_missed_messages), 0)));
}
protected static void postNotification(Intent intentAction, Context context) {
final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
pendingIntent = PendingIntent.getActivity(context, 0, intentAction, PendingIntent.FLAG_UPDATE_CURRENT);
int numOfMissedMessages = 0;
String missedMessage = "";
if(savedValues != null){
missedMessage = savedValues.getString("message", "nothing there");
}
Log.v("NUMOFMISSEDMESSAGES", String.valueOf(numOfMissedMessages));
final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(missedMessage.substring(missedMessage.indexOf("=") + 1, missedMessage.length()))
.setContentText("")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
mNotificationManager.notify(R.string.notification_number, notification);
}
private void register() {
new AsyncTask() {
protected Object doInBackground(final Object... params) {
try {
String instanceId = InstanceID.getInstance(getApplicationContext()).getId();
//token = gcm.register(getString(R.string.project_number));
token = InstanceID.getInstance(getApplicationContext()).getToken(getString(R.string.project_number), INSTANCE_ID_SCOPE);
Log.i("registrationId", token);
} catch (IOException e) {
Log.i("Registration Error", e.getMessage());
}
return true;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
new SendRegUserId().execute();
}
}.execute();
}
public IBinder onBind(Intent arg0) {
return null;
}
}
Upvotes: 0
Views: 123
Reputation: 3022
Use a Broadcast Receiver to receive the notification, and then send it to your Service. That will allow you to send a notification
to the user without starting your app.
=========
Edit 1:
So your Broadcast receiver needs to start the service instead of calling its methods. So after your check for intent to be null, something along the lines of:
ComponentName comp = new ComponentName(context.getPackageName(), YourIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp));
setResultCode(Activity.RESULT_OK);
Also, your Broadcast Receiver
should extend WakefulBroadcastReceiver if you still want to receive notifications after the phone's been turned off.
Also, your Service
should be an IntentService. I think Android Studio actually comes with some pre-made GCM classes or a GCM app that will actually take care of 90% of these little issues you're having. It's a better starting point.
Check out the GCM docs for more help.
Upvotes: 2
Reputation: 374
Some of few possible solutions-
1) Use BroadcastReceiver
2) Use onPause(), onResume() methods
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Intent messageReceivingIntent = new Intent(this,MessageReceivingService.class);
onCreate(){
//YOUR OWN CODE
prefs.getBoolean("service_started",false);
}
onPause(){
//YOUR OWN CODE
prefs.edit().putBoolean("service_started",true).apply();
startService(messageReceivingIntent);
}
onResume(){
//YOUR OWN CODE
if(prefs.getBoolean("service_started",false)){
stopService(new Intent(this, MessageReceivingService.class));
prefs.edit().putBoolean("service_started",false).apply();
}
}
3) Or the Best to do according to me is to implement Firebase Cloud Messaging for notification.
Check this out https://firebase.google.com/docs/cloud-messaging/
It reduces your battery and server effort a lot. Its a brand new service from Google.
OR I think there can be Bug in your Service Code
Upvotes: 0