Пусть таймер продолжит следующую активность - PullRequest
0 голосов
/ 16 октября 2018

Я создал timer на моем первом activity и хотел бы, чтобы timer продолжил timing на втором activity.Как мне это сделать?Должен ли я создать SharedPrefrence или создать новый timer на втором activity.Я просто не знаю, как бы связать timer со вторым activity.

Код ниже

FirstActivity.java

package com.example.warrenedy.mainapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.example.warrenedy.mainapp.IMEI_UTILS.TelephonyInfo;
import com.example.warrenedy.mainapp.Utils.Utils;
import com.example.warrenedy.mainapp.VolleyUtils.AppController;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import pl.droidsonroids.gif.GifImageView;

import static com.example.warrenedy.mainapp.VolleyUtils.AppController.TAG;

public class MeditationTrackerTest extends Activity {

    Button mButtonSavePoints, btnHelpBut;
    ImageView btnSolver;

    TextView text;
    ImageView dr0;
    ImageView dr1;
    ImageView dr2;
    ImageView dr3;
    ImageView dr4;
    ImageView dr5;
    ImageView dr6;
    ImageView dr7;
    ImageView dr8;
    ImageView dr9;

    private Context mContext;
    private MeditationTrackerTest mActivity;

    private SharedPreferences sharedpreferences;

    public static final String MyPREFERENCES = "MyPrefs";
    public static final String Count = "Count";
    public static final String Screen = "Screen";
    public static final String Count2 = "Count2";
    public static final String TestCnt = "testCnt";

    public static final String FINAL_COUNT = "final_cnt";

    int cnt = 0;
    int cnt2 = 0;
    int Points = 0;
    int convertPoints = 0;
    String Points2;
    String points;
    String screen;
    View v;

    TextView TimerValue, solve;

    TimerTask mTimerTask;
    final Handler handler = new Handler();
    Timer t = new Timer();

    private int nCounter = 0;
    int countSolve = 0;
    String StartOrStop;
    String name;

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

        sharedpreferences = getSharedPreferences(Utils2.MyPREFERENCES, Context.MODE_PRIVATE);

        mContext = getApplicationContext();
        mActivity = MeditationTrackerTest.this;

        if ( sharedpreferences.contains(Count)) {
            cnt = sharedpreferences.getInt(Count,0);
        }

        screen = "";
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Screen,screen);
        editor.commit();

        TimerValue = (TextView) findViewById(R.id.tv_current_time);
        TimerValue.setText("00:00:00");

        StartOrStop = "Start";

        dr0=(GifImageView) findViewById(R.id.d0);
        dr1=(GifImageView) findViewById(R.id.d1);
        dr2=(GifImageView) findViewById(R.id.d2);
        dr3=(GifImageView) findViewById(R.id.d3);
        dr4=(GifImageView) findViewById(R.id.d4);
        dr5=(GifImageView) findViewById(R.id.d5);
        dr6=(GifImageView) findViewById(R.id.d6);
        dr7=(GifImageView) findViewById(R.id.d7);
        dr8=(GifImageView) findViewById(R.id.d8);
        dr9=(GifImageView) findViewById(R.id.d9);

        mButtonSavePoints = (Button) findViewById(R.id.btn_save_points);
        btnHelpBut = (Button) findViewById(R.id.btnHelp);
        btnSolver = (ImageView) findViewById(R.id.btnSolver);

        convertToImg(cnt);

        mButtonSavePoints.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculate();
                if (Utils.getConnectivityStatus(mContext)) {
                    updateClientPointsAPI();
                } else {
                    Utils.alertPopup(mContext, "You are not connected to internet.kindly connect with internet and try again.", mActivity);
                }
            }
        });
        btnHelpBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculate();
                Intent i = new Intent(getApplicationContext(), HelpScreen6_7.class);
                startActivity(i);
            }
        });
        btnSolver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnSolver.setBackgroundResource(R.drawable.solver_green);
                TimerValue.setText("00:00:00");
                nCounter = 0;
                name = "solve";
                if( StartOrStop == "Start") {
                    doTimerTask();
                    Intent i = new Intent(getApplicationContext(), EmotionByDay.class);
                    startActivity(i);
                }
                else if ( StartOrStop == "Stop") {
                    stopTask();
                }
            }
        });
    }

    public void doTimerTask(){
        if( name == "solve") {
            btnHelpBut.setClickable(false);
            mButtonSavePoints.setClickable(false);
        }

        mTimerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        nCounter++;
                        TimerValue.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
                        if ( name == "solve" ) {
                            countSolve =  nCounter;
                            //exercise.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(countExercise))));
                        }
                        StartOrStop = "Stop";
                        //Log.d("TIMER", "TimerTask run");
                    }
                });
            }};

        // public void schedule (TimerTask task, long delay, long period)
        t.schedule(mTimerTask, 200, 1000);  //

    }

    public void stopTask(){

        if(mTimerTask!=null){
            TimerValue.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));

            //Log.d("TIMER", "timer canceled");
            mTimerTask.cancel();
            if( name == "solve" ) {
                btnSolver.setBackgroundResource(R.drawable.solver);
                TrackerDb3.insertOrUpdateMeditation(this, countSolve, MeditationTrackerActivity.ACTIVITIES.STUDY);
                TimerValue.setText("00:00:00");
            }
            btnHelpBut.setClickable(true);
            mButtonSavePoints.setClickable(true);
            StartOrStop = "Start";

        }
    }

    private void updateClientPointsAPI() {
        // Tag used to cancel the request
        String tag_string_req = "string_req_update_client_points";

        String url = Utils.URL_UPDATE_CLIENT_POINTS;
        final ProgressDialog pDialog = new ProgressDialog(mContext);

        Toast.makeText(this, "Uploading Client Points to server..", Toast.LENGTH_SHORT).show();
//        pDialog.setMessage("Uploading Client Points to server");
//        pDialog.show();


        StringRequest strReq = new StringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, response.toString());
                pDialog.hide();
                JSONObject jObject = null;
                try {
                    jObject = new JSONObject(response);
                    boolean serverResponse = jObject.getBoolean("Result");
                    if (serverResponse) {
                        Toast.makeText(mContext, "Points Sucessfully uploaded to server", Toast.LENGTH_SHORT).show();
                        Utils.alertPopup(mContext, "Points Sucessfully uploaded to server", mActivity);
                    } else {
                        String msg = jObject.getString("msg");

                        // Utils.alertPopup(mContext, msg, mActivity);
                        Toast.makeText(mContext, "Points Sucessfully uploaded to server", Toast.LENGTH_SHORT).show();
                        Utils.alertPopup(mContext, "Points Sucessfully uploaded to server", mActivity);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                    return;

                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());

                pDialog.hide();

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(mActivity);

                String imeiSIM1 = telephonyInfo.getImsiSIM1();
                String imeiSIM2 = telephonyInfo.getImsiSIM2();

                boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
                boolean isSIM2Ready = telephonyInfo.isSIM2Ready();

                boolean isDualSIM = telephonyInfo.isDualSIM();
                if (isDualSIM) {

                    params.put("deviceSerial1", imeiSIM1);
                    params.put("deviceSerial2", imeiSIM2);
                    params.put("isDualSIM", "1");
                } else {
                    params.put("deviceSerial1", imeiSIM1);
                    params.put("isDualSIM", "0");
                }
                params.put("total_points",Points2);

                return params;
            }

        };


// Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    }

    public void calculate() {

        cnt++;
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putInt(Count, cnt);
        editor.commit();
    }

    public void convertToImg(Integer cnt)
    {
        if ( Points2 != null ) {
            cnt = Integer.valueOf(Points2);
        }
//        else if ( Points2 == null || cnt == 0 ) {
//            Points2 = String.valueOf(mTextViewPoints);
//            cnt = Integer.valueOf(Points2);
//        }

        int a = cnt;

        Points2 = String.valueOf(cnt);

        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putInt(Count,cnt);
        editor.commit();

        SharedPreferences.Editor final_cnt = sharedpreferences.edit();
        final_cnt.putInt(FINAL_COUNT, cnt);
        final_cnt.commit();

        int num=0;
        int digit=0;
        while (a>=1)
        {


            num=a%10;

            a=a/10;

            Points = num;

            switch(num)
            {
                case 0:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==1)
                        dr1.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_0_500_clr_624);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_0_500_clr_624);

                    break;
                case 1:


                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==1)
                        dr1.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_1_500_clr_625);
                    break;
                case 2:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_2_500_clr_654);
                    break;

                case 3:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_3_500_clr_648);
                    break;
                case 4:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==1)
                        dr1.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_4_500_clr_650);
                    break;

                case 5:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_5_500_clr_643);
                    break;

                case 6:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_6_500_clr_630);
                    break;
                case 7:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_7_500_clr_615);
                    break;
                case 8:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_8_500_clr_647);
                    break;
                case 9:

                    if(digit==0)
                        dr0.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==1)

                        dr1.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==2)
                        dr2.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==3)
                        dr3.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==4)
                        dr4.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==5)
                        dr5.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==6)
                        dr6.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==7)
                        dr7.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==8)
                        dr8.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    if(digit==9)
                        dr9.setImageResource(R.drawable.gold_streak_9_500_clr_617);
                    break;

                default:
                    Toast.makeText(this,"error", Toast.LENGTH_SHORT).show();

            }

            digit++;
        }
    }
}

1 Ответ

0 голосов
/ 16 октября 2018

Я думаю, что вы ищете фоновые сервисы.

Посмотрите на это: Запуск фоновых сервисов

Таким образом, фоновый сервис будет использоваться для таймераи продолжается, если вы переходите к другим действиям (вы должны помнить о том, чтобы остановить его при закрытии приложения)

...