Broadcast receiver push notification - android

I have implemented push notification in my android application:
In my main class:
// PUSH
Parse.initialize(this, applicationId, clientKey);
PushService.setDefaultPushCallback(this, SlidingMenuActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
ParseAnalytics.trackAppOpened(getIntent());
In my manifest.xml:
<!-- PUSH -->
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
When i open my application, i am receiving notification. I click on back and close the application.
I still receiving notification for approximatively 1 hours. After one hour, i send three notification and no notification appear. So i restart my app, and three notification notification appear.
I guess my broadcast receiver has been recreated. Why my android is killing my notification broadcast receiver?
How can i fix that?

try my solution it worked for me:
link your broadcast receiver to your service by adding
public void onReceive(Context context, Intent intent) {
//add the following
Intent e = new Intent(context, urservice.class);
context.startService(e);
}
then register your receiver in your service onCreate() like so
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.BOOT_COMPLETED);
filter.addAction(Intent.USER_PRESENT);
BroadcastReceiver mReceiver = new ParseBroadcastReceiver();
registerReceiver(mReceiver, filter);
}
then just delete your 'broadcastreceiver' from the manifest, lastly surly you want the service to live as long as possible,,, well then you need also 2 codes for the service in your int onStartCommand(Intent intent, int flags, int startId) make sure you put the following
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(urservice.this, urmain.class);
PendingIntent pbIntent = PendingIntent.getActivity(urservice.this, 0 , bIntent, 0);
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setContentText("sub title")
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
// also the following code is important
return Service.START_STICKY;
now make return sticky at the end of your onstartcommand. feel free to ask me.
hope I helped,,, good luck. :)

Is your device going to sleep? Is it getting low on memory? All of these things you have to consider. You may have to hold a wake lock or start a service that returns a value to restart sticky.

Related

Keeping the service running indefinitely

I'm trying to write a service that will run in background until removed by the user, I used this code:
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
activityIntent, 0);
Notification notification = new Notification.Builder(this).
setContentTitle(getText(R.string.app_name)).
setContentText("Doing stuff").
setContentInfo("").
setSmallIcon(R.drawable.icon).
setDeleteIntent(createOnDismissedIntent(getBaseContext(), notId)).
setContentIntent(pendingIntent).build();
notificationManager.notify(notId,notification);
return START_REDELIVER_INTENT;
The service is supposed to listen for incoming SMS and then do something once it detects an SMS.
Now it works , But if I wait for a little while and then try sending myself an SMS to see if the service is still up , the service does not do any thing implying that the service is down(I think), So my question is , Why would the service be down if i used 'START_REDELIVER_INTENT'?
-I remove the notification in onDestroy function in the service. So while the service stops working after a while the notification is still there implying that the service has not been destroyed
You need autorestart service after reboot.
Manifest:
<service android:exported="false" android:name=".service.YourService" android:enabled="true"></service>
<receiver android:name=".service.YourBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
Also permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Define receiver:
public class YourBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Intent serviceIntent = new Intent(arg0, YourService.class);
arg0.startService(serviceIntent);
}

GCM message received but not displayed - Broadcast receiver result=CANCELLED - Service force stop

I have implemented GCM messaging at my app and server and everything works fine but not on every phone!
The main problem is:
When app is opened i get the GCM message and i generate the notification as it's supposed, but when the app is closed i can see(through LOGCAT) that the message was received but cancelled -> "Broadcast receiver, result=CANCELLED".
Next thing is that i cannot get my app-services to work in the background. As long as i "close" my app from the "recent activities" menu it also stops in the background(going under Settings -> Apps -> "MY_APP" -> force stop is disabled).
I have done a lot of research and i think the cause may be that Huawei P8(the primary testing device) forcefully closes all apps automatically when you swipe them away from the "recent activities" tab. But if that's the case other apps like "Facebook", "Viber" and so on would not send me push notifications.
Manifest.xml
<receiver
android:name="com.happyhour.gcm.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.REBOOT"/>
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<action android:name="android.intent.action.BATTERY_CHANGED"/>
<action android:name="android.intent.action.USER_PRESENT"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.happyhour.main" />
</intent-filter>
</receiver>
<service
android:name="com.happyhour.gcm.GcmIntentService" >
</service>
<receiver android:name="com.happyhour.gcm.UpdateReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<action android:name="android.intent.action.PACKAGE_INSTALL"/>
<data android:path="com.happyhour.main"
android:scheme="package" />
</intent-filter>
</receiver>
GCMBroadCastReceiver
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("GcmBroadcast",intent.getExtras().toString());
SharedPreferences settings = context.getSharedPreferences("MyPrefsFile", 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
//do nothing
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}else{
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
}
GCMIntentService
public class GcmIntentService extends IntentService {
private String TAG = "GcmIntent";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
public void onCreate(){
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
Log.i(TAG, "Received: " + extras.toString());
String messageType = gcm.getMessageType(intent);
Log.i(TAG, "Message type:" + messageType);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification(extras.getString("message"), extras.getString("title"));
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg, String title) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
if(title.isEmpty()){
title="Happy Hour plus";
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, SplashScreen.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] {250,250,250,250})
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
public boolean checkApp(){
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equalsIgnoreCase("com.happyhour.main")) {
return true;
} else {
return false;
}
}
}
I am confused! I can't find the root of the cause.
Thanks in advance.
So apparently seems like EMUI interface of Huawei (P8 in my case) has a special way to handle things.
After installation of each app, it will prompt a toggle button asking you, whether or not, to allow this certain app to run in background.
So if an app comes straight from the Google Play store it won't prompt you this "Run in background" allowance button because it's a "trusted source" .
If you just export your .apk from Android Studio and install it straight to your phone it will prompt the button as shown above because installing straight on your phone falls in the case of the "untrusted source".
Finally if you are using the USB debugger option to install the .apk on the phone it will NEVER prompt the button and it will always act like you have pressed "off". Everytime you close the app it will force close all its tasks.
So, what i did was to transfer my Android-Studio-generated .apk into my phone and install it manually. When it prompted the button i toggled it to "ON" and that's it. I can finally receive GCM messages when app is closed!
I think that's an EMUI bug/special-app-handling problem.
Special thanks #TeChNo_DeViL for his help.
You are using very old libraries. Consider switching to latest official GCM libraries. Make your listener extend GcmListenerService. Look up official docs for the same. Also it's far easier to maintain.
Ensure all TODO's mentioned below are properly done:
Register for the Project in Google Developer Console with a unique project name and package name, your package name for your App and App Project names must match the ones in the Console.
Put the google_services.json configuration file in the app/ directory. Open it and verify whether the API_KEY in the file and one shown on the configuration in the Google Developer Console match, so does your package names. Also check status of google cloud messaging must be 2.
Follow the detailed steps in Set up a GCM Client App on Android. All the listeners must be properly implemented.
Once your app is running, Log the generated GCM Registration token, send it to your server and cross check the one logged in the adb console with the one received on the server, both must match.
Still if nothing works, use this sample app as your reference. You can copy the listeners, RegistrationIntentService.java file and manifest, but don't forget to change the package names to your package name (in the AndroidManifest.xml package name references as well, specially for the listeners)

Good practice for Android services?

I want to create an independent service of my main activity. This service is started at boot my phone and retrieves information via webservice every x minutes.
What are the best practices to do this?
Launch a service with BOOT_COMPLETED action?
There he other actions to launch a service without launching the main activity?
Another design or best practice?
I want a service with the same behavior as Facebook for example. This service is active all the time and displays a notification when you receive a message. If you click on the notification, it opens the Facebook application. But that kills the application, served remains active for receiving new messages.
My first test kills my service when I want to kill my main activity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.mrbmx"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="fr.mr.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>
<receiver android:name="fr.mr.service.MyReceiver"
android:enabled="true"
android:exported="false"
android:label="OnBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="fr.mr.service.LocalService"
android:enabled="true"
android:exported="false"
android:label="LocalService" />
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="#string/mapKey"/>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
</application>
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = MyReceiver.class.getName();
#Override
public void onReceive( Context ctx, Intent i ) {
Log.d( TAG, "MyReceiver.onReceive : " + i.getAction() );
ctx.startService(new Intent().setComponent(new ComponentName(
ctx.getPackageName(), LocalService.class.getName())));
}
}
public class LocalService extends Service{
private static final String TAG = LocalService.class.getName();
private NotificationManager mNM;
// Unique Identification Number for the Notification.
// We use it on Notification start, and to cancel it.
private int NOTIFICATION = 1332;
private Timer timer ;
private int mId;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.i(TAG, "onCreate");
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
timer = new Timer();
Notification note = new Notification( 0, null, System.currentTimeMillis() );
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground( 0, note );
/*
Notification.Builder mBuilder =
new Notification.Builder(this)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("test title")
.setContentText("test content")
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
startForeground(1, mBuilder.getNotification());*/
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
mId = startId;
new Thread(new Runnable() {
public void run() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
showNotification();
}
}, 0, 60000);
}
}).start();
return START_STICKY;
}
#Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
mNM.cancel(NOTIFICATION);
}
/**
* Show a notification while this service is running.
*/
private void showNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(getString(fr.mrbmx.R.string.notification_title))
.setContentText(getString(fr.mrbmx.R.string.notification_text))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
}
}
Your service does not need to be active all the time to receive messages. Facebook, along with just about every other push based system, use Google Cloud Messaging (GCM) to wake up your device and send a message to your application from the remote server.
Of course, if you only need to periodically check (rather than be pushed information in near real time), then you can schedule an alarm to start your service every X minutes or build a Sync Adapter - an Android component specifically built to periodically load data from a remote server.
Note that many applications combine the two approaches and run a sync adapter in response to a GCM push.
I want to create an independent service of my main activity. This
service is started at boot my phone and retrieves information via
webservice every x minutes.
You can certainly do this by registering a BroadcastReceiver on your AndroidManifest.xml that responds to BOOT_COMPLETED and launch the Service from it. Your app will need to be ran at least once for BOOT_COMPLETED to be delivered (before API 11 it wasn't the case). Also, consider the implications of pulling data from a server too often (i.e. battery, etc).
I want a service with the same behavior as facebook for example. This
service is active all the time and displays a notification when you
receive a message. If you click on the nitification, it opens the
facebook application. But that kills the application, served remains
active for receiving new messages.
At least for their chat application, Facebook uses MQTT, which is a M2M publish/subscribe asynchronous mechanism. They do not pull data from the server every X minutes. They just listen to incoming data when it is broadcasted. If you want to use MQTT there is an open source project called Eclipse Paho that you might be interested in.

Android: Cannot replace bundle from a service on Restart

I am trying to pass some values by using a bundle through a pending intent to my activity from a service. If the app is just started everything works fine but when the app is in resume mode, though my service receives new values from the remote server and put them in the pendingintent to pass to the activity, the activity shows the old values. Here is the code on service side:
private void sendNotification(String wholemsg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
/* Do something to extract salesID and notificationmessage from wholemsg
....
....
....
salesID=....
notificationmessage=...
....
*/
Bundle bundle=new Bundle();
bundle.putString("msg", notificationmessage);
bundle.putString("strsalesID", salesID);
notificationIntent.replaceExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_ONE_SHOT+PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("AppV001 Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationmessage))
.setContentText(notificationmessage);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
And this is onRestart method on my activity:
#Override
protected void onRestart() {
super.onRestart();
NotificationManager mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1);
try {
Intent intent = getIntent();
if (intent.hasExtra("msg") && intent.hasExtra("strsalesID")) {
String strmsgtitle = intent.getStringExtra("msg");
salesID = intent.getStringExtra("strsalesID");
titletext.setText(getString(R.string.str_ettitle) + salesID);
}
} catch (Exception ex) {
return;
}
}
The problem is that the salesID holds the previous value when the app comes back from hidden mode. It seems that the service cannot change the bundle of activity while it is hidden.
Many thanks in advance for your time!
I have found what was wrong with what my code and I want to post it here in case someone else faced the same problem. acj was right and there was a problem with my launch mode. My original application manifest was this:
<activity
android:name="com.example.appv001.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>
Since the launch mode wasn't declared the standard mode was taken automatically. We can have four launchMode(look at this):
The 'standard' is the default value. The four values fall into two
groups:
'standard' and 'singleTop' can instantiate multiple activity instances and the instance will stay in the same task.
For 'singleTask' or 'singleInstance', the activity class uses the singleton pattern, and that instance will be the root activity of a
new task.
Since my activity had standard launch mode, when the service was calling it a new instance of the activity was created and the intent was passed to the this new activity. Therefore instead of invoking "onNewIntent()", the "onCreate" method was invoked, in the other words the "onNewIntent()" was never called to set the bundle and etc. I changed the activity manifest to this and set the launch mode to singleTask (android:launchMode="singleTask) and the problem just solved:
<activity
android:name="com.example.appv001.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
I hope this helps someone else.

android notification always relaunches activity

First time poster here, please excuse my lengthy post - I want to provide all the necessary info.
I am trying to achieve the coveted resume from clicking on notification functionality, but I am having some difficulties. First off, details(code below):
Project Properties
Android Developer Tools Build: v21.1.0-569685
Project Build Target : 4.2.2
Platofrm : 4.2.2
API Level : 17
SDK Target : 17
SDK min : 14
Android Device Chooser : Android Device : Nexus 4
MyApp launches MyAppService via startService
MyAppService's onStartCommand function uses NotificationCompat.Builder object to create a bar in the pull down notification.
The behavior I am trying to achieve :
Launch an app with a notification bar entry(e.g. Mail)
Start MyApp(this will also start MyAppService)
Pull down the notification bar and select MyAppService(yes, MyApp is currently on screen
Notification bar should just roll up w/o doing anything
What I am noticing is that MyApp will minimize out, and a new instance of MyApp will maximize(similar transition to when the app is being launched). I expect this behavior when I select on MyAppService when I have Mail app on top(Mail app to minimize and for MyApp to maximize).
There have been many code snippets and suggestions but I can't seem to get it to work; so here are the contents of my files :
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#drawable/eyeview"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.MyApp.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>
<service
android:name=".service.MyAppService"
android:label="MyAppService">
</service>
</application>
MyApp/MainActivity.java
public static Intent serviceIntent;
public static Messenger clientMessenger;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstance);
if (getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
{
finish();
return;
}
setContentView(R.layout.activity_main);
...
[stuff specific to app, like setting up Fragments]
...
MainActivity.serviceIntent = new Intent(this, MyAppService.class);
MainActivity.serviceIntent.putExtra("clientMessenger", clientMessenger);
startService(MainActivity.serviceIntent);
}
MyAppService.java
#Override
private int onStartCommand(Intent intent, int flags, int startId)
{
NotificationCompat.Builder ncB = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.icon_app)
.setContentTitle("MyAppService")
.setSmallIcon(R.drawable.app);
ncB.setContentText("Click to start MyApp");
Intent nIntent = new Intent(getApplicationContext(), MainActivity.class);
nIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
nIntent.setAction(Intent.ACTION_MAIN);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
stackBuilder.addNextIntent(nIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int nId = 1;
Notification notification = ncB.build();
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notificationManager.notify(nId, notification);
sendMessengerToClient(intent);
startForeground(nId, ncB.build());
return Service.START_NOT_STICKY;
}
I hope I included all the enough information - I've been tweaking the code I got from SO just to see if this would work - in EVERY case, the topmost application minimizes out to black screen, and MyApp would maximize and MainActivity.java's onCreate function gets called.
I just want the notification pulldown to just scroll up if MyApp is already topmost.
Thanks in advance!
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
By setting PendingIntent.FLAG_UPDATE_CURRENT and Intent.FLAG_ACTIVITY_SINGLE_TOP flags you can achieve this I guess. It won't create your activity if its already running.
In my case, the answer have by Shashika worked but in a weird fashion. I HAD TO RESTART THE PHONE! :)

Categories

Resources