parse custom push sound - java

Sorry for my english. I use parse.com i want create custom sound when i get push. When I send a push, the phone just vibrates. There is no sound and the message does not show too.
This is my sound: image (i have not 15 reputation)
code:
public class MyBroadcastReceiver extends ParsePushBroadcastReceiver {
private int NOTIFICATION_ID = 1;
#Override
public void onPushOpen(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#Override
public void onReceive(Context context, Intent intent) {
try{
String jsonData = intent.getExtras().getString("com.parse.Data");
JSONObject json = new JSONObject(jsonData);
String title = null;
if(json.has("title")) {
title = json.getString("title");
}
String message = null;
if(json.has("alert")) {
message = json.getString("alert");
}
if(message != null) {
generateNotification(context, title, message);
}
} catch(Exception e) {
Log.e("NOTIF ERROR", e.toString());
}
}
private void generateNotification(Context context, String title, String message) {
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager mNotifM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(title == null) {
title = context.getResources().getString(R.string.app_name);
}
final NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.addAction(0, "View", contentIntent)
.setAutoCancel(true)
.setDefaults(new NotificationCompat().DEFAULT_VIBRATE)
.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/beep1.mp3"));
mBuilder.setContentIntent(contentIntent);
mNotifM.notify(NOTIFICATION_ID, mBuilder.build());
}
}
UPD:
This is not work too, i have standart sound
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "beep1.mp3");
return n;
}
UPD:
I pu mp3 to folder res/raw/beep1.mp3 and use ("android.resource://" + context.getPackageName() + R.raw.beep1); but its not help

Assuming that you have your own subclass of ParsePushBroadcastReceiver and you declared it in Manifest, I recommend you to put your mp3 file in the /raw folder and to change your getNotification() method as follows
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.defaults = 2;
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.beep1);
return n;
}
If you want just to change sound the getNotification() method is the only one you need to overrid

Its work for me! Import: sound mus be here: res/raw/beep1.mp3 and path like this "android.resource://" + context.getPackageName() +"/"+ "R.raw.beep1"
#Override
public void onReceive(Context context, Intent intent) {
try {
JSONObject json = new JSONObject(intent.getExtras().getString(
"com.parse.Data"));
alert = json.getString("alert").toString();
} catch (JSONException e) {}
notifySound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_launcher); //You can change your icon
mBuilder.setContentText(alert);
mBuilder.setContentTitle("Пользователь");
mBuilder.setSound(Uri.parse("android.resource://" + context.getPackageName() +"/"+ R.raw.beep1));
mBuilder.setAutoCancel(true);
resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, mBuilder.build());
}
}

Related

Custom Notification for incoming call not showing in android

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);

How I can call BroadcastReceiver from intent service?

I am trying to call BroadcastReceiver from intent service but it is never called:
public class IntentServiceTest extends IntentService {
public IntentServiceTest() {
super("IntentServiceTest");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(#Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Brodcast brodcast;
brodcast = new Brodcast();
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(brodcast, intentFilter);
}
}
}
Here is my BroadcastReceiver:
public class Brodcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "BroadcastReceiver", Toast.LENGTH_SHORT).show();
String NOTIFICATION_CHANNEL_ID = "100";
String channelName = "My back";
NotificationChannel channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(channel);
}
BluetoothAdapter bluetoothAdapter;
ArrayList<String> arrayList;
BluetoothDevice device;
NotificationManagerCompat notificationManagerCompat;
notificationManagerCompat = NotificationManagerCompat.from(context);
arrayList = new ArrayList<>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!arrayList.contains(device.getName())) {
arrayList.add(device.getName());
if (arrayList.size() >= 0) {
Toast.makeText(context, "s", Toast.LENGTH_SHORT).show();
}
}
Intent i = new Intent(context, MainActivity3.class);
i.putExtra("noti", NOTIFICATION_CHANNEL_ID);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder n = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification notification = n.setOngoing(true)
.setSmallIcon(R.drawable.ss)
.setContentTitle(arrayList.size() + device.getName())
.addAction(R.drawable.as, "Action", pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("App running"))
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
notificationManagerCompat.notify(1 , notification);
}
}
}
I need to call broadcast every 20 min; can anyone help me?

error: cannot find symbol method setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)

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.

Notification action button dosen't stop the alarm ringtone

I set an alarm and i want to disable the ongoing alarm using notification action button without opening the activity.
I have attached my whole code below.
When user set alarm it call the broadcast receiver and from them i call my ringtone service to start ringtone. and it will fire a notification. in that notification it will have a disable button. i have done all the resource i had found on internet. but
disable button on notification didn't work. where is my fault
onToggled button to start alarm from main activity
public void OnToggleClicked(View view) {
long time;
if (((ToggleButton) view).isChecked()) {
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
} else {
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
}
intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// setRepeating() lets you specify a precise custom interval--in this case,
// 1 minutes.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
My broadcast receiver class
public class AlarmReceiver extends BroadcastReceiver {
public static Ringtone ringtone;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
// using service class
Intent i = new Intent(context, RingtonePlayingService.class);
context.startService(i);
createNotification(context);
}
public void createNotification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("It is prayer time")
.setContentText("Prayer")
.setSmallIcon(R.mipmap.ic_launcher)
.setSubText("Tab to cancel the ringtone")
.setPriority(NotificationCompat.PRIORITY_HIGH);
//To add a dismiss button
Intent dismissIntent = new Intent(context, RingtonePlayingService.class);
dismissIntent.setAction(RingtonePlayingService.ACTION_DISMISS);
PendingIntent pendingIntent = PendingIntent.getService(context,
123, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action = new NotificationCompat.Action
(android.R.drawable.ic_lock_idle_alarm, "DISMISS", pendingIntent);
builder.addAction(action);
// end of setting action button to notification
Intent intent1 = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 123, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(123, notification);
}
My ringtoneplaying service class
public class RingtonePlayingService extends Service{
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
private Ringtone ringtone;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand");
if(intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
String action = intent.getAction();
if(ACTION_DISMISS.equals(action))
dismissRingtone();
return START_NOT_STICKY;
}
public void dismissRingtone() {
Intent i = new Intent(this, RingtonePlayingService.class);
stopService(i);
}
#Override
public void onDestroy() {
ringtone.stop();
}
That was my fault
When i click on disable on notification it again call the receiver class that's why ringtone keeps playing. So i keep some modifying and it works fine.
public class RingtonePlayingService extends Service {
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
private Ringtone ringtone;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if (intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
String action = intent.getAction();
if (ACTION_DISMISS.equals(action))
dismissRingtone();
else {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(this, alarmUri);
ringtone.play();
}
return START_NOT_STICKY;
}
public void dismissRingtone() {
// stop the alarm rigntone
Intent i = new Intent(this, RingtonePlayingService.class);
stopService(i);
// also dismiss the alarm to ring again or trigger again
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
aManager.cancel(pendingIntent);
// Canceling the current notification
NotificationManager notificationManager =
(NotificationManager)getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.cancel(321);
}
#Override
public void onDestroy() {
ringtone.stop();
}}

How to get Notification count with NotificationCompat.Builder

I am developing an android application one of it function is to alert the user if he exceeds the allowed speed , I want to send to the user three alert with notification ... I found some example of how to count the notification.number, but I am using
NotificationCompat.Builder
here is my code
public class SpeedService extends IntentService {
CharSequence appName ;
int count ;
MyReceiver myReceiver;
int speed ;
int allowedSpeed ;
public SpeedService() {
super("SpeedService");
}
#Override
protected void onHandleIntent(Intent intent) {
appName = getString(R.string.app_name);
allowedSpeed = APP.getInstance().getSharedPreferences().readInt("streetSpeed");
Log.e("streetSpeed" , allowedSpeed+"");
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(GPSService.MY_ACTION);
this.registerReceiver(myReceiver, intentFilter);
if(allowedSpeed <= speed && count ==0 ){
createNotification(R.raw.alert1, "");
}
if(allowedSpeed <= speed && count ==1){
createNotification(R.raw.alert2, "");
Log.e("NotificationCount" , count+"");
}
if(allowedSpeed <= speed && count ==2){
createNotification(R.raw.alert3, "");
}
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
speed = arg1.getIntExtra("speed", 0);
}
}
private void createNotification(int raw , String message){
int pendingNotificationsCount = APP.getPendingNotificationsCount() + 1;
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + raw);
Random random = new Random();
int ID = random.nextInt(9999 - 1000) + 1000;
Intent intent=new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("data", message);
intent.putExtra("KEY", "YOUR VAL");
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder= (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(appName)
.setContentText(message)
.setSmallIcon(R.drawable.marker_icon)
.setContentIntent(pendingIntent).setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setNumber(pendingNotificationsCount).setContentText(message);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(ID,builder.build());
MediaPlayer mp= MediaPlayer.create(this, raw);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setLooping(false);
mp.start();
pendingNotificationsCount ++;
APP.setPendingNotificationsCount(pendingNotificationsCount);
}
}
any help please ...

Categories

Resources