当前位置: 首页 > 面试题库 >

如何设置Service / StartForeground使其正常运行CountDownTimer

齐献
2023-03-14
问题内容

我不确定在哪里/如何在后台运行此服务。我开发使用CountDownTimer的应用程序。我发现我应该在Service.class中创建一个CountDownTimer并在MainActivity.class中运行一个Service.class。

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

  2. 我仍然尝试实现我的代码以在后台正确运行此CountDownTimer。在Android官方网站上,我看到他们使用“ Log.i”命令来运行此Foreground方法。如何在我的代码中使用它?我应该在Service.class中添加它吗?

下面是我的代码:

主要活动:

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);
}

我的服务:

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.");
    }
}

问题答案:

这是您的解决方案,虽然很简单:)

活动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代码

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"));
                }
            }
        }
    }
}

服务代码

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);
        }
    }
}

忘了需要在清单中添加服务

 <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>


 类似资料:
  • 问题内容: 我正在使用WebDriver,并且已经下载了InternetExplorerDriver,并且想知道下载后如何处理? 这就是说要把驾驶员放在我的路上。不确定他们到底在说什么。 有人使用过吗?如果可以,您是否可以提供有关如何设置它的详细步骤,使其能够正常工作? 我收到以下错误: 驱动程序可执行文件的路径必须由webdriver.ie.driver系统属性设置 我下载了IE和Chrome驱

  • 我想连接一个android设备直接从我的环境android studio测试我的应用程序 android Studio-http://developer.android.com/sdk/index.html 我有一个三星galaxy s5设备,我已经把它连接到usb上,我已经安装了这个驱动程序: http://developer.samsung.com/technical-doc/view.do?

  • 我正在尝试设置selenium网络驱动程序,以便与浏览器堆栈一起使用Java进行自动化测试。我为java安装了Selenium,并从浏览器堆栈的站点https://www.browserstack.com/automate/java#configure-capabilities复制和粘贴代码以设置示例自动化测试。 我运行了javac-classpath selenium-server-standa

  • 问题内容: 我试图设置Selenium Webdriver与Java的Browserstack一起使用,以进行自动测试。我安装了Selenium for Java,然后从浏览器堆栈的站点https://www.browserstack.com/automate/java#configure- capabilities 复制并粘贴了代码,以建立示例自动化测试。 我从终端运行(JavaSample.j

  • 问题内容: 我需要禁用IPv6。为此,Java文档指示设置jvm属性。 但是我不了解如何从代码本身做到这一点。 许多论坛都演示了如何从命令提示符下执行此操作,但是我需要在运行时执行此操作。 问题答案: 您可以使用 这等效于通过以下命令在命令行中传递它

  • 有一个 JDK 错误:http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8022628 它将在49.7天内获得java.net.SocketTimeoutException。 在那个链接中,它说“我们已经加速了cpu的正常运行时间”。我想测试一下这个bug,但是我不知道如何“加速cpu的正常运行时间”。 我运行了上面的程序,而不是将时间更改为4