android - 后台计时器

标签 android timer android-service

我正在为一项大学作业开发 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;
    }


}

最佳答案

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

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

关于android - 后台计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19741477/

相关文章:

android - 如何让水平 Linear Layout Child 包裹其内容?

java - AlarmManager 在重新启动时重置

android - 后台服务和前台服务有什么区别?

android - 在 ListView 中使用 BaseAdapter 时如何单独单击每个项目?

android - 如何不在 CalendarView 中设置默认日期?

android - 界面正在褪色,但未显示警报对话框

c# - 如何在每天的特定时间运行 Windows 服务

c# - 在 C# 中锁定线程

ios - 如何在 plist 中存储时间和日期并将其与现在时间 iOS 7 进行比较

java - 服务停止时如何删除通知?