Actually I'm implementing firebasePushNotification service which is working wihtout any issue . Now when I'm receiving push_notification and my app is in foreground by clicking the notification intent is being passed to the desired activity without any error. But when the app is in background or not opened clicking on the notification is not sending the intent to the desired activity and even it's not showing any error . I tried to refer some questions in SO about adding exported=true option in manifest.xml but it couldn't solve my issue.
Code of NotificationManager Class:
public void displayNotification(String title, String body,String post_owner_username,String post_owner_time,
String notif_commenter_username,String notif_comment_time,String follower_username,String type) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx, Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.new_icon)
.setContentTitle(title)
.setContentText(body);
Intent i = new Intent(ctx, ProfileHolder.class);
if (type.equals("likes")) {
Bundle b = new Bundle();
b.putString("post_owner_username", post_owner_username);
b.putString("post_owner_time", post_owner_time);
b.putString("what", "show_notification_post");
i.putExtras(b);
i.putExtra("Open", "starred");
}
else if (type.equals("comments")) {
Bundle b = new Bundle();
b.putString("post_owner_username",post_owner_username);
b.putString("post_owner_time", post_owner_time);
b.putString("notif_commenter_username", notif_commenter_username);
b.putString("notif_comment_time",notif_comment_time);
b.putString("what", "show_notification_post");
i.putExtras(b);
i.putExtra("Open", "starred");
}
else if (type.equals("comment_likes")) {
Bundle b = new Bundle();
b.putString("post_owner_username", post_owner_username);
b.putString("post_owner_time", post_owner_time);
b.putString("notif_commenter_username", notif_commenter_username);
b.putString("notif_comment_time", notif_comment_time);
b.putString("what", "show_notification_post");
i.putExtras(b);
i.putExtra("Open", "starred");
}
else if (type.equals("follow")||type.equals("follow_request")) {
Bundle b = new Bundle();
b.putString("searchUsername", follower_username);
i.putExtras(b);
i.putExtra("Open", "search_profile");
}
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, i, PendingIntent.FLAG_ONE_SHOT);
/*
* Setting the pending intent to notification builder
* */
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mBuilder.setAutoCancel(true);
mNotifyMgr.notify(1, mBuilder.build());
}
}
If you are using firebase push notification
You need to send a click_action attribute ...to open the desired activity when app is in background.
So try ..
Intent i = new Intent(click_action);
click_action is the intent-filter mapping to the desired activity. click_action is mandatory
instead of the Explicit intent call - explicit intent call in the above case will only work when the app is in foreground..
Here is how I've managed to open specific activity from notification when app is in the background/closed and to pass data through Intent.
Application
public class AppConfig extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
}
}
Manifest
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<!-- Don't forget to set exported attribute to true -->
<activity android:name=".MainActivity" android:exported="true"/>
MessagingService
public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String body = null;
if(remoteMessage.getNotification() != null) {
body = remoteMessage.getNotification().getBody();
}
String id = null;
// get data that server passed (if it passed any at all)
if(remoteMessage.getData().size() > 0) {
id = remoteMessage.getData().get("id");
}
sendNotification(body, id);
}
private void sendNotification(String messageBody, String id) {
// put data you want to send through intent
Bundle bundle = new Bundle();
bundle.putString("id", id);
// create intent, put data, and
Intent intent = new Intent(this, ActivityLogin.class);
intent.putExtras(bundle);
// IMPORTANT! clearing previous tasks so desired activity will launch
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// customising the notification
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Related
I added the following pice in the manifest to call the onMessageReceived function when a firebase message comes in:
<service android:name=".Notifications"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Here is my onMessageReceive function:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("NotificationService", "Notification received!");
Map<String, String> data = remoteMessage.getData();
String deep_link = data.get("deep_link");
String title = data.get("title");
String body = data.get("body");
Log.d("NotificationService", "Notification received!");
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.context.getApplicationContext(), "1");
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(new MainActivity(), Uri.parse(deep_link));
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle(title);
builder.setContentText(body);
NotificationManager notificationManager = (NotificationManager) MainActivity.context.getSystemService(MainActivity.context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "1";
NotificationChannel channel = new NotificationChannel(
channelId,
"1",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
But the function is never called does someone know where the problem lays?
I tried to send the notification with and without notification payload, tried the app in background state and foreground state, tried killing the app and then sending the notification
When clicking the notification it doesnt open the app or anything
Inside the onCreate method of my Service I create a notification by doing the following:
String channelId = "001";
String channelName = "myChannel";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
Notification notification;
Intent myIntent = new Intent("alarmReceiver");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
Notification.Action action = new Notification.Action.Builder(
Icon.createWithResource(this, R.drawable.ic_stop_black_24dp),
"action string",
pendingIntent).build();
//Modify notification badge
notification = new Notification.Builder(getApplicationContext(), channelId).setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(Notification.CATEGORY_SERVICE)
.addAction(action)
.build();
startForeground(101, notification);
}
The alarmReceiver in the Intent above is registered in my manifest as shown below (I did the following after seeing this question):
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="alarmReceiver" />
</intent-filter>
</receiver>
and here is my AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("onReceive - ","was called");
}
}
The notification is shown, as well as the button, but when I press the button nothing happens.
I'm not sure what I'm doing wrong. Any help would greatly be appreciated.
Set PendingIntent to foreground service, And potentially add a flag:
FLAG_UPDATE_CURRENT
PendingIntent pendingIntent = PendingIntent.getForegroundService(this, 0, myIntent, FLAG_UPDATE_CURRENT);
Your broadcast is Implicit, so if you want to use getBroadcast() it may be best to Explicitly declare the receiver by providing the intent with the componentName of the receiver.
eg:
intent.setComponent(new ComponentName("packagename","fully qualified class name"));
Have you declared the service in your manifest?
I have implemented FCM Push notifications in my Android App.
I get the all the notification JSON in data payload. And I have 'not added' 'Notification' tag on api. So in all the states (Foreground/Background/Killed) I got the notification in data payload only.
It is Working fine on Non-Customised OS phones like Moto, Google etc, In All States when an app is Foreground/Background/Killed. But the Problem is when I testing on the customised OS phones like Oppo, Vivo or MIUI the notification is arrived only when the app is in Foreground or Background (App is in Memory), Not arrived/appearing when App is "killed" (Not in Memory).
What should I do?
In any case, thank you for your time.
public class MyFirebaseMessagingService extends FirebaseMessagingService{
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
Log.e(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();
}
if (remoteMessage.getNotification()!=null)
sendNotification(remoteMessage.getNotification().getBody());
else
sendNotification("Body");
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null)
{
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
if (remoteMessage.getNotification()!=null)
sendNotification(remoteMessage.getNotification().getBody());
else
sendNotification("Body");
}
// 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.
}
// [END receive_message]
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
}
My AndroidManifest.xml file as below:
<!-- [START firebase_iid_service] -->
<service
android:name=".Firebase.FirebaseId">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name="Firebase.MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<!--
Set custom default icon. This is used when no icon is set for incoming notification messages.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_launcher_background" />
<!--
Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<!-- [START fcm_default_channel] -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
<!-- [END fcm_default_channel] -->
Well i have found a solution to this problem. Write a custom service for your application which continuously running in background and write one Broadcast Receiver to restart the service once it is killed. This works fine for me. I have tested this on Vivo, Oppo, Redmi phones. It is working!
My Service Code is as below--
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_NOT_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "Service Destroyed!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.myapp.startservice");
//Intent intent = new Intent("android.intent.action.BOOT_COMPLETED");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
super.onDestroy();
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
//thread = new Thread(this);
//startThread();
/*Intent alarm = new Intent(this.getApplicationContext(), MyBroadCastReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.getApplicationContext(), 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
//if(!alarmRunning)
{
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 10000, pendingIntent);
}
}*/
//send broadcast to your BroadcastReciever
Intent intent = new Intent("com.myapp.startservice"); //unique String to uniquely identify your broadcastreceiver
//Intent intent = new Intent("android.intent.action.BOOT_COMPLETED");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
//intent to restart your service.
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
if (alarmService != null) {
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
My BroadcastReceiver is as Below --
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
Log.e("BootCompleteReceiver", " __________BootCompleteReceiver _________");
}
}}
My AndroidManifest.xml file as below--
<!-- My Service -->
<service
android:name=".Service.MyService"
android:exported="false"
android:stopWithTask="false" />
<!-- My Broadcast Receiver -->
<receiver
android:name=".Service.MyBroadCastReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.myapp.startservice" />
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
And my MainActivity.java file code to start the service ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}
private void s()
{
Intent intent = new Intent(this, MyService.class);
startService(intent);
}}
This is an age old story with custom OS providers like MIUI, Vivo etc
They're very strict with their battery optimization policies and hence they won't allow even sticky services to restart when an app is closed and this is the primary reason why you're facing this issue.
Although there is nothing that you can do from your code that can help your users here but you can take them to their Security Center and ask them to enable auto-start feature.
To do this you have to add this piece of code:
try {
Intent intent = new Intent();
String manufacturer = android.os.Build.MANUFACTURER;
if ("xiaomi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
} else if ("oppo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
} else if ("vivo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
} else if("oneplus".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.oneplus.security", "com.oneplus.security.chainlaunch.view.ChainLaunchAppListAct‌​ivity")); }
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
context.startActivity(intent);
}
} catch (Exception e) {
Crashlytics.logException(e);
}
this app will take the user to the security center where you have to ask them to enable auto-start feature for your app.
Now apps like whatsapp and instagram don't have such issues but i don't clearly know the reason for this, As i have seen on my devices, auto-start is by default enabled for these apps.
i got an Android app, which is receiving push messages.
If the user is clicking on the push message, the activity GoToNotification is called.
This is working so far.
But how can I access the content of the push message? The Bundle.extra?
I am trying, to react on some content of the push message, but the bundle extra is always null.
here my code so far:
private void sendNotification(String msg, Bundle extras) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, GoToNotification.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Warning")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setExtras(extras)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
public class GoToNotification extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = this.getIntent().getExtras();
if (extras != null) {
System.out.println(extras.toString());
} else {
System.out.println("extras is null");
}
}
}
Intent notificationIntent = new Intent(context, SampleActivity.class);
notificationIntent.putExtra("EXTRA_ID", "ur data");
and in ur activity
if (extras != null) {
ID = extras.getString("EXTRA_ID");
}
Thanks, I managed to solve the problem, here is the code:
As written already, i need to put the extra content.
It's also important to set the requestId, it was not working without it.
Here is the code working:
private void sendNotification(String msg, String dpId) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, GoToNotification.class);
intent.putExtra("dpId", dpId);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,
intent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Test")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(Integer.parseInt(dpId), mBuilder.build());
}
public class GoToNotification extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); String regid;
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra("dpId")) {
System.out.println("Klick auf push dpid:" + intent.getStringExtra("dpId"));
}
}
}
}
Manifest:
<activity android:name=".GoToNotification" android:label="#string/app_name" />
I'm developing an online radio application. The application works in the background. When I click the NotificationManager, radioclass starts working again. I want to call the radioclass that are running. How can I do?
player = MediaPlayer.create(this, Uri.parse("http://...../playlist.m3u8"));
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
}
});
player.start();
final int notificationID = 1234;
String msg = "mesajjj";
Log.d(TAG, "Preparing to update notification...: " + msg);
NotificationManager mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, RadioClass.class);
//Here RadioClass running again. But RadioClass already running. I should call RadioClass that is running.
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.logotam)
.setContentTitle("Test FM")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(pendingIntent);
mNotificationManager.notify(notificationID, mBuilder.build());
If you want to go back to the same activity you are currently running, you can do it like this:
Add the following tag on your AndroidManifest.xml:
<activity
........
android:launchMode="singleTop" >
........
</activity>
Modify your PendingIntent like this:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
With this modifications, you ensure that your activity will only have one instance at any given time. On your activity class, you can also override the onNewIntent method:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
This method will handle all of the additional calls to your activity.