实现一个在后台使用服务倒计时 [英] Implementing a Count down timer using Service in the background

查看:138
本文介绍了实现一个在后台使用服务倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序是什么: 1.当用户打开该应用时,他将能够看到已经运行的倒数计时器。因此,在这种情况下,我想说明的倒计时数字在会随时更新每一秒一个TextView。 2.用户将能够停止它。 3.用户可以离开应用程序,但倒数还是应该继续下去,并显示更新时间,当他回来的应用程序用户界面。

What I want to do in my app: 1. When the user opens the app, he will be able to see an already running countdown timer. So in that case I want to show the countdown numbers in a textview that will always update each second. 2. The user will be able to stop it. 3. The user can leave the application, but the countdown should still go on and show updated time when he comes back to the application UI.

因此​​,基于以上几点,我明白我需要实现服务,只要在后台工作。我已阅读​​这的链接,但我的问题是与落实。我很为丢失如何实现这种方式。话虽这么说,我也不能想办法,以显示在用户界面的时候,一旦用户回来的应用程序。我也看到​​此链接为好,但我不知道如果只实施CountDownTimer使得正在运行的服务。 所以,我应该如何进行,实现它?具体教程/ codeS的任何链接都是AP preciated。谢谢你。

So based on the above points, I understand I need to implement Service that does work in the background. I have read this link but my problem is with the implementation. I am quite at a lost about how to implement that way. That being said, I also cannot think of a way as to showing the time in the UI once the user comes back to the application. I have also seen this link as well, but I am not sure if only implementing CountDownTimer makes it a running Service. So how should I proceed and implement it? Any links to specific tutorials/codes are appreciated. Thanks.

更新:我到目前为止已经能够做到以下几点: MainActivity.java

UPDATES: I have so far been able to do the following: MainActivity.java

public class MainActivity extends Activity {

Button btnStart,btnStop;
Intent serviceIntent;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnStart = (Button) findViewById(R.id.btnStart);
    btnStop = (Button) findViewById(R.id.btnStop);
    tv = (TextView) findViewById(R.id.timeView);

    //final MyCounter timer = new MyCounter(100000,1000);
    //tv.setText("100"); 
    //timer.start();
    serviceIntent = new Intent(MainActivity.this,MyService.class);

    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            startService(serviceIntent);
        }
    });

    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            stopService(serviceIntent);
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

MyService.java:

MyService.java:

public class MyService extends Service {

MyCounter timer;
@Override
public void onCreate() {
    // TODO Auto-generated method stub
    timer = new MyCounter(100000,1000);
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    timer.start();
    return super.onStartCommand(intent, flags, startId);
}
private class MyCounter extends CountDownTimer{

    public MyCounter(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
        Toast.makeText(getApplicationContext(), "death", Toast.LENGTH_LONG).show();
        stopSelf();
    }

    @Override
    public void onTick(long millisUntilFinished) {

        Toast.makeText(getApplicationContext(), (millisUntilFinished/1000)+"", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    timer.cancel();
    //stopSelf();
    super.onDestroy();

}

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

    }

的问题是:  1。我不知道如何从这个吐司显示在MainActivity UI倒计时分开。  2.它不会停止计数,当我preSS停止键。

The problem is: 1. I don't know how to show the countdown on the MainActivity UI apart from this Toast. 2. It doesn't stop counting when I press Stop Button.

推荐答案

使用bindService(意向服务,ServiceConnection康涅狄格州,INT标志)绑定您的倒计时的服务,然后在你的服务,回报您的粘合剂包含您的计数,并在你的活动,一个实例ServiceConnection对象可以处理的粘合剂。 AIDL可以做到这一点为好,建议看看如何先绑定的服务,希望能帮助你。

use bindService(Intent service, ServiceConnection conn, int flag) to bind your countdown service, then in your service, return your binder that contain your count, and in your activity, a instantiated ServiceConnection object can handle the binder. AIDL can do this as well, suggest have a look at how to bind service firstly, wish can help you.

演示

public class BindService extends Service{
private int count;
private boolean quit;
private MyBinder binder = new MyBinder();
// My Binder
public class MyBinder extends Binder
{
    public int getCount()
    {
        // get the counting status:count
        return count;
    }
}

@Override
public IBinder onBind(Intent intent)
{
    System.out.println("Service is Binded");
    // return the binder instance
    return binder;
}

@Override
public void onCreate()
{
    super.onCreate();
    System.out.println("Service is Created");
    // counting work
    new Thread()
    {
        @Override
        public void run()
        {
            while (!quit)
            {
                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e)
                {
                }
                count++;
            }
        }
    }.start();      
}
// invoke when the service unbind
@Override
public boolean onUnbind(Intent intent)
{
    System.out.println("Service is Unbinded");
    return true;
}

@Override
public void onDestroy()
{
    super.onDestroy();
    this.quit = true;
    System.out.println("Service is Destroyed");
}

@Override
public void onRebind(Intent intent) 
{
    super.onRebind(intent);
    this.quit = true;
    System.out.println("Service is ReBinded");
}   

}

和随后的活性

public class MainActivity extends Activity{
Button bind , unbind , getServiceStatus;
BindService.MyBinder binder;
// define a ServiceConnection object
private ServiceConnection conn = new ServiceConnection()
{
    // then the Activity connected with the Service, this will be called
    @Override
    public void onServiceConnected(ComponentName name
        , IBinder service)
    {
        System.out.println("--Service Connected--");
        // achieve MyBinder instance
        binder = (BindService.MyBinder) service;
    }
    // then the connection break off
    @Override
    public void onServiceDisconnected(ComponentName name)
    {
        System.out.println("--Service Disconnected--");         
    }
};
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    bind = (Button) findViewById(R.id.bind);
    unbind = (Button) findViewById(R.id.unbind);
    getServiceStatus = (Button) findViewById(R.id.getServiceStatus);

    final Intent intent = new Intent();

    intent.setAction("org.crazyit.service.BIND_SERVICE");       
    bind.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View source)
        {
            //bind Serivce
            bindService(intent , conn , Service.BIND_AUTO_CREATE);  
        }
    });
    unbind.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View source)
        {
            //unbind Serivce
            unbindService(conn);
        }
    }); 
    getServiceStatus.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View source)
        {
            // Toast to show the conut value
            Toast.makeText(MainActivity.this
                , "Serivce's count value is:" + binder.getCount()
                , 4000)
                .show();
        }
    });
}}

这篇关于实现一个在后台使用服务倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆