如何在通知上显示计时器?

时间:2018-01-09 07:04:25

标签: android timer notifications android-notifications

如何在通知上显示我的计时器?我有一个应用程序启动用户指定的计时器,我想在通知上显示计时器。我使用服务来运行我的计时器,即使我的应用程序已关闭,我使用SharedPreference传递用户设置为服务的持续时间。

这是我的代码: 第2页(片段)

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 个答案:

答案 0 :(得分:1)

您可以使用在创建通知之前指定的唯一通知ID来更新通知。

循环你的计时器(例如,从你的例子中的共享偏好中减去一个初始值的计数器)并循环每一次减量并更新通知,如:

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

示例已从官方文档修改:Update Notifications in Android

答案 1 :(得分:0)

像你一样从共享偏好中获取持续时间。

int dur = sharedPreferences.getInt("duration", 0);

现在您可以通过将“dur”的值传递给setContentText来显示计时器。

notification.setContentText("Apps are now unblocked!"+dur);

答案 2 :(得分:0)

我试图在通知时制作计时器,所以制作了一个库。

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

希望对大家有所帮助..