Android Notification Preferences - java

I am trying to connect my check box preferences with my notification such that when the user clicks on any of the check box preferences, the Notification works as specified. I want the "entering" to work only if the preference "alarm entering" is clicked on. Same for exiting and vibration.
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering){
Log.d(getClass().getSimpleName(), "entering");
}
else{
Log.d(getClass().getSimpleName(), "exiting");
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String alertName = prefs.getString("name_preference", "");
String alertMessage = prefs.getString("message_preference", "");
//boolean enteringRegion = prefs.getBoolean("alarm_entering", true);
//boolean exitRegion = prefs.getBoolean("alarm_exiting", false);
//boolean vibrate = prefs.getBoolean("vibrate_preference", true);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, null, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(context, alertName, alertMessage, pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private Notification createNotification(){
Notification notification = new Notification();
notification.icon = R.drawable.icon_notification;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_LIGHTS;
long[] vibrate = new long[] {2000, 2000, 2000, 2000, 2000};
notification.vibrate = vibrate;
Uri ringURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
notification.sound = ringURI;
notification.ledARGB = Color.BLUE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;
return notification;

I'd try like that:
myPrefListner = new OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
{
//check if alarm key is set as wanted and if so launch notification
}
};
But I'm not quite sure what you mean by "entering"?

Related

NotificationChannel not working for Android 8 and above

I'm new to developing an application. Currently, I'm working on push notification. Before this, I'm trying using Android 4.4, and the push notification work just fine. But, now I'm trying to debug on my Android 9 (Pie), but it seems like the notification does not appear.
I already try a few solutions. They suggest to use a notification channel for Android 8 and above. I have tried some of the solution from here: Previous question answer and here Previous question answer.
But, I don't know why it does not work for me.
Here is my code
public void onReceive(final Context context, final Intent intent) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
nm.createNotificationChannel(mChannel);
}
if (!intent.getExtras().getBoolean("cancel", false)) {
this.context = context;
prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
notification = new NotificationCompat.Builder(context, channelId);
count = intent.getExtras().getInt("count");
name = prefs.getString("name"+count, "");
hours = prefs.getInt("hora"+count, 8);
minutes = prefs.getInt("minuto"+count, 0);
minutesBefore = prefs.getInt("minutesBefore", 30);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH)
isScreenOn = pm.isInteractive();
else
isScreenOn = pm.isScreenOn();
if (!isScreenOn) {
#SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
wl.acquire(10000);
#SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
wl_cpu.acquire(10000);
}
/**
* notification
*/
final Intent notificationIntent = new Intent(context, Broadcast_TakenAction.class);
//Broadcast_TakenAction gets called when notification is clicked
notificationIntent.putExtra("count", count);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pIntent = PendingIntent.getBroadcast(context, count, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setAutoCancel(true);
notification.setLargeIcon(drawableToBitmap(ResourcesCompat.getDrawable(context.getResources(), R.drawable.notification_large_icon, null)));
notification.setSmallIcon(R.drawable.small_icon);
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle(name);
notification.setContentIntent(pIntent);
notification.setPriority(0);
notification.addAction(R.drawable.check, "Taken", pIntent);
if (intent.getExtras().getBoolean("shownBefore", false)) {
Runnable delayedThreadStartTask2 = new Runnable() {
#Override
public void run() {
new Thread(
new Runnable() {
#Override
public void run() {
for (int incr = 0; incr < minutesBefore; incr++) {
if (!intent.getExtras().getBoolean("cancel", false)) {
int time_left = minutesBefore - incr;
notification.setContentText(time_left + "m left.");
nm.notify(count, notification.build());
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException ignored) {
}
}
}
realNotification();
if (prefs.getBoolean("vibrates", true)) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
}
}
}
).start();
}
};
delayedThreadStartTask2.run();
} else {
realNotification();
}
}
}
I'm not sure what wrong with my code. Please correct me if I'm wrong.
this code worked for me in any API number:
public void Notificate() {
try {
final String NOTIFICATION_CHANNEL_ID = "10001";
String notification_title = getResources().getString(R.string.label);
String notification_message =jsonArray.get(4).getAsString() ;
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ActivityMain.this)
.setSmallIcon(R.drawable.tahlil)
.setContentTitle(notification_title)
.setContentText(notification_message)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400})
.setSound(alarmSound);
Intent resultIntent = new Intent(getApplicationContext(), ActivityChatList.class);
resultIntent.putExtra("menuFragment", "favoritesMenuItem");
// resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getApplicationContext(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
if (mNotifyMgr != null) {
mNotifyMgr.createNotificationChannel(notificationChannel);
}
}
if (mNotifyMgr != null) {
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
} catch (Exception e) {
}
}

Specify time delay for sending Notification in Android Studio?

I have setup Notification Channels in Android Studio for sending my notifications.
So far, I can send a notification when I click a button.
However, I want to add a delay to when the notification is sent.. for example, send the notification after 20 seconds.
I know there is a function in the AlarmManager for System.getTimeInMillis, that would be related to this, but not sure where to go from here.
Here is my code:
public class MyNotificationPublisher extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
public class EmailActivity extends AppCompatActivity {
private Button btnSend;
private NotificationManagerCompat notificationManager;
private long tenSeconds = 10000L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
notificationManager = NotificationManagerCompat.from(this);
btnSend = findViewById(R.id.button_send);
}
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
You can just schedule the notifications to be sent :-
Use the following method :
public void scheduleNotification(Context context, long delay, int notificationId)
{
//delay is after how much time(in millis) from current time you want to schedule the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(context.getString(R.string.title)) .setContentText(context.getString(R.string.content)) .setAutoCancel(true) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent intent = new Intent(context, YourActivity.class);
PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(activity); Notification notification = builder.build();
Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then, the receiver class:
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(final Context context, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(notificationId, notification);
}
}
Then, call scheduleNotification with the appropriate arguments.
Use a handler to delay the execution of notification sending code
Update your code like that
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(1, notification);
}
}, 20000);
}

How to show notification from broadcast receiver?

I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?
This is Service:
public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private static final int NOTIF_ID = 1;
#Override
public void onCreate() {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
registerReceiver(mReceiver, filter);
super.onCreate();
}
private void startForeground() {
startForeground(NOTIF_ID, getMyActivityNotification(""));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.startForeground();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
Log.i("onDestroy Reciever", "Called");
}
super.onDestroy();
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
private Notification getMyActivityNotification(String text) {
CharSequence title = "new";
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
}
return notification;
}
/* public void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIF_ID, notification);
}*/
}
And this is broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();
private final static String TAG = "LocationProviderChanged";
boolean isGpsEnabled;
boolean isNetworkEnabled;
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Log.i(TAG, "Location Providers changed");
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//Start your Activity if location was enabled:
if (isGpsEnabled || isNetworkEnabled) {
Log.i(TAG, "Location Providers on");
}
else {
Log.i(TAG, "Location Providers off");
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);
}
}
}
I can see logcat messages on changing location status but notification is not created
Changing notification code to this solved the problem
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "
com.example.fizatanveerkhan.citycops";
CharSequence name = "My Background Service";
String description = "My Background Service";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, 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 = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Service running")
.setContentText("new")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
NotificationManagerCompat notificationManagerq =
NotificationManagerCompat.from(context);
// notificationId is a unique int for each notification that you must define
notificationManagerq.notify(1, notificationBuilder.build());
}
So basically you need to create a foreground notification and update its contents on location change.
You can use the code below to create a foreground notification:-
//for foreground service notification
public Notification showForegroundNotification(String notificationTitle, String notificationBody, Intent intent, ServiceName serviceName) {
String id = mContext.getString(R.string.upload_notification_channel_id);
PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = mContext.getString(R.string.upload_notification_channel_name);
String description = mContext.getString(R.string.upload_notification_channel_description); //user visible
int importance = NotificationManager.IMPORTANCE_LOW;
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(false);
mChannel.enableVibration(false);
mChannel.setVibrationPattern(new long[]{0L});
mChannel.setSound(null, att);
if (mNotifyManager != null) {
mNotifyManager.createNotificationChannel(mChannel);
}
notificationBuilder
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVibrate(new long[]{0L})
.setSound(null)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setContentTitle(notificationTitle)
.setAutoCancel(true)
.setContentIntent(lowIntent);
} else {
notificationBuilder.setContentTitle(notificationTitle)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setVibrate(new long[]{0L})
.setSound(null)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setAutoCancel(true)
.setContentIntent(lowIntent);
}
if (notificationBody != null) {
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody));
}
notificationBuilder.setContentText(notificationBody);
return notificationBuilder.build();
}
and you need to call startForegroundService();
private void startForegroundService(){
String dataTitle = SharedPrefer.getLastUpdatedLocationName();
String dataContent = SharedPrefer.getLastUpdatedLocation();
Intent intent = new Intent(WITHU.getAppContext(), MapLocateActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startForeground(121, showNotification.showForegroundNotification(dataTitle, dataContent, intent, ServiceName.SMART_LOCATION, -1, false));
}
So it will pass the updated location name and location which you can collect from SharedPreference or also can be called directly onLocationChanged.

notification for low battery

i was trying to pop a notification when the device have under 15% battery left.
but it shows the notification every time, also when i have over 15%.
this is my code:
public class MainActivity extends Activity {
public int battery, level;
private static final int DIALOG_EXIT=1;
Button Hscore,ToInfo,ToProj;
ImageView Easter,EXIT,Help,Info;
private TextView contentTxt;
public BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "% Battery");
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
contentTxt = (TextView) this.findViewById(R.id.txtbattery);
if(level <= 15)
{
Intent Charge = new Intent(MainActivity.this,ChargeActivity.class);
// Intent st =new Intent(android.provider.Settings.ACTION_SETTINGS);
String title="you have low battery", message="charge your phone";
int icon = R.raw.duck_yellow;
int mNotificationId = 001;
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getBaseContext(),
0,
Charge,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getBaseContext());
Notification notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(resultPendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(getBaseContext().getResources(), R.raw.duck_yellow))
.setContentText(message).build();
NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, notification);
}
what should i do to fix this?
i think its something to do with the private/public variables

Start Activity while Countdown is running

I have a problem with my Android app at the moment. I use the Google Client Message Service to send messages to my Android App. If the user opens the app, he starts on the HomeActivity.
When the user now receives my message from the server and press on the push message, the app starts a new intent with the AlertActivity.
At this point, I pass the time (saved in the message) with putExtra to the new activity, where i use it for a CownDownTimer. Till this point everything is ok and the countdown works perfect.
The problem is now, when the user minimizes the app and open it again.
At this Point the user is not redirected to my AlertActivity again but to my HomeActivity.
After the CountDownTimer Ends the AlertSound is played, but he can't cancel it, because he can't show the activity again.
How can I redirect the User to the AlertActivity if he starts the app while the CountDown is running?
My AlertActivity
package com.prgguru.example;
public class AlertActivity extends Activity {
String str;
Boolean running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
final TextView txttime = (TextView) findViewById(R.id.txtalert);
str = getIntent().getStringExtra("msg");
Integer time = Integer.parseInt(str);
time = time; //*60000;
txttime.setText(time+"");
CountDownTimer Count = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
running = true;
txttime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
//txttime.setText(""+millisUntilFinished / 1000);
}
#Override
public void onFinish() {
txttime.setText("Finished");
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.alarm);
mp.start();
}
};
Count.start();
}
public boolean getRunning(){
return false;
}
}
GCMIntentService
public class GCMIntentService extends IntentService {
// Sets an ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification(extras.get(ApplicationConstants.MSG_KEY)+"");
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Intent resultIntent = new Intent(this, AlertActivity.class);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Alert")
.setContentText("You've received new message.")
.setSmallIcon(R.drawable.ic_launcher);
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
//defaults = defaults | Notification.DEFAULT_LIGHTS;
//defaults = defaults | Notification.DEFAULT_VIBRATE;
// defaults = defaults | Notification.DEFAULT_SOUND;
Notification notification = mNotifyBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alarm);
notification.defaults |= Notification.DEFAULT_VIBRATE;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("New message from Server");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, notification);
}
}

Categories