如何设置服务/ StartForeground正常工作CountDownTimer [英] How to set Service/StartForeground to work CountDownTimer properly

查看:269
本文介绍了如何设置服务/ StartForeground正常工作CountDownTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道在哪里/我怎样才能运行此服务在后台工作。
我开发的应用程序,使用CountDownTimer。
我发现我应该创造一个Service.class和CountDownTimer在MainActivity.class运行Service.class。


  1. TextView的,为什么不显示我的屏幕上?我把这个OnCreate中和onStartCommand。接下来,我尝试在MainActivity但没有成功运行此。


  2. 我还是尽量实现我的code在后台正常工作,这CountDownTimer。在官方Android网站上我看到他们用一个Log.i命令来运行这个前景的方法。我怎么能在我的code使用?我应该Service.class添加此?


下面是我的code:

MainActivity:

 按钮btnStart,btnStop;
TextView的textViewTime;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
}公共无效startService(查看视图)
{
    意向意图=新意图(这一点,MyService.class);
    startService(意向);
}公共无效stopService(查看视图)
{
    意向意图=新意图(这一点,MyService.class);
    stopService(意向);
}

为MyService:

 按钮btnStart,btnStop;
TextView的textViewTime;
公共字符串HMS;@覆盖
公共无效的onCreate(){    btnStart =(按钮)btnStart.findViewById(R.id.btnStart);
    btnStop =(按钮)btnStop.findViewById(R.id.btnStop);
    textViewTime =(TextView中)textViewTime.findViewById(R.id.textViewTime);    textViewTime.setText(00:01:30);    最后CounterClass定时器=新CounterClass(90000,1000);
    btnStart.setOnClickListener(新View.OnClickListener(){
              @覆盖
             公共无效的onClick(视图v){
                // startService(五);
                timer.start();
                                         }
                                                            });    super.onCreate();
}
@覆盖
公众诠释onStartCommand(意向意图,诠释标志诠释startId){//创建启动服务    textViewTime.setText(00:01:30);    Toast.makeText(这一点,服务启动...,Toast.LENGTH_LONG).show();
   // timer.start();
    //返回START_STICKY; //返回整型值
    返回super.onStartCommand(意向,旗帜,startId);
}@覆盖
公共无效的onDestroy(){//停止服务    Toast.makeText(这一点,服务被摧毁...,Toast.LENGTH_LONG).show();    super.onDestroy();
}@Nullable
@覆盖
公众的IBinder onBind(意向意图){//这不是必要的,但我们必须重写此方法
    返回null;
}
公共类CounterClass扩展CountDownTimer {    公共CounterClass(长millisInFuture,长countDownInterval){
        超(mil​​lisInFuture,countDownInterval);
    }    @覆盖
    公共无效onTick(长millisUntilFinished){
        长米利斯= millisUntilFinished;
         HMS =的String.format(%02D:%02D:%02D,TimeUnit.MILLISECONDS.toHours(millis)来,
                TimeUnit.MILLISECONDS.toMinutes(millis)来 - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)来)
                TimeUnit.MILLISECONDS.toSec​​onds(millis)来 - TimeUnit.MINUTES.toSec​​onds(TimeUnit.MILLISECONDS.toMinutes(米利斯)));
        的System.out.println(HMS);
        textViewTime.setText(HMS);    }    @覆盖
    公共无效onFinish(){
        textViewTime.setText(完成。);
    }
}


解决方案

下面是您的解决方案很简单,但:)

活动XML

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直
    工具:上下文=in.ashish29agre.stackoverflow.sample.servicetimer.ServiceTimerActivity>    <的TextView
        机器人:ID =@ + ID / status_tv
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:填充=16DP
        机器人:文字=计时器就从这里开始/>    <按钮
        机器人:ID =@ + ID / start_btn
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        安卓的onClick =startService
        机器人:文字=开始/>    <按钮
        机器人:ID =@ + ID / stop_btn
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        安卓的onClick =stopService
        机器人:文字=停止/>
< / LinearLayout中>

Java的code

 进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.os.Bundle;
进口android.support.v4.content.LocalBroadcastManager;
进口android.support.v7.app.AppCompatActivity;
进口android.view.View;
进口android.widget.TextView;进口in.ashish29agre.stackoverflow.R;公共类ServiceTimerActivity扩展AppCompatActivity {    TextView的textViewTime;
    私人TimerStatusReceiver接收机;
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_service_timer);
        textViewTime =(的TextView)findViewById(R.id.status_tv);
        接收器=新TimerStatusReceiver();
    }
    @覆盖
    保护无效onResume(){
        super.onResume();
        LocalBroadcastManager.getInstance(本).registerReceiver(接收器,新的IntentFilter(CountdownTimerService.TIME_INFO));
    }    @覆盖
    保护无效的onPause(){
        super.onPause();
        LocalBroadcastManager.getInstance(本).unregisterReceiver(接收机);
    }    公共无效startService(查看视图){
        意向意图=新意图(这一点,CountdownTimerService.class);
        startService(意向);
    }    公共无效stopService(查看视图){
        意向意图=新意图(这一点,CountdownTimerService.class);
        stopService(意向);
    }
    私有类TimerStatusReceiver扩展广播接收器{        @覆盖
        公共无效的onReceive(上下文的背景下,意图意图){
            如果(意向= NULL&放大器;!&安培; intent.getAction()等于(CountdownTimerService.TIME_INFO)){
                如果(intent.hasExtra(VALUE)){
                    textViewTime.setText(intent.getStringExtra(VALUE));
                }
            }
        }
    }
}

服务code

 进口android.app.Notification;
进口android.app.PendingIntent;
进口android.app.Service;
进口android.content.Intent;
进口android.os.CountDownTimer;
进口android.os.IBinder;
进口android.support.annotation.Nullable;
进口android.support.v4.content.LocalBroadcastManager;
进口android.support.v7.app.NotificationCompat;进口java.util.concurrent.TimeUnit中;进口in.ashish29agre.stackoverflow.R;公共类CountdownTimerService延伸服务{
    公共静态最后弦乐TIME_INFO =time_info;    私人CounterClass定时器;    @覆盖
    公共无效的onCreate(){
        super.onCreate();    }    @Nullable
    @覆盖
    公众的IBinder onBind(意向意图){
        返回null;
    }    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志诠释startId){
        定时器=新CounterClass(90000,1000);
        timer.start();
        意图notificationIntent =新意图(这一点,ServiceTimerActivity.class);
        的PendingIntent的PendingIntent = PendingIntent.getActivity(这一点,0,
                notificationIntent,Intent.FLAG_ACTIVITY_NEW_TASK);        通知通知=新NotificationCompat.Builder(本)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentText(计数器减服务)
                .setContentIntent(的PendingIntent).build();        startForeground(101,通知);        返回START_NOT_STICKY;
    }    @覆盖
    公共无效的onDestroy(){
        timer.cancel();
        super.onDestroy();
        意图timerInfoIntent =新意图(TIME_INFO);
        timerInfoIntent.putExtra(VALUE,停止);
        LocalBroadcastManager.getInstance(CountdownTimerService.this).sendBroadcast(timerInfoIntent);
    }    公共类CounterClass扩展CountDownTimer {        公共CounterClass(长millisInFuture,长countDownInterval){
            超(mil​​lisInFuture,countDownInterval);
        }        @覆盖
        公共无效onTick(长millisUntilFinished){
            长米利斯= millisUntilFinished;
            字符串HMS =的String.format(%02D:%02D:%02D,TimeUnit.MILLISECONDS.toHours(millis)来,
                    TimeUnit.MILLISECONDS.toMinutes(millis)来 - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)来)
                    TimeUnit.MILLISECONDS.toSec​​onds(millis)来 - TimeUnit.MINUTES.toSec​​onds(TimeUnit.MILLISECONDS.toMinutes(米利斯)));
            的System.out.println(HMS);
            意图timerInfoIntent =新意图(TIME_INFO);
            timerInfoIntent.putExtra(VALUE,HMS);
            LocalBroadcastManager.getInstance(CountdownTimerService.this).sendBroadcast(timerInfoIntent);
        }        @覆盖
        公共无效onFinish(){
            意图timerInfoIntent =新意图(TIME_INFO);
            timerInfoIntent.putExtra(VALUE,已完成);
            LocalBroadcastManager.getInstance(CountdownTimerService.this).sendBroadcast(timerInfoIntent);
        }
    }
}

忘记提及需在清单中添加服务

 <应用
        机器人:allowBackup =真
        机器人:图标=@的mipmap / ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:supportsRtl =真
        机器人:主题=@风格/ AppTheme>
        <服务机器人:名字=。sample.servicetimer.CountdownTimerService/>
    < /用途>

I am not sure where/how I can run this service to work in background. I develop application which use a CountDownTimer. I found that I should create a CountDownTimer in Service.class and run a Service.class in MainActivity.class.

  1. Why TextView doesn't show on my screen? I put this in OnCreate and onStartCommand. Next I try run this in MainActivity but without success.

  2. I still try to implement my code to work this CountDownTimer properly in a background. On official Android website I see that they use a "Log.i" command to run this Foreground method. How can I use this in my code? Should I add this in Service.class?

Below is my code:

MainActivity:

Button btnStart, btnStop;
TextView textViewTime;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void startService(View view)
{
    Intent intent = new Intent(this,MyService.class);
    startService(intent);
}

public void stopService(View view)
{
    Intent intent = new Intent(this,MyService.class);
    stopService(intent);
}

MyService:

Button btnStart, btnStop;
TextView textViewTime;
public String hms;

@Override
public void onCreate() { 

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

    textViewTime.setText("00:01:30");

    final CounterClass timer = new CounterClass(90000, 1000);


    btnStart.setOnClickListener(new View.OnClickListener() {
              @Override
             public void onClick(View v) {
                //startService(v);
                timer.start();
                                         }
                                                            });

    super.onCreate();
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {  // create start a service

    textViewTime.setText("00:01:30");

    Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
   // timer.start();




    //return START_STICKY; // return integer value
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {  // stop a service

    Toast.makeText(this, "Service Destroyed...", Toast.LENGTH_LONG).show();

    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {  // it's not needed but we must override this method
    return null;
}


public class CounterClass extends CountDownTimer {

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

    @Override
    public void onTick(long millisUntilFinished) {
        long millis = millisUntilFinished;
         hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
        System.out.println(hms);
        textViewTime.setText(hms);

    }

    @Override
    public void onFinish() {
        textViewTime.setText("Completed.");
    }
}

解决方案

Here is your solution was easy though :)

activity xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="in.ashish29agre.stackoverflow.sample.servicetimer.ServiceTimerActivity">

    <TextView
        android:id="@+id/status_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:text="TImer will start here" />

    <Button
        android:id="@+id/start_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="startService"
        android:text="Start" />

    <Button
        android:id="@+id/stop_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="stopService"
        android:text="Stop" />
</LinearLayout>

Java code

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import in.ashish29agre.stackoverflow.R;

public class ServiceTimerActivity extends AppCompatActivity {

    TextView textViewTime;
    private TimerStatusReceiver receiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_timer);
        textViewTime = (TextView) findViewById(R.id.status_tv);
        receiver = new TimerStatusReceiver();
    }


    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(CountdownTimerService.TIME_INFO));
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    public void startService(View view) {
        Intent intent = new Intent(this, CountdownTimerService.class);
        startService(intent);
    }

    public void stopService(View view) {
        Intent intent = new Intent(this, CountdownTimerService.class);
        stopService(intent);
    }


    private class TimerStatusReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction().equals(CountdownTimerService.TIME_INFO)) {
                if (intent.hasExtra("VALUE")) {
                    textViewTime.setText(intent.getStringExtra("VALUE"));
                }
            }
        }
    }
}

service code

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.NotificationCompat;

import java.util.concurrent.TimeUnit;

import in.ashish29agre.stackoverflow.R;

public class CountdownTimerService extends Service {
    public static final String TIME_INFO = "time_info";

    private CounterClass timer;

    @Override
    public void onCreate() {
        super.onCreate();

    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        timer = new CounterClass(90000, 1000);
        timer.start();
        Intent notificationIntent = new Intent(this, ServiceTimerActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentText("Counter down service")
                .setContentIntent(pendingIntent).build();

        startForeground(101, notification);

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();
        Intent timerInfoIntent = new Intent(TIME_INFO);
        timerInfoIntent.putExtra("VALUE", "Stopped");
        LocalBroadcastManager.getInstance(CountdownTimerService.this).sendBroadcast(timerInfoIntent);
    }

    public class CounterClass extends CountDownTimer {

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

        @Override
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            System.out.println(hms);
            Intent timerInfoIntent = new Intent(TIME_INFO);
            timerInfoIntent.putExtra("VALUE", hms);
            LocalBroadcastManager.getInstance(CountdownTimerService.this).sendBroadcast(timerInfoIntent);
        }

        @Override
        public void onFinish() {
            Intent timerInfoIntent = new Intent(TIME_INFO);
            timerInfoIntent.putExtra("VALUE", "Completed");
            LocalBroadcastManager.getInstance(CountdownTimerService.this).sendBroadcast(timerInfoIntent);
        }
    }
}

Forget to mention need to add service in manifest

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <service android:name=".sample.servicetimer.CountdownTimerService" />
    </application>

这篇关于如何设置服务/ StartForeground正常工作CountDownTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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