Android 13 New notification appears after old one notification clear. When first notification show then new notification received on onMessageReceived method but it will display if i have old notifiction cleared form notification bar. otherwise it will not showing on notification bar.
My FirebaseMessageingService class as below
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
//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());
}
}
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
sendRegistrationToServer(token);
}
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
private void sendNotification(String title,String messageBody) {
int uniqueCode=Prefs.getUniqueCode(getApplicationContext());
if(uniqueCode==1000){
uniqueCode=0;
}
Log.d("uniqueCode",uniqueCode+"");
Intent intent
= new Intent(this, LoginActivity.class);
// Assign channel ID
String channel_id = "Default";
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent
= PendingIntent.getActivity(
this, uniqueCode, intent,
PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Prefs.setUniqueCode(getApplicationContext(),uniqueCode+1);
NotificationCompat.Builder builder
= new NotificationCompat
.Builder(getApplicationContext(),
channel_id)
.setSmallIcon(R.drawable.applogo)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000,
1000, 1000})
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
builder = builder.setContentTitle(title)
.setContentText(messageBody)
.setSmallIcon(R.drawable.applogo)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody));
NotificationManager notificationManager
= (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel
= new NotificationChannel(
channel_id, "Default channel",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(
notificationChannel);
}
notificationManager.notify(0, builder.build());
}
}
Related
I am trying to make a custom incoming call notification like WhatsApp for my app if I don't use this custom layout then my notification is working. I am trying this for the first time any help will be appreciated.
This is my FireBaseMessagingService Class
public class MyFireBaseMessagingService extends FirebaseMessagingService {
private String CHANNEL_ID = "channel-02";
private String CHANNEL_NAME = "Channel Ring";
long[] pattern = {500, 500, 500, 500, 500, 500, 500, 500, 500};
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
Log.e("NewToken", s);
getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
}
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e("Notification", remoteMessage.getFrom());
showSimpleNotification(getApplicationContext(), remoteMessage, remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
}
public static String getToken(Context context) {
return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
}
#SuppressLint("RemoteViewLayout")
#RequiresApi(api = Build.VERSION_CODES.P)
public void showFullScreenIntent(RemoteMessage remoteMessage, String title, String body) {
Intent receiveCallIntent = new Intent(getApplicationContext(), FCMReceiver.class);
receiveCallIntent.putExtra("appointment_id", remoteMessage.getData().get("appointment_id"));
receiveCallIntent.putExtra("message", title);
receiveCallIntent.setAction("RECEIVE_CALL");
Intent cancelCallIntent = new Intent(getApplicationContext(), FCMReceiver.class);
receiveCallIntent.putExtra("appointment_id", remoteMessage.getData().get("appointment_id"));
receiveCallIntent.putExtra("message", "Call Rejected");
receiveCallIntent.setAction("CANCEL_CALL");
PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1200,
receiveCallIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1201,
cancelCallIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_call_notification);
remoteViews.setImageViewResource(R.id.caller_image, R.drawable.icon);
remoteViews.setTextViewText(R.id.caller_name, body);
remoteViews.setTextViewText(R.id.call_type, title);
remoteViews.setOnClickPendingIntent(R.id.btnAccept, receiveCallPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.btnDecline, cancelCallPendingIntent);
#SuppressLint("ResourceAsColor") NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(remoteViews)
.setCustomHeadsUpContentView(remoteViews)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setTimeoutAfter(30000)
.setOngoing(true)
.setVibrate(pattern)
.setSound(ringtone)
.setFullScreenIntent(receiveCallPendingIntent, true);
NotificationChannel channel = createChannel();
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Notification incomingCallNotification = notificationBuilder.build();
mNotificationManager.createNotificationChannel(channel);
mNotificationManager.notify(120, incomingCallNotification);
}
This is my channel
public NotificationChannel createChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setDescription("Call Notifications");
channel.setSound(Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ringtone),
new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_RING)
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build());
channel.shouldVibrate();
channel.enableVibration(true);
channel.setVibrationPattern(pattern);
Objects.requireNonNull(getApplicationContext().getSystemService(NotificationManager.class)).createNotificationChannel(channel);
return channel;
}
return null;
}
This is my FCMReceiver Class
public class FCMReceiver extends BroadcastReceiver {
private Context mContext;
private String mTitle;
private String mContent;
String action = "";
#Override
public void onReceive(Context context, Intent intent) {
if (context != null) {
mContext = context;
}
Log.e("Receiver", "Receiver a notification");
mTitle = intent.getStringExtra("message");
if (mTitle != null && !mTitle.isEmpty()) {
Log.e("action", "message : " + mTitle);
performActionClicks(context, mTitle, intent);
Intent iclose = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(iclose);
context.stopService(new Intent(context, MyFireBaseMessagingService.class));
}
if (intent.getStringExtra("gcm.notification.title") != null) {
if (intent.getStringExtra("gcm.notification title").equalsIgnoreCase("New Appointment")) {
ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
boolean isInBackground = myProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
if (isInBackground) {
Intent launchIntent = new Intent(context, HomeActivity.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchIntent.putExtra("appointment_id", intent.getStringExtra("appointment_id"));
}
}
}
if (intent.getStringExtra("notification") != null) {
}
}
private void performActionClicks(Context context, #NonNull String mTitle, Intent intent) {
if (!mTitle.isEmpty()) {
if (mTitle.equalsIgnoreCase("Ringing")) {
Intent intentCallReceive = new Intent(context, VideoChatViewActivity.class)
.putExtra("appointment_id", intent.getStringExtra("appointment_id"));
intentCallReceive.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intentCallReceive);
NotificationManagerCompat.from(mContext).cancel(null, 120);
} else if (mTitle.equalsIgnoreCase("Declined")) {
} else if (mTitle.equalsIgnoreCase("Call Rejected")) {
NotificationManagerCompat.from(mContext).cancel(null, 120);
}
}
}
In you NotificationBuilder you need to set notification category to NotificationCompat.CATEGORY_CALL and style to NotificationCompat.BigTextStyle() like this
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(remoteViews)
.setCustomHeadsUpContentView(remoteViews)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setTimeoutAfter(30000)
.setStyle(NotificationCompat.BigTextStyle())
.setCategory(NotificationCompat.CATEGORY_CALL)
.setOngoing(true)
.setVibrate(pattern)
.setSound(ringtone)
.setFullScreenIntent(receiveCallPendingIntent, true);
Am trying to save all notification message to Firebase Realtime Database. But it doesn't work when app is not running, any notification that is received when app is closed will not be saved to Firebase Database. But any notification that is received when am making use of the app will be saved.
Please can anyone advice me how to get this working?
Below is my saveTokenToDatabase method which am using to save notification.
public void saveTokenToDatabase(String title, String message, String image) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference notificationDatabase = database.getReference("user_notifications");
String key = notificationDatabase.push().getKey();
String userSessionId = "peter123";
if(userSessionId.equals("NULL")){
return;
}
//Create Object saveNotifications
saveNotifications newmessages = new saveNotifications(message, title, "firebase", image, userSessionId, key);
notificationDatabase.child(userSessionId).child(key).setValue(newmessages).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(_this, "Token Saved", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(_this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
Below is the a send method which I call in Firebase onMessageReceived method for RemoteMessage
void send(int type, String title, String message, Bitmap image, String imageurl, String clickAction) {
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) _this.getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager != null){
createChannel(notificationManager);
}
Intent intent = new Intent(_this, MainActivity.class);
switch(type){
case 1:
title = _this.getString(R.string.loc_fail);
message = _this.getString(R.string.loc_fail_text);
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
break;
case 2:
title = _this.getString(R.string.app_name);
message = _this.getString(R.string.loc_perm_text);
intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
break;
case 3:
default:
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
//intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("NotificationClickAction", clickAction);
PendingIntent pendingIntent = PendingIntent.getActivity(_this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = Uri.parse("android.resource://" + _this.getPackageName() + "/" + R.raw.notification_alert);
Vibrator vibration = (Vibrator) _this.getSystemService(Context.VIBRATOR_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(_this, Utils.CHANNEL_ID);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(message);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setColor(ContextCompat.getColor(_this, R.color.colorPrimaryDark));
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
notificationBuilder.setVibrate(new long[]{350, 700, 350, 700, 350});
notificationBuilder.setWhen(when);
notificationBuilder.setOngoing(false);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setTicker(_this.getString(R.string.app_name));
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
if(image != null){
notificationBuilder.setLargeIcon(image);
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image));/*Notification with Image*/
}else{
notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(_this.getResources(),R.mipmap.ic_launcher));
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(_this.getString(R.string.loc_perm_more)));
}
if(vibration != null) { vibration.vibrate(1000); }
if (notificationManager != null) {
notificationManager.notify(0, notificationBuilder.build());
saveTokenToDatabase(title, message, imageurl);
}
}
here is my full code
Start notification work well in Service, but when i change service to IntentService, the notification doesn't show, here is my service:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
Context ctx;
String channelId;
#Override
protected void onHandleIntent(Intent intent) {
ctx = getApplicationContext();
channelId = getPackageName() + " Channel";
createNotificationChannel();
startForeground(1, getNotification());
}
Notification getNotification() {
return new NotificationCompat.Builder(ctx, channelId)
.setContentTitle("Title")
.setContentText("Content")
.setSmallIcon(R.drawable.ic_android_black_24dp)
.build();
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = channelId + " Name";
String description = channelId + " Desc";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
I start service with following code:
startService(new Intent(this, MyIntentService.class))
I find the solution
IntentService cannot use startforeground since IntentService will stop after onHandleIntent, it cannot long-time foreground notification(see StartForeground for IntentService)
If I wanna use startForeground, use Service instead IntentSerivce
If I wanna use notification in IntentService, use NotificationManager#notify, see following code:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
Context ctx;
String channelId;
#Override
protected void onHandleIntent(Intent intent) {
initNotification();
}
private void initNotification() {
ctx = getApplicationContext();
channelId = getPackageName() + " Channel";
createNotificationChannel();
// startForeground(1, getNotification());
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, getNotification());
}
Notification getNotification() {
return new NotificationCompat.Builder(ctx, channelId)
.setContentTitle("Title")
.setContentText("Content")
.setSmallIcon(R.drawable.ic_android_black_24dp)
.build();
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = channelId + " Name";
String description = channelId + " Desc";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
I've created a service which consult notes if they are in recicle bin, it have to run once a day but with handler I think it will drain too much battery, So I need you help How can I do a task once a day without drain battery or other thing that's not a handler ?
When the app is launched the NotesApplication is created and start the NotesService class, it should be executing all day but it will drain battery, so I need to execute once a day
NotesApplication
public class NotesApplication extends Application {
String TAG = "NotesApplication";
Intent intent;
#Override
public void onCreate() {
// TODO: Implement this method
super.onCreate();
Log.d(TAG, "Application created");
intent = new Intent(getApplicationContext(), NotesService.class);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
Log.d(TAG, "Foreground service started");
getApplicationContext().startForegroundService(intent);
}else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
Log.d(TAG, "Service started");
getApplicationContext().startService(intent);
}
}
Notes Service
public class NotesService extends Service {
ArrayList<Notes> listNotas;
String TAG = "NotesService";
SQLiteHelperConnection conn;
#Override
public void onCreate()
{
// TODO: Implement this method
super.onCreate();
Log.d(TAG, "Notes service created");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
final NotificationManager mNotific= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Axco";
String description = "Service";
int importance = NotificationManager.IMPORTANCE_MIN;
final String ChannelID="Service Channel";
NotificationChannel mChannel = new NotificationChannel(ChannelID, name, importance);
mChannel.setDescription(description);
mChannel.setLightColor(ThemeClass.getColor());
mChannel.canShowBadge();
mChannel.setShowBadge(true);
mNotific.createNotificationChannel(mChannel);
final int code = 101;
String body= "Service Running";
Notification notification = new Notification.Builder(this, ChannelID)
.setContentTitle(getPackageName())
.setContentText(body)
.setBadgeIconType(R.drawable.ic_launcher)
.setNumber(1)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.build();
startForeground(code, notification);
}
conn = new SQLiteHelperConnection(this, "db_notas.db", null, 1);
listNotas = new ArrayList<Notes>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO: Implement this method
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
final NotificationManager mNotific= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Axco";
String description = "Service";
int importance = NotificationManager.IMPORTANCE_MIN;
final String ChannelID="Service Channel";
NotificationChannel mChannel = new NotificationChannel(ChannelID, name, importance);
mChannel.setDescription(description);
mChannel.setLightColor(ThemeClass.getColor());
mChannel.canShowBadge();
mChannel.setShowBadge(true);
mNotific.createNotificationChannel(mChannel);
final int code = 101;
String body= "Service Running";
Notification notification = new Notification.Builder(this, ChannelID)
.setContentTitle(getPackageName())
.setContentText(body)
.setBadgeIconType(R.drawable.ic_launcher)
.setNumber(1)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.build();
startForeground(code, notification);
}
final Handler handler = new Handler();
Runnable runnable = new Runnable(){
#Override
public void run()
{
// TODO: Implement this method
Log.d(TAG, "Service running");
listNotas.clear();
consult();
check();
handler.postDelayed(this, 15000);
}
};
handler.post(runnable);
return Service.START_STICKY;
}
private void consult(){
Log.d(TAG, "Consulting...");
SQLiteDatabase db = conn.getReadableDatabase();
Notes notas = null;
Cursor cursor = db.rawQuery("SELECT * FROM "+Utilities.TABLA_NOTA, null);
while (cursor.moveToNext()) {
notas = new Notes();
notas.setId(cursor.getString(0));
notas.setLastModified(cursor.getString(5));
notas.setLastModifiedDate(cursor.getString(7));
boolean a = Boolean.valueOf(cursor.getString(4));
if(a){
listNotas.add(notas);
}
}
}
private void check(){
//Do something
}
private void deleteNote(int position){
SQLiteDatabase db = conn.getWritableDatabase();
String[] parametros = {listNotas.get(position).getId()};
db.delete(Utilities.TABLA_NOTA, Utilities.ID+"=?", parametros);
listNotas.remove(position);
}
#Override
public IBinder onBind(Intent p1){
// TODO: Implement this method
return null;
}
Using Alarm Manager is efficient.
See implementation
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i= new Intent(context, AlarmManagerBroadcastReceiver.class);
//intent.putExtra(something you want to put);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// check if it is more than 11 am. if so set alarm for next day
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) {
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
// everyday at 11 am
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
// alarm set
Finally create a broadcast receiver to do the work you want.
I am not able to update the app with API 26.
The following error appears in when I try to run the project
Error:
"ServerRunningNotification.java": error: cannot find symbol method
setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
This is my code snippet which having Error
Code:
public class ServerRunningNotification extends BroadcastReceiver {
private static final String TAG = ServerRunningNotification.class.getSimpleName();
private final int NOTIFICATIONID = 7890;
public String iptext;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive broadcast: " + intent.getAction());
if (intent.getAction().equals(FtpServerService.ACTION_STARTED)) {
setupNotification(context);
} else if (intent.getAction().equals(FtpServerService.ACTION_STOPPED)) {
clearNotification(context);
}
}
#SuppressWarnings("deprecation")
private void setupNotification(Context context) {
Log.d(TAG, "Setting up the notification");
// Get NotificationManager reference
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager) context.getSystemService(ns);
// get ip address
InetAddress address = FtpServerService.getLocalInetAddress();
if (address == null) {
Log.w(TAG, "Unable to retreive the local ip address");
return;
}
iptext = "ftp://" + address.getHostAddress() + ":"
+ Settings.getPortNumber() + "/";
// Instantiate a Notification
int icon = R.drawable.ftp_icon;
CharSequence tickerText = String.format(
context.getString(R.string.notif_server_starting), iptext);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
// Define Notification's message and Intent
CharSequence contentTitle = context.getString(R.string.notif_title);
CharSequence contentText = String.format(context.getString(R.string.notif_text),
iptext);
Intent notificationIntent = new Intent(context, FTP_Start_Stop.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification
.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// Pass Notification to NotificationManager
nm.notify(NOTIFICATIONID, notification);
Log.d(TAG, "Notication setup done");
}
private void clearNotification(Context context) {
Log.d(TAG, "Clearing the notifications");
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager) context.getSystemService(ns);
nm.cancelAll();
Log.d(TAG, "Cleared notification");
}
}
According to here, setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) method was removed in Android M (API 23). So it won't work in API versions above 23.