Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.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
Java 为什么我的应用程序在调用stopService()时崩溃?_Java_Android_Android Studio_Service_Intentservice - Fatal编程技术网

Java 为什么我的应用程序在调用stopService()时崩溃?

Java 为什么我的应用程序在调用stopService()时崩溃?,java,android,android-studio,service,intentservice,Java,Android,Android Studio,Service,Intentservice,我正在尝试使用服务创建一个包含计时器的应用程序(用户单击文本视图后,cardview元素被禁用,以显示倒计时计时器),但是计时器工作正常,但当计时器完成时(达到0:1),我调用stopService(intent);要停止服务并重新启用cardview,以允许用户再次单击它,从而导致应用程序崩溃,我已检查,在我尝试停止服务时,服务已启动,这就是我迄今为止所做的所有操作。。我是新的服务和安卓,任何帮助将不胜感激…谢谢你 选择achoice.java public class SelectaChoi

我正在尝试使用服务创建一个包含计时器的应用程序(用户单击文本视图后,cardview元素被禁用,以显示倒计时计时器),但是计时器工作正常,但当计时器完成时(达到0:1),我调用stopService(intent);要停止服务并重新启用cardview,以允许用户再次单击它,从而导致应用程序崩溃,我已检查,在我尝试停止服务时,服务已启动,这就是我迄今为止所做的所有操作。。我是新的服务和安卓,任何帮助将不胜感激…谢谢你

选择achoice.java

public class SelectaChoice extends AppCompatActivity implements RewardedVideoAdListener  {

private TextView coins2;
private boolean connected;
public SharedPreferences coins;
private String currentCoins;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
private FirebaseAuth firebaseAuth;
private DatabaseReference mRef;
private RewardedVideoAd mRewardedVideoAd;
private InterstitialAd mInterstitialAd;
private Intent intent_service;





String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private TextView TextviewAds;
private CardView cardsmallads;






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




    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            if (null != activeNetwork) {
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { }
                if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { }
            } else {

                Intent intent = new Intent(SelectaChoice.this, NoInternetActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intent);
                finish();

            }
            handler.postDelayed(this, 1000);
        }
    };

    mAuth = FirebaseAuth.getInstance();

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
    mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    mRewardedVideoAd.setRewardedVideoAdListener(this);
    loadRewardedVideoAd();
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
    mInterstitialAd.loadAd(new AdRequest.Builder().build());

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isAcceptingText()) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }

    final Handler handler2 = new Handler();
    final int delay = 1000; //milliseconds
    handler2.postDelayed(new Runnable(){
        public void run(){
            ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                    connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                connected = true;
            }
            else
                connected = false;
            handler2.postDelayed(this, delay);
        }
    }, delay);

    coins = getSharedPreferences("Rewards", MODE_PRIVATE);
    currentCoins = coins.getString("Coins", "0");
    ImageView settingbtn = (ImageView) findViewById(R.id.imageView9);
    settingbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            presentActivity(v);
        }
    });
    coins2 = (TextView) findViewById(R.id.textViewCoins);
    coins2.setText(currentCoins);

    FirebaseDatabase database =  FirebaseDatabase.getInstance();
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user =  mAuth.getCurrentUser();
    String userId = user.getUid();
    mRef =  database.getReference().child("Users").child(userId);
    mRef.child("Coins").setValue(currentCoins);
    coins2 = (TextView) findViewById(R.id.textViewCoins);

    final CardView cardsmallads = findViewById(R.id.smallads);
    try {
        String str_value = mpref.getString("data", "");
        if (str_value.matches("")) {
            cardsmallads.setEnabled(true);
            TextviewAds.setText("Get 20 coin");

        } else {

            if (mpref.getBoolean("finish", false)) {
                cardsmallads.setEnabled(true);
                TextviewAds.setText("Get 20 coin");
            } else {

                cardsmallads.setEnabled(false);
                // TextviewAds.setText("Next Try "+str_value);
            }
        }
    } catch (Exception e) {

    }
    cardsmallads.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();



                cardsmallads.setEnabled (false);
                calendar = Calendar.getInstance();
                simpleDateFormat = new SimpleDateFormat ("HH:mm:ss");
                date_time = simpleDateFormat.format(calendar.getTime());
                mEditor.putString("data", date_time).commit();
                mEditor.putString("hours", "1").commit();
                Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
                startService(intent_service);


            } else {
                Toast.makeText(SelectaChoice.this, "The Ads wasn't loaded yet. Try again later", Toast.LENGTH_SHORT).show();
                Log.d("TAG", "The interstitial wasn't loaded yet.");}
        }
    });

    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdOpened() {
            int coinCount = Integer.parseInt(coins.getString("Coins", "0"));
            coinCount = coinCount + 20;
            SharedPreferences.Editor coinsEdit = coins.edit();
            coinsEdit.putString("Coins", String.valueOf(coinCount));
            coinsEdit.apply();
            coins2.setText(String.valueOf(coinCount));
        }
        @Override
        public void onAdClosed() {
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
        }
    });

    final Handler handler1 = new Handler();
    Runnable runnableCode = new Runnable() {
        @Override
        public void run() {
            int coinCount = Integer.parseInt(coins.getString("Coins", "0"));
            coins2.setText(String.valueOf(coinCount));
            Log.d("Handlers", "Called on main thread");
            handler1.postDelayed(this, 2000);
        }
    };
    handler.post(runnableCode);
}

private void init() {

    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();
    TextviewAds = (TextView) findViewById(R.id.TextviewAds);

    try {
        String str_value = mpref.getString("data", "");
        if (str_value.matches("")) {
            cardsmallads.setEnabled(true);
            TextviewAds.setText("");

        } else {

            if (mpref.getBoolean("finish", false)) {
                cardsmallads.setEnabled(true);
                TextviewAds.setText("");
            } else {

                cardsmallads.setEnabled(false);
                TextviewAds.setText("");
            }
        }
    } catch (Exception e) {

    }
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver () {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        String str_time = intent.getStringExtra("time");
        TextviewAds.setText(str_time);
        if (str_time.equals("0:0:1")) {

            mEditor.clear().commit();
            stopService(intent_service); // stop service after work's done
            cardsmallads.setEnabled(true);
            TextviewAds.setText("Get 20 coin");

        }

    }

};



public void presentActivity(View view) {
    ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, view, "transition");
    int revealX = (int) (view.getX() + view.getWidth() / 2);
    int revealY = (int) (view.getY() + view.getHeight() / 2);
    Intent intent = new Intent(this, SettingsActivity.class);
    intent.putExtra(SettingsActivity.EXTRA_CIRCULAR_REVEAL_X, revealX);
    intent.putExtra(SettingsActivity.EXTRA_CIRCULAR_REVEAL_Y, revealY);
    ActivityCompat.startActivity(this, intent, options.toBundle());
}
public void startVideo(View view) {
    if(mRewardedVideoAd.isLoaded()){
        mRewardedVideoAd.show();
    }  else {
        Toast.makeText(SelectaChoice.this, "The Video wasn't loaded yet. Try again later", Toast.LENGTH_SHORT).show();
        Log.d("TAG", "The mRewardedVideoAd wasn't loaded yet.");}

}
public void instruction(View view) {
    Intent openInstructions = new Intent(getApplicationContext(), Instructions.class);
    startActivity(openInstructions);
}
public void redeem(View view) {
    Intent openRedeem = new Intent(getApplicationContext(), Redeem.class);
    startActivity(openRedeem);
}
public void aboutus(View view) {
    String url = "https://www.codester.com/micodes?ref=micodes";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}
public void contact(View view) {
    Intent contact = new Intent(Intent.ACTION_SENDTO);
    contact.setData(Uri.parse("mailto:strba.dev@gmail.com"));
    startActivity(contact);
}
public void dailyCheck(View view) {
    Intent openDailyChecks = new Intent(getApplicationContext(), DailyCheckins.class);
    startActivity(openDailyChecks);
}
public void luckyWheel(View view) {
    Intent openLuckyWheel = new Intent(getApplicationContext(), LuckyWheel.class);
    startActivity(openLuckyWheel);
}
@Override
public void onBackPressed() {
    Log.d("CDA", "onBackPressed Called");
    Intent setIntent = new Intent(Intent.ACTION_MAIN);
    setIntent.addCategory(Intent.CATEGORY_HOME);
    setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(setIntent);
}
@Override
public void onRewarded(RewardItem reward) {
    int coinCount = Integer.parseInt(coins.getString("Coins", "0"));
    coinCount = coinCount + 50;
    SharedPreferences.Editor coinsEdit = coins.edit();
    coinsEdit.putString("Coins", String.valueOf(coinCount));
    coinsEdit.apply();
    coins2.setText(String.valueOf(coinCount));
}
private void loadRewardedVideoAd() {
    if (!mRewardedVideoAd.isLoaded()){
        mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
    }
}
@Override
public void onRewardedVideoAdLeftApplication() {}
@Override
public void onRewardedVideoAdClosed() {
    loadRewardedVideoAd();
}
@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {}
@Override
public void onRewardedVideoAdLoaded() {}
@Override
public void onRewardedVideoAdOpened() {}
@Override
public void onRewardedVideoStarted() {}
@Override
public void onRewardedVideoCompleted() {
    loadRewardedVideoAd();
}
@Override
public void onResume() {
    mRewardedVideoAd.resume(this);
    registerReceiver(broadcastReceiver,new IntentFilter (Timer_Service.str_receiver));

    super.onResume();
}
@Override
public void onPause() {
    mRewardedVideoAd.pause(this);
    unregisterReceiver(broadcastReceiver);
    super.onPause();
}
@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(this);
    super.onDestroy();
}
public class Timer_Service extends Service {

public static String str_receiver = "com.example.watch.receiver";

private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;

private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent2;

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

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

    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();
    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

    mTimer = new Timer();
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
    intent2 = new Intent(str_receiver);
}


class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        mHandler.post(new Runnable() {

            @Override
            public void run() {

                calendar = Calendar.getInstance();
                simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                strDate = simpleDateFormat.format(calendar.getTime());
                Log.e("strDate", strDate);
                twoDatesBetweenTime();

            }

        });
    }

}

public String twoDatesBetweenTime() {


    try {
        date_current = simpleDateFormat.parse(strDate);
    } catch (Exception e) {

    }

    try {
        date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
    } catch (Exception e) {

    }

    try {


        long diff = date_current.getTime() - date_diff.getTime();
        // long int_hours = Long.parseLong(mpref.getString("hours", ""));
        //long int_hours = new Long("0.1").longValue();
        int int_hours = Integer.valueOf(mpref.getString("hours", ""));

        // long int_timer = TimeUnit.HOURS.toMillis(int_hours);

        long int_timer = TimeUnit.MINUTES.toMillis(int_hours);
        long long_hours = int_timer - diff;
        long diffSeconds2 = long_hours / 1000 % 60;
        long diffMinutes2 = long_hours / (60 * 1000) % 60;
        long diffHours2 = 0;
        if (int_hours>59){
            diffHours2 = long_hours / (60 * 60 * 1000) % 24;

        }
        //long diffHours2 = long_hours / (60 * 60 * 1000) % 24;


        if (long_hours > 0) {
            String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
            // String str_testing = diffMinutes2 + ":" + diffSeconds2;

            Log.e("TIME", str_testing);

            fn_update(str_testing);
        } else {
            mEditor.putBoolean("finish", true).commit();
            mTimer.cancel();
        }
    }catch (Exception e){
        mTimer.cancel();
        mTimer.purge();


    }

    return "";

}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("Service finish","Finish");
}

private void fn_update(String str_time){

    intent2.putExtra("time",str_time);
    sendBroadcast(intent2);
}
}

Timer\u service.java

public class SelectaChoice extends AppCompatActivity implements RewardedVideoAdListener  {

private TextView coins2;
private boolean connected;
public SharedPreferences coins;
private String currentCoins;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
private FirebaseAuth firebaseAuth;
private DatabaseReference mRef;
private RewardedVideoAd mRewardedVideoAd;
private InterstitialAd mInterstitialAd;
private Intent intent_service;





String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private TextView TextviewAds;
private CardView cardsmallads;






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




    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            if (null != activeNetwork) {
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { }
                if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { }
            } else {

                Intent intent = new Intent(SelectaChoice.this, NoInternetActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intent);
                finish();

            }
            handler.postDelayed(this, 1000);
        }
    };

    mAuth = FirebaseAuth.getInstance();

    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
    mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    mRewardedVideoAd.setRewardedVideoAdListener(this);
    loadRewardedVideoAd();
    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
    mInterstitialAd.loadAd(new AdRequest.Builder().build());

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isAcceptingText()) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }

    final Handler handler2 = new Handler();
    final int delay = 1000; //milliseconds
    handler2.postDelayed(new Runnable(){
        public void run(){
            ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                    connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                connected = true;
            }
            else
                connected = false;
            handler2.postDelayed(this, delay);
        }
    }, delay);

    coins = getSharedPreferences("Rewards", MODE_PRIVATE);
    currentCoins = coins.getString("Coins", "0");
    ImageView settingbtn = (ImageView) findViewById(R.id.imageView9);
    settingbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            presentActivity(v);
        }
    });
    coins2 = (TextView) findViewById(R.id.textViewCoins);
    coins2.setText(currentCoins);

    FirebaseDatabase database =  FirebaseDatabase.getInstance();
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user =  mAuth.getCurrentUser();
    String userId = user.getUid();
    mRef =  database.getReference().child("Users").child(userId);
    mRef.child("Coins").setValue(currentCoins);
    coins2 = (TextView) findViewById(R.id.textViewCoins);

    final CardView cardsmallads = findViewById(R.id.smallads);
    try {
        String str_value = mpref.getString("data", "");
        if (str_value.matches("")) {
            cardsmallads.setEnabled(true);
            TextviewAds.setText("Get 20 coin");

        } else {

            if (mpref.getBoolean("finish", false)) {
                cardsmallads.setEnabled(true);
                TextviewAds.setText("Get 20 coin");
            } else {

                cardsmallads.setEnabled(false);
                // TextviewAds.setText("Next Try "+str_value);
            }
        }
    } catch (Exception e) {

    }
    cardsmallads.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();



                cardsmallads.setEnabled (false);
                calendar = Calendar.getInstance();
                simpleDateFormat = new SimpleDateFormat ("HH:mm:ss");
                date_time = simpleDateFormat.format(calendar.getTime());
                mEditor.putString("data", date_time).commit();
                mEditor.putString("hours", "1").commit();
                Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
                startService(intent_service);


            } else {
                Toast.makeText(SelectaChoice.this, "The Ads wasn't loaded yet. Try again later", Toast.LENGTH_SHORT).show();
                Log.d("TAG", "The interstitial wasn't loaded yet.");}
        }
    });

    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdOpened() {
            int coinCount = Integer.parseInt(coins.getString("Coins", "0"));
            coinCount = coinCount + 20;
            SharedPreferences.Editor coinsEdit = coins.edit();
            coinsEdit.putString("Coins", String.valueOf(coinCount));
            coinsEdit.apply();
            coins2.setText(String.valueOf(coinCount));
        }
        @Override
        public void onAdClosed() {
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
        }
    });

    final Handler handler1 = new Handler();
    Runnable runnableCode = new Runnable() {
        @Override
        public void run() {
            int coinCount = Integer.parseInt(coins.getString("Coins", "0"));
            coins2.setText(String.valueOf(coinCount));
            Log.d("Handlers", "Called on main thread");
            handler1.postDelayed(this, 2000);
        }
    };
    handler.post(runnableCode);
}

private void init() {

    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();
    TextviewAds = (TextView) findViewById(R.id.TextviewAds);

    try {
        String str_value = mpref.getString("data", "");
        if (str_value.matches("")) {
            cardsmallads.setEnabled(true);
            TextviewAds.setText("");

        } else {

            if (mpref.getBoolean("finish", false)) {
                cardsmallads.setEnabled(true);
                TextviewAds.setText("");
            } else {

                cardsmallads.setEnabled(false);
                TextviewAds.setText("");
            }
        }
    } catch (Exception e) {

    }
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver () {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        String str_time = intent.getStringExtra("time");
        TextviewAds.setText(str_time);
        if (str_time.equals("0:0:1")) {

            mEditor.clear().commit();
            stopService(intent_service); // stop service after work's done
            cardsmallads.setEnabled(true);
            TextviewAds.setText("Get 20 coin");

        }

    }

};



public void presentActivity(View view) {
    ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, view, "transition");
    int revealX = (int) (view.getX() + view.getWidth() / 2);
    int revealY = (int) (view.getY() + view.getHeight() / 2);
    Intent intent = new Intent(this, SettingsActivity.class);
    intent.putExtra(SettingsActivity.EXTRA_CIRCULAR_REVEAL_X, revealX);
    intent.putExtra(SettingsActivity.EXTRA_CIRCULAR_REVEAL_Y, revealY);
    ActivityCompat.startActivity(this, intent, options.toBundle());
}
public void startVideo(View view) {
    if(mRewardedVideoAd.isLoaded()){
        mRewardedVideoAd.show();
    }  else {
        Toast.makeText(SelectaChoice.this, "The Video wasn't loaded yet. Try again later", Toast.LENGTH_SHORT).show();
        Log.d("TAG", "The mRewardedVideoAd wasn't loaded yet.");}

}
public void instruction(View view) {
    Intent openInstructions = new Intent(getApplicationContext(), Instructions.class);
    startActivity(openInstructions);
}
public void redeem(View view) {
    Intent openRedeem = new Intent(getApplicationContext(), Redeem.class);
    startActivity(openRedeem);
}
public void aboutus(View view) {
    String url = "https://www.codester.com/micodes?ref=micodes";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}
public void contact(View view) {
    Intent contact = new Intent(Intent.ACTION_SENDTO);
    contact.setData(Uri.parse("mailto:strba.dev@gmail.com"));
    startActivity(contact);
}
public void dailyCheck(View view) {
    Intent openDailyChecks = new Intent(getApplicationContext(), DailyCheckins.class);
    startActivity(openDailyChecks);
}
public void luckyWheel(View view) {
    Intent openLuckyWheel = new Intent(getApplicationContext(), LuckyWheel.class);
    startActivity(openLuckyWheel);
}
@Override
public void onBackPressed() {
    Log.d("CDA", "onBackPressed Called");
    Intent setIntent = new Intent(Intent.ACTION_MAIN);
    setIntent.addCategory(Intent.CATEGORY_HOME);
    setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(setIntent);
}
@Override
public void onRewarded(RewardItem reward) {
    int coinCount = Integer.parseInt(coins.getString("Coins", "0"));
    coinCount = coinCount + 50;
    SharedPreferences.Editor coinsEdit = coins.edit();
    coinsEdit.putString("Coins", String.valueOf(coinCount));
    coinsEdit.apply();
    coins2.setText(String.valueOf(coinCount));
}
private void loadRewardedVideoAd() {
    if (!mRewardedVideoAd.isLoaded()){
        mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
    }
}
@Override
public void onRewardedVideoAdLeftApplication() {}
@Override
public void onRewardedVideoAdClosed() {
    loadRewardedVideoAd();
}
@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {}
@Override
public void onRewardedVideoAdLoaded() {}
@Override
public void onRewardedVideoAdOpened() {}
@Override
public void onRewardedVideoStarted() {}
@Override
public void onRewardedVideoCompleted() {
    loadRewardedVideoAd();
}
@Override
public void onResume() {
    mRewardedVideoAd.resume(this);
    registerReceiver(broadcastReceiver,new IntentFilter (Timer_Service.str_receiver));

    super.onResume();
}
@Override
public void onPause() {
    mRewardedVideoAd.pause(this);
    unregisterReceiver(broadcastReceiver);
    super.onPause();
}
@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(this);
    super.onDestroy();
}
public class Timer_Service extends Service {

public static String str_receiver = "com.example.watch.receiver";

private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;

private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent2;

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

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

    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();
    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

    mTimer = new Timer();
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
    intent2 = new Intent(str_receiver);
}


class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        mHandler.post(new Runnable() {

            @Override
            public void run() {

                calendar = Calendar.getInstance();
                simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                strDate = simpleDateFormat.format(calendar.getTime());
                Log.e("strDate", strDate);
                twoDatesBetweenTime();

            }

        });
    }

}

public String twoDatesBetweenTime() {


    try {
        date_current = simpleDateFormat.parse(strDate);
    } catch (Exception e) {

    }

    try {
        date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
    } catch (Exception e) {

    }

    try {


        long diff = date_current.getTime() - date_diff.getTime();
        // long int_hours = Long.parseLong(mpref.getString("hours", ""));
        //long int_hours = new Long("0.1").longValue();
        int int_hours = Integer.valueOf(mpref.getString("hours", ""));

        // long int_timer = TimeUnit.HOURS.toMillis(int_hours);

        long int_timer = TimeUnit.MINUTES.toMillis(int_hours);
        long long_hours = int_timer - diff;
        long diffSeconds2 = long_hours / 1000 % 60;
        long diffMinutes2 = long_hours / (60 * 1000) % 60;
        long diffHours2 = 0;
        if (int_hours>59){
            diffHours2 = long_hours / (60 * 60 * 1000) % 24;

        }
        //long diffHours2 = long_hours / (60 * 60 * 1000) % 24;


        if (long_hours > 0) {
            String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
            // String str_testing = diffMinutes2 + ":" + diffSeconds2;

            Log.e("TIME", str_testing);

            fn_update(str_testing);
        } else {
            mEditor.putBoolean("finish", true).commit();
            mTimer.cancel();
        }
    }catch (Exception e){
        mTimer.cancel();
        mTimer.purge();


    }

    return "";

}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("Service finish","Finish");
}

private void fn_update(String str_time){

    intent2.putExtra("time",str_time);
    sendBroadcast(intent2);
}
}

LogCat

2020-09-13 17:34:06.544 18987-18987/com.example.watch E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.watch, PID: 18987
java.lang.RuntimeException: Error receiving broadcast Intent { act=com.example.watch.receiver flg=0x10 (has extras) } in com.example.watch.SelectaChoice$7@b116d9d
    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1174)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
 Caused by: java.lang.IllegalArgumentException: connection is null
    at android.app.ContextImpl.unbindService(ContextImpl.java:1492)
    at android.content.ContextWrapper.unbindService(ContextWrapper.java:648)
    at com.example.watch.SelectaChoice$7.onReceive(SelectaChoice.java:287)
    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1164)
    at android.os.Handler.handleCallback(Handler.java:836) 
    at android.os.Handler.dispatchMessage(Handler.java:103) 
    at android.os.Looper.loop(Looper.java:203) 
    at android.app.ActivityThread.main(ActivityThread.java:6251) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
2020-09-13 17:34:07.185 2287-2287/?E/Launcher.Utilities:NoSuchMethodError发生广播stkintent。 java.lang.NoSuchMethodError:没有静态方法SemgetElephonyProperty(ILjava/lang/String;Ljava/lang/String;)Ljava/lang/String;类内Landroid/telephony/TelephonyManager;或其超类(在/system/framework/framework.jar:classes2.dex中出现“android.telephony.TelephonyManager”声明) 在com.android.launcher3.Utilities.broadcastStkIntent上(Utilities.java:1418) 在com.android.Launcher.3.Launcher.onResume上(Launcher.java:885) 位于android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269) 在android.app.Activity.performResume(Activity.java:6929)上 位于android.app.ActivityThread.performResumeActivity(ActivityThread.java:3477) 位于android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546) 在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1577)上 位于android.os.Handler.dispatchMessage(Handler.java:110) 位于android.os.Looper.loop(Looper.java:203) 位于android.app.ActivityThread.main(ActivityThread.java:6251) 位于java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)上 位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 2020-09-13 17:34:07.233 10642-11206/? E/PBSessionCacheImpl:sessionId[46805610984838194]未持久化