Start Activity while Countdown is running - java

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

Related

Android - notification button from/to service

I created a running service that generates a notification with a button. I would like to create a listener in the service to do something when the button is pressed.
The notification is simple with an addaction statement.
I success on sending data to a external broadcaster receiver but no luck with a local one.
I'm just trying to change a boolean value of the service from the notification.
Thank you
public class TrackerService extends Service {
private static final int REQUEST_RESULT = 200;
final static String PANIC_ACTION = "PANIC";
private Point point = new Point();
private static final String TAG = "TrackerService";
private static final String NOTIFICATION_CHANNEL_ID = "tracker_service.channel";
private IntentFilter panicIntentFilter;
protected final IBinder binder = new TrackerServiceBinder();
public BroadcastReceiver trackerServiceBroadcastReceiver;
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
panicIntentFilter = new IntentFilter();
panicIntentFilter.addAction("PANIC");
this.registerReceiver(trackerServiceBroadcastReceiver, panicIntentFilter);
}
public class trackerServiceBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG + " TSRECEIVER","Complete intent: " + intent.toString() + " extras intent: " + intent.getExtras().toString());
if (intent.getAction().equals("PANIC") && intent.hasExtra("PANIC")){
if (intent.getExtras().getBoolean("PANIC")) {
//point.setPanicState(true);
Log.d(TAG + " TSRECEIVER", "panic pressed - point.getPanic(): " + "true");
} else {
//point.setPanicState(false);
Log.d(TAG + " TSRECEIVER", "panic pressed - point.getPanic(): " + "false");
}
}
}
}
public class TrackerServiceBinder extends Binder {
public TrackerService getServiceInstance() {
return TrackerService.this;
}
}
public Boolean TogglePanicState() {
point.setPanicState( !point.getPanicState() );
return point.getPanicState();
}
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
Intent panicIntent = new Intent(this, trackerServiceBroadcastReceiver.class); // Prueba al broadcaster local
//Intent panicIntent = new Intent(this, TrackerService.class); // Prueba al servicio
//Intent panicIntent = new Intent(this, NotificationReceiver.class); // Prueba a un Broadcaster externo - Funciona
panicIntent.setAction("PANIC");
panicIntent.putExtra("PANIC", true);
PendingIntent panicPendingIntent = PendingIntent.getBroadcast(this, 123456, panicIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG + " Notification","Complete intent: " + panicIntent.toString() + " extras intent: " + panicIntent.getExtras().toString() + " Complete PendingIntent: " + panicPendingIntent.toString());
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Tracker Service - Channel", NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ou)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.addAction(R.drawable.alarm, "PANIC", panicPendingIntent)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(trackerServiceBroadcastReceiver);
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
}

Action button on Notification if not clicked on certain time will do something else

I have an app that if something happens it will pop up a Notification with an action button. if it pressed it will the app running but if not for a certain amount of time it will run another code.
I'm still confused about how to make that
EDIT :
Here is The code I tried
Main Activity.java :
public class MainActivity extends AppCompatActivity {
public NotificationManagerCompat notificationManager;
public TextView mViewLabel;
public ArrayList<Integer> lst = new ArrayList<Integer>();
boolean continueThread = true;
int count =0;
Thread t;
Timer j = new java.util.Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = NotificationManagerCompat.from(this);
mViewLabel = (TextView) findViewById(R.id.textChanger);
t = new Thread(){
#Override
public void run() {
if (continueThread) {
while (continueThread) {
lst.add(70);
lst.add(71);
lst.add(72);
lst.add(73);
lst.add(74);
lst.add(75);
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Collections.shuffle(lst);
mViewLabel.setText(String.valueOf(lst.get(count)));
}
});
}catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
}
};
}
public void BtnStart(View view){
t.start();
j.schedule(
new java.util.TimerTask() {
#Override
public void run() {
while(continueThread){
if(lst.get(count) < 80){
sendOnChannel1();
break;
}
count++;
}
}
},
5000
);
}
public void BtnStop(View view){
if(continueThread){
continueThread=false;
mViewLabel.setText("0");
}
}
public void BtnReset(View view){
if(!continueThread){
continueThread=true;
mViewLabel.setText("Click Start To Simulate Heartbeat");
}
}
public void sendOnChannel1() {
String title = "Title";
String message = "Testing";
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", message);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setColor(Color.BLUE)
.setContentIntent(contentIntent)
.addAction(R.mipmap.ic_launcher, "Toast", actionIntent)
.build();
notificationManager.notify(1, notification);
}
if something happens it will pop up a Notification with an action button
is on this code
j.schedule(
new java.util.TimerTask() {
#Override
public void run() {
while(continueThread){
if(lst.get(count) < 80){
sendOnChannel1();
break;
}
count++;
}
}
},
5000
);
From your example. You could pass the current time into the intent.
So from your MainActivity.java
public void sendOnChannel1(View v) {
String title = editTextTitle.getText().toString();
String message = editTextMessage.getText().toString();
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", message);
broadcastIntent.putExtra("time", Calendar.getInstance().getTimeInMillis()); //**Add here
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setColor(Color.BLUE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.addAction(R.mipmap.ic_launcher, "Toast", actionIntent)
.build();
notificationManager.notify(1, notification);
}
Then when you receive it within the NotificationReceiver.java Compare the date time etc.
public class NotificationReceiver extends BroadcastReceiver {
Integer TEN_MINUETS = 1000 * 60 * 10;
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("toastMessage");
long time = intent.getLongExtra("time", -1);
if(time == -1){
Toast.makeText(context, "Example, no time found", Toast.LENGTH_SHORT).show();
}
if(time + TEN_MINUETS < Calendar.getInstance().getTimeInMillis()){
//10 minutes passed do something else
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
return;
}
//10 miuntes not passed do something more?
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
Just make sure to check the intent has data etc.

Android Firebase push message in Android Studio

I have tried this code, but something happened unexpectedly. I can see a push message on my phone, but I can’t see the log in Android Studio. I think the method onMessageReceived isn’t working. Why did this happen?
My code follows.
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private boolean isVibrator = true;
#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());
//vibrator();
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: "+remoteMessage.getNotification().getBody());
vibrator();
}
}
private void vibrator(){
if(isVibrator){
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {200,1000,150,1500,100,2000,50,3000};
vibe.vibrate(pattern, -1);
}
}
private void sendNotification(String messageBody) {
vibrator();
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);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)//.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakelock.acquire(5000);*/
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
Log.d(TAG, "send Server");
}
}

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

Android Notification Preferences

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"?

Categories