如何将String数据从我的服务传递到我的片段?

时间:2018-01-10 03:22:03

标签: android android-fragments service timer

我有一个在后台运行计时器的服务,我希望将数据传递给我的片段,以便在那里显示计时器。如果我关闭我的应用程序并再次打开它我想看到我的edittext显示计时器。任何答案都将不胜感激。

这是我的服务

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

        //background timer
        CountDownTimer countDownTimer = new CountDownTimer(dur,    1000) {
            @Override
            public void onTick(long dur) {
                long millis= dur;
                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))
                );
                startnotif(hms);
            }

            @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);
                endnotif();
                onDestroy();
            }
        };
        countDownTimer.start();
        return START_STICKY;
    }

    public void onDestroy() {
        stopSelf();
    }

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

    //notification
    public void startnotif(String hms)
    {
        String noT = hms;
        notification.setSmallIcon(R.mipmap.ic_launcher);
        notification.setTicker("apps are blocked!");
        notification.setWhen(System.currentTimeMillis());
        notification.setContentTitle("Be productive!");
        notification.setContentText(hms);
        ClickNotif();
    }

    public void endnotif(){
        notification.setContentText("00:00");
        notification.setTicker("apps are now unblocked!");
        notification.setWhen(System.currentTimeMillis());
        notification.setContentTitle("You survived!");
        notification.setContentText("Apps are now unblocked!");
        ClickNotif();
    }

    public void ClickNotif(){
        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());
    }

}

这是片段。我计划在这个片段上删除倒数计时器,因为我要在服务上使用计时器。

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;

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

}

提前致谢。

2 个答案:

答案 0 :(得分:1)

尝试EventBus库,你可以正常发送消息或者粘贴事件,也许它可以解决你的问题:)

答案 1 :(得分:0)

您可以通过多种方式更新editText。

  1. 当您打开应用程序时,您可以绑定到已经运行的服务。绑定后,您可以调用服务中的方法来获取结果。对于简单绑定服务,请参阅bind service
  2. 您可以保持共享偏好并在每次倒计时继续更新。每当应用程序打开时,请阅读共享首选项并更新您的edittext。