Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在后台运行计时器?_Android_Android Studio - Fatal编程技术网

Android 如何在后台运行计时器?

Android 如何在后台运行计时器?,android,android-studio,Android,Android Studio,我有一个计时器的代码,但是如果我更改了片段,计时器被重置为00:00,我希望在我单击停止或暂停后计时器仍然计数,或者这意味着这个计时器仍然在后台计数 怎么做? 这是我的密码 public class TimerFragment extends BaseFragment { private Button startButton; private Button pauseButton; private TextView timerValue; private long

我有一个计时器的代码,但是如果我更改了片段,计时器被重置为00:00,我希望在我单击停止或暂停后计时器仍然计数,或者这意味着这个计时器仍然在后台计数 怎么做? 这是我的密码

public class TimerFragment extends BaseFragment {
    private Button startButton;
    private Button pauseButton;
    private TextView timerValue;
    private long startTime = 0L;
    private Handler customHandler = new Handler();
    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_timer, container, false);

        initialize();
        //when start

        startTime = SystemClock.uptimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);

        //pause
        pauseButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                timeSwapBuff += timeInMilliseconds;
                customHandler.removeCallbacks(updateTimerThread);

            }
        });

        return rootView;
    }

    private Runnable updateTimerThread = new Runnable() {

        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;

            timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs));
            customHandler.postDelayed(this, 0);
        }

    };

无论如何谢谢您

问题:-当您切换片段并返回到计时器片段时,将调用onCreate生命周期回调,并在中重置计时器

postDelayed(updateTimerThread,0)

解决方案:-将计时器逻辑移动到活动类,但活动将在方向更改中重新创建,因此将计时器逻辑移动到应用程序类:-

在项目包中删除该类

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Application;
import android.os.Handler;
import android.widget.Toast;

public class App extends Application {

    public static App appInstance;
    private SimpleDateFormat dateFormat;

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

        appInstance = this;

        dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }

    public void afficher() {
        Toast.makeText(getBaseContext(), dateFormat.format(new Date()), 300).show();
        handler.postDelayed(runnable,1000);
    }

    public void startTimer() {
        runnable.run();
    }

    public void stopTimer() {
        handler.removeCallbacks(runnable);
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            afficher();
        }
    };

}
将你的应用程序名设置为应用程序类,如下所示(应用程序的android名称属性):-

添加AppController


java lang调用App.appInstance.startTimer()时出现空指针异常;抱歉,我是android新手:(你必须在清单中声明应用程序名称,请参见编辑以供参考。将逻辑移动到应用程序范围是一个很好的解决方案,如果他需要在片段中显示时间,那么问题在于你需要访问片段的ui。我认为最好将startTimer()更改为startTimer()(Hanlder handler)并在fragment@visionixvisionix好的,伙计,我会试试的,谢谢你的计时器逻辑。
   <application
        android:name="com.masterdetail_webview.App"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.masterdetail_webview.TimertestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            App.appInstance.startTimer();

        }
    });

    findViewById(R.id.button2).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            App.appInstance.stopTimer();

        }
    });