【问题标题】:Timer in Background后台定时器
【发布时间】:2013-11-02 11:35:54
【问题描述】:

我正在为大学工作开发一个 Android 应用程序。在这项工作中,我想创建一个带有计时器的后台服务,当我关闭应用程序时,计时器仍在运行。当我打开应用程序时,我可以看到自启动服务以来的时间。 好吧,我的问题是当我关闭应用程序时,后台计时器停止并且不再增加。

你能帮帮我吗? 非常感谢

我的启动器类

    import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button startButton;
    private Button pauseButton;

    private TextView timerValue;

    Intent intent;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        timerValue = (TextView) findViewById(R.id.timerValue);

        startButton = (Button) findViewById(R.id.startButton);
        startButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                intent = new Intent(MainActivity.this, CounterService.class);
                startService(intent);
                registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));
            }
        });

        pauseButton = (Button) findViewById(R.id.pauseButton);

        pauseButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                unregisterReceiver(broadcastReceiver);
                stopService(intent);
            }
        });

    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            updateUI(intent);       
        }
    };    

    private void updateUI(Intent intent) {
        int time = intent.getIntExtra("time", 0);

        Log.d("Hello", "Time " + time);

        int mins = time / 60;
        int secs = time % 60;
        timerValue.setText("" + mins + ":"
                + String.format("%02d", secs));
    }


}

这里是服务类

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;

public class CounterService  extends Service {

    private Intent intent;
    public static final String BROADCAST_ACTION = "com.javacodegeeks.android.androidtimerexample.MainActivity";

    private Handler handler = new Handler();
    private long initial_time;
    long timeInMilliseconds = 0L;

    @Override
    public void onCreate() {
        super.onCreate();
        initial_time = SystemClock.uptimeMillis();
        intent = new Intent(BROADCAST_ACTION);  
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            DisplayLoggingInfo();           
            handler.postDelayed(this, 1000); // 1 seconds
        }
    };    

    private void DisplayLoggingInfo() {

        timeInMilliseconds = SystemClock.uptimeMillis() - initial_time; 

        int timer = (int) timeInMilliseconds / 1000;
        intent.putExtra("time", timer);
        sendBroadcast(intent);

    }

    @Override
    public void onDestroy() {   
        super.onDestroy();
        handler.removeCallbacks(sendUpdatesToUI);   

    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


}

【问题讨论】:

  • 是否需要为此使用Service?您始终可以在任何时候以毫秒为单位存储时间(在本地 SQL 数据库中,甚至在 SharedPreferences 中),并在 onResume() 中执行一些快速增量算术以确定自您尝试执行的操作以来已经过了多长时间采取措施。
  • 我正在尝试使用一项服务,以获得显示时间的通知。但你的想法一点也不差
  • 好吧,如果您有兴趣了解更多关于Service 课程的信息(大学课程通常就是这种情况),请查看@Mahfa 提供的答案。否则,我相信我的建议会简单得多。
  • 你有没有得到任何答复。我有同样的问题

标签: android timer android-service


【解决方案1】:

您需要在活动中的onStop() 方法中启动您的服务,如下所示:

@Override
    protected void onStop() {
        super.onStop();
       //write your code here to start your service
    }

【讨论】:

    【解决方案2】:

    如果您想在后台运行计时器,请浏览链接希望对您有所帮助Timer in background

    activity_main.xml

    <RelativeLayout android:layout_width="match_parent"
     android:layout_height="match_parent"
     xmlns:android="http://schemas.android.com/apk/res/android">
    
    
     <EditText
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/et_hours"
     android:hint="Hours"
     android:inputType="time"
     android:layout_marginRight="5dp"
     />
    
    
    
    
     <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/btn_timer"
     android:layout_above="@+id/btn_cancel"
     android:text="Start Timer"/>
    
     <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentBottom="true"
     android:id="@+id/btn_cancel"
     android:text="cancel timer"/>
    
    
    
    
     <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/tv_timer"
     android:layout_centerInParent="true"
     android:textSize="25dp"
     android:textColor="#000000"
     android:text="00:00:00"/>
    
    
     </RelativeLayout>
    

    MainActivity.java

    package playstore.com.a02backgroundtimer;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private Button btn_start, btn_cancel;
        private TextView tv_timer;
        String date_time;
        Calendar calendar;
        SimpleDateFormat simpleDateFormat;
        EditText et_hours;
    
        SharedPreferences mpref;
        SharedPreferences.Editor mEditor;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            init();
            listener();
    
    
        }
    
        private void init() {
            btn_start = (Button) findViewById(R.id.btn_timer);
            tv_timer = (TextView) findViewById(R.id.tv_timer);
            et_hours = (EditText) findViewById(R.id.et_hours);
            btn_cancel = (Button) findViewById(R.id.btn_cancel);
    
    
    
            mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            mEditor = mpref.edit();
    
            try {
                String str_value = mpref.getString("data", "");
                if (str_value.matches("")) {
                    et_hours.setEnabled(true);
                    btn_start.setEnabled(true);
                    tv_timer.setText("");
    
                } else {
    
                    if (mpref.getBoolean("finish", false)) {
                        et_hours.setEnabled(true);
                        btn_start.setEnabled(true);
                        tv_timer.setText("");
                    } else {
    
                        et_hours.setEnabled(false);
                        btn_start.setEnabled(false);
                        tv_timer.setText(str_value);
                    }
                }
            } catch (Exception e) {
    
            }
    
    
    
        }
    
        private void listener() {
            btn_start.setOnClickListener(this);
            btn_cancel.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
    
            switch (v.getId()) {
                case R.id.btn_timer:
    
    
                    if (et_hours.getText().toString().length() > 0) {
    
                        int int_hours = Integer.valueOf(et_hours.getText().toString());
    
                        if (int_hours<=24) {
    
    
                            et_hours.setEnabled(false);
                            btn_start.setEnabled(false);
    
    
                            calendar = Calendar.getInstance();
                            simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                            date_time = simpleDateFormat.format(calendar.getTime());
    
                            mEditor.putString("data", date_time).commit();
                            mEditor.putString("hours", et_hours.getText().toString()).commit();
    
    
                            Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
                            startService(intent_service);
                        }else {
                            Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
                        }
    /*
                        mTimer = new Timer();
                        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
                    } else {
                        Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
                    }
                    break;
    
    
                case R.id.btn_cancel:
    
    
                    Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
                    stopService(intent);
    
                    mEditor.clear().commit();
    
                    et_hours.setEnabled(true);
                    btn_start.setEnabled(true);
                    tv_timer.setText("");
    
    
                    break;
    
            }
    
        }
    
        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String str_time = intent.getStringExtra("time");
                tv_timer.setText(str_time);
    
            }
        };
    
        @Override
        protected void onResume() {
            super.onResume();
            registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
    
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            unregisterReceiver(broadcastReceiver);
        }
    }
    

    Timer_Service.java

    package playstore.com.a02backgroundtimer;
    
    import android.app.Service;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Handler;
    import android.os.IBinder;
    import android.preference.PreferenceManager;
    import android.support.annotation.Nullable;
    import android.util.Log;
    
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.concurrent.TimeUnit;
    
    public class Timer_Service extends Service {
    
        public static String str_receiver = "com.countdowntimerservice.receiver";
    
        private Handler mHandler = new Handler();
        Calendar calendar;
        SimpleDateFormat simpleDateFormat;
        String strDate;
        Date date_current, date_diff;
        SharedPreferences mpref;
        SharedPreferences.Editor mEditor;
    
        private Timer mTimer = null;
        public static final long NOTIFY_INTERVAL = 1000;
        Intent intent;
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            mEditor = mpref.edit();
            calendar = Calendar.getInstance();
            simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
    
            mTimer = new Timer();
            mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
            intent = new Intent(str_receiver);
        }
    
    
        class TimeDisplayTimerTask extends TimerTask {
    
            @Override
            public void run() {
                mHandler.post(new Runnable() {
    
                    @Override
                    public void run() {
    
                        calendar = Calendar.getInstance();
                        simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                        strDate = simpleDateFormat.format(calendar.getTime());
                        Log.e("strDate", strDate);
                        twoDatesBetweenTime();
    
                    }
    
                });
            }
    
        }
    
        public String twoDatesBetweenTime() {
    
    
            try {
                date_current = simpleDateFormat.parse(strDate);
            } catch (Exception e) {
    
            }
    
            try {
                date_diff = simpleDateFormat.parse(mpref.getString("data",""));
            } catch (Exception e) {
    
            }
    
            try {
    
    
                long diff = date_current.getTime() - date_diff.getTime();
                int int_hours = Integer.valueOf(mpref.getString("hours", ""));
    
                long int_timer = TimeUnit.HOURS.toMillis(int_hours);
                long long_hours = int_timer - diff;
                long diffSeconds2 = long_hours / 1000 % 60;
                long diffMinutes2 = long_hours / (60 * 1000) % 60;
                long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
    
    
                if (long_hours > 0) {
                    String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
    
                    Log.e("TIME", str_testing);
    
                    fn_update(str_testing);
                } else {
                    mEditor.putBoolean("finish", true).commit();
                    mTimer.cancel();
                }
            } catch (Exception e) {
                mTimer.cancel();
                mTimer.purge();
    
    
            }
    
            return "";
    
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.e("Service finish", "Finish");
        }
    
        private void fn_update(String str_time) {
    
            intent.putExtra("time", str_time);
            sendBroadcast(intent);
        }
    }
    

    应用程序启动后,您需要提及您想要计时器的小时数...然后在您重新启动应用程序时终止应用程序后,它将显示计时器的开始时间...现在您可以自定义您的应用程序你的要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多