6

How can I show my timer on a notification? I have an app that starts a timer specified by a user and I want to show the timer on a notification. Im using a service to run my timer even if my app is closed and I used SharedPreference to pass the duration that the user set to the service.

here are my codes: page2 (fragment)

public class page2 extends Fragment {
    private static final String TAG =   "page2";

    private Button btntest;
    private TextView timer,tv;
    private Spinner spinner, spinner2;
    public int hours, mins, duration;
    private Vibrator v;

    private static int myVariable;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page2_fragment,container,false);

        btntest = (Button) view.findViewById(R.id.button2);
        timer = (TextView) view.findViewById(R.id.Timer);
        tv = (TextView) view.findViewById(R.id.textView3);

        //setting up 2 spinners
        spinner = (Spinner) view.findViewById(R.id.spinner1);
        String [] values = {"00","01","02","03","04","05","06"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner.setAdapter(adapter);
        spinner2 = (Spinner) view.findViewById(R.id.spinner2);
        String [] values2 = {"00","01","10","20","30","40","50","60"};
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values2);
        adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner2.setAdapter(adapter2);

        //button start
        btntest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String spin=spinner.getSelectedItem().toString();
                hours = Integer.parseInt(spin);
                hours = hours*3600000;
                String spin2=spinner2.getSelectedItem().toString();
                mins = Integer.parseInt(spin2);
                mins = mins*60000;
                duration = hours+mins;
                setParam(duration);
                startService(duration);
            }
        });
        return view;
    }

    //timer part
    public void setParam(int param){
         CountDownTimer countDownTimer = new CountDownTimer(param,    1000) {

            @Override
            public void onTick(long param) {
                long millis= param;
                String hms= String.format("%02d:%02d:%02d",

                        TimeUnit.MILLISECONDS.toHours(millis),
                        TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
                        //seconds
                        ,TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
                );
                timer.setText(hms);
            }

            @Override
            public void onFinish() {
                timer.setText("00:00");
            }
        };
        countDownTimer.start();
    }

    //saving data and passing intent to service
    public void startService(int duration)
    {
        int d = duration;
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Timer", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("duration", d);
        editor.apply();
        Intent intent = new Intent(getActivity(),MyService.class);
        getActivity().startService(intent);
        Toast.makeText(getActivity(), "Intent passed and preferences saved!"+d,Toast.LENGTH_SHORT).show();
    }

}

MyService.java

public class MyService extends Service {

    private Vibrator v;
    //private static Timer timer = new Timer();
    NotificationCompat.Builder notification;
    private static final int uniqueID = 71399;
    @Override
    public void onCreate() {
        super.onCreate();

        notification = new NotificationCompat.Builder(this);
        notification.setAutoCancel(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        SharedPreferences sharedPreferences = getSharedPreferences("Timer", Context.MODE_PRIVATE);
        int dur = sharedPreferences.getInt("duration", 0);
        CountDownTimer countDownTimer = new CountDownTimer(dur,    1000) {

            @Override
            public void onTick(long param) {
            }

            @Override
            public void onFinish() {
                long n[] = {1,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000};
                v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(n, -1);
                startnotif();
                onDestroy();
            }
        };
        countDownTimer.start();
        return START_STICKY;
    }


    public void onDestroy() {

        stopSelf();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //notification
    public void startnotif()
    {
        notification.setSmallIcon(R.mipmap.ic_launcher);
        notification.setTicker("apps are now unblocked!");
        notification.setWhen(System.currentTimeMillis());
        notification.setContentTitle("You survived!");
        notification.setContentText("Apps are now unblocked!");

        Intent intent1 = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setContentIntent(pendingIntent);

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(uniqueID, notification.build());

    }

}
3
  • were the answers given helpful to you? Feb 5, 2018 at 11:59
  • @ThomasRichter yes Feb 7, 2018 at 4:50
  • Would you mind to rate the answers somehow, just to guide other people, who are running into the same problem, to a solution? ;) Feb 7, 2018 at 6:05

3 Answers 3

2

You can update Notifications by using the unique notification ID you specified right before you created your notification.

Loop over your timer (e.g. decrease a counter from an initial value like from shared preferences in your example) and loop over every decrement and update the notification like that:

mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int numMessages = 0;
    mNotifyBuilder.setContentText(String.valueOf(timerValue))  // <-- your timer value
        .setNumber(++numMessages);
    // Because the ID remains unchanged, the existing notification is
    // updated.
    mNotificationManager.notify(
            notifyID,  // <-- Place your notification id here
            mNotifyBuilder.build());

Example is modified from official documentation: Update Notifications in Android

2

I was trying to make timer on notification, so made a library.

https://github.com/Jun-Hub/NotificationTimer

I hope it helpful to somebody..

0

With Notification you can do this to set the Chronometer to count down

var expireTimeInMiliSeconds = Date().time + 60000
Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
.setChronometerCountDown(true)
.setUsesChronometer(true)
.setShowWhen(true)
.setWhen(expireTimeInMiliSeconds)

and to set the Chronometer to counting up

Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
.setUsesChronometer(true)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.