Android:如何获取int值表单服务并在文本View中设置活动

时间:2017-06-29 05:43:17

标签: android android-service

我的应用程序在他的服务中有24小时的countDown计时器。即使用户离开应用,也可以在TextView显示时间。

在服务上,我把一个int数= 5184000.这是24小时转换为毫秒;

问题:

  1. TextView请勿在{{1​​}}显示时间。
  2. 我希望当计时器等于00:00:00,计时器重置且新时间等于23:59:59。
  3. MainActiviy:

    Activity

    服务

    public class MainActivity extends Activity {
    
    TextView tv;
    BroadcastReceiver broad;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        tv = (TextView) findViewById(R.id.textView1);
    
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    
        registerReceiver(broad, new IntentFilter(MyService.BROADCAST_ACTION));
    
    
        broad = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    
                Intent intent1 = getIntent();
                Bundle bundle = intent1.getExtras();
                if (bundle != null) {
                    int data = bundle.getInt("DDDD");
                    tv.setText(data);
                } else {
                    tv.setText("00:00:00");
                }
            }
    
         };
    }
    

    XML:

    public class MyService extends Service {
    
    CountDownTimer cdt = null;
    Intent intent1;
    int h = 5184000;
    
    public static final String BROADCAST_ACTION = "com.example.service";
    
    
    @Override
    public void onCreate() {
        super.onCreate();
    
    }
    
    @Override
    public void onDestroy() {
    
        cdt.cancel();
        Log.i("DDD", "Timer cancelled");
        super.onDestroy();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
    
    
        Log.i("TIME", "Starting timer...");
    
        cdt = new CountDownTimer(h, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
    
                Log.i("TIME", "secondes: " + millisUntilFinished);
    
                intent1 = new Intent(BROADCAST_ACTION);
                intent1.putExtra("T", h);
                sendBroadcast(intent1);
    
            }
    
            @Override
            public void onFinish() {
                Log.i("TIME", "Timer finished");
            }
        };
    
        cdt.start();
    
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
     }
    }
    

1 个答案:

答案 0 :(得分:0)

您可以使用Alarm Manager。

查看以下AlarmManager的链接。

AlarmManager

Scheduling Repeating Alarms