stopwatch - how to? - android

I have been trying to build a stopwatch in my app which starts counting on a start button click.I want it to count from seconds then minutes, then Hour but the problem is I can't count Hour but I can count milliseconds which I do not want. is that possible on start button click the app takes the current system time and on stop click just calculate and print the interval between starts and stop clicks?
Here is my activity class
package com.example.rimapps.stopwatch;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button but1,but2;
long MillisecondTIme,StarTime,TimeBuff,UpdateTime=0L;
Handler handler;
int MilliSeconds,Seconds,Minutes,Hour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
but1=(Button)findViewById(R.id.buttonstart);
but2=(Button)findViewById(R.id.buttonstop);
handler = new Handler();
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Date d=new Date();
//SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
//String currentDateTimeString=sdf.format(d);
//textView.setText(currentDateTimeString);
StarTime=SystemClock.uptimeMillis();
handler.postDelayed(runnable,0);
//reset.setEnabled(false);
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MillisecondTIme=0L;
TimeBuff = 0L ;
UpdateTime = 0L ;
Seconds = 0 ;
Minutes = 0 ;
MilliSeconds = 0 ;
textView.setText("00:00:00");
}
});
}
public Runnable runnable=new Runnable() {
#Override
public void run() {
MillisecondTIme=SystemClock.uptimeMillis()-StarTime;
UpdateTime=TimeBuff+MillisecondTIme;
Seconds=(int)(UpdateTime/1000);
Minutes=Seconds/60;
Seconds=Seconds%60;
MilliSeconds=(int)(UpdateTime%1000);
textView.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this,0);
}
};
}
here is my xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rimapps.stopwatch.MainActivity">
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#009688"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
<Button
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="47dp"
android:id="#+id/buttonstart"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:text="Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonstop"
android:layout_marginRight="89dp"
android:layout_marginEnd="89dp"
android:layout_marginTop="140dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>

While I was learning a book I also had a stopwatch coding problem this is a sample of the code I use.
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
int hours=seconds/3600;
int minutes=(seconds%3600)/60;
int secs=seconds%60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
also understand Handler class, handler will always run the code immediately(like every second forever) so you gotta add a boolean value that know if it is running then set it to your button like if start button is click you got to set the running to true. Handler will always run forever like the famous loop() method of arduino(it is running forever).

Use sendMessage that does have a clearMessage instead of postRunnable
This time I'll write for you (most for fix convention with camel case):
The stop function is at the second button action listener
package com.example.rimapps.stopwatch;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button but1,but2;
long millisecondTIme,starTime,timeBuff,updateTime=0L;
Handler handler;
int milliSeconds,seconds,minutes,hour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
but1=(Button)findViewById(R.id.buttonstart);
but2=(Button)findViewById(R.id.buttonstop);
handler = new Handler() {
public void handleMessage(Message what) {
millisecondTIme=SystemClock.uptimeMillis()-starTime;
updateTime=timeBuff+millisecondTIme;
seconds=(int)(UpdateTime/1000);
minutes=Seconds/60;
seconds=Seconds%60;
milliSeconds=(int)(updateTime%1000);
textView.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliSeconds));
handler.sendEmptyMessageDelayed(0, 1000); //repost in a loop
}
}
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
starTime=SystemClock.uptimeMillis();
handler.sendEmptyMessage(0); //Here send message with id 0
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
millisecondTIme=0L;
timeBuff = 0L ;
updateTime = 0L ;
seconds = 0 ;
minutes = 0 ;
milliSeconds = 0 ;
textView.setText("00:00:00");
handler.removeMessages(0); //Here clear all messages with same id
}
});
}
}

Related

All SeekBar + onProgressChanged + MediaPlayer + MeidaPlayer.getDuration() + Android OS Bugs do not work with me I have "The Ultimate Solution"

I have tried all the solutions on StackOverflow and none solved my issue, I'm looking for the ultimate solution, for the problem, I can solve all these problems with one working code? and 1 software.
Also, I added how to load lyrics using volley, and the PHP backend code.
The Ultimate Solution is: reencode your video or audio with an encoder that put seek points of the video or audio in the start index of the file and I found one good free software that solves this problem, which is "Miro Video Converter"
Note: mp3 encoding should be 128kb or more before using Miro Video
Encoder
and the Ultimate code that Will Work for Sure with this Excellent Encoding for audio is (video is the same solution but you change the code to what your video player code is I'm making a songs player with lyrics fragment):
Java:: "SongsFragment.java"
package com.emadzedan.acdc;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import java.io.IOException;
import java.util.Objects;
import static android.content.Context.MODE_PRIVATE;
public class SongsFragment extends Fragment {
private static final String TAG = "Debug: ";
private Button playButton;
private SeekBar seekBar;
private Handler handler;
private Runnable runnable;
private TextView lyricsTextView;
private TextView currentTime;
private SharedPreferences prefs;
public SongsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_songs, container, false);
AdManager adManager = AdManager.getInstance();
adManager.createAd(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "path to: volleyLyrics.php"),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
lyricsTextView = Objects.requireNonNull(getView()).findViewById(R.id.lyricsTextView);
lyricsTextView.setText(Html.fromHtml(response));
DrawerBaseActivity.DisableBackButtonOnLoadSongDetailsError = false;
}
}, new Response.ErrorListener() {
#SuppressLint("SetTextI18n")
#Override
public void onErrorResponse(VolleyError error) {
lyricsTextView = (TextView) Objects.requireNonNull(getView()).findViewById(R.id.lyricsTextView);
lyricsTextView.setText(R.string.lyrics_error);
}
});
MySingleton.getInstance(view.getContext()).addToRequestQueue(stringRequest);
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (!DrawerBaseActivity.DisableBackButtonOnLoadSongDetailsError) {
handler.removeCallbacks(runnable);
DrawerBaseActivity.releaseMediaPlayer();
DrawerBaseActivity.titleTextView.setText(R.string.all_songs);
DrawerBaseActivity.CurrentFragment = "Search";
Objects.requireNonNull(getActivity()).onBackPressed();
}
return true;
}
return false;
}
});
playButton = view.findViewById(R.id.playButton);
playButton.setVisibility(View.GONE);
DrawerBaseActivity.mediaPlayer = new MediaPlayer();
DrawerBaseActivity.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
DrawerBaseActivity.mediaPlayer.seekTo(0);
currentTime = view.findViewById(R.id.currentTime);
handler = new Handler();
seekBar = view.findViewById(R.id.seekBar);
seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
try {
DrawerBaseActivity.mediaPlayer = new MediaPlayer();
DrawerBaseActivity.mediaPlayer.setDataSource("song.mp3");
DrawerBaseActivity.mediaPlayer.prepare();
DrawerBaseActivity.mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playButton.setVisibility(View.VISIBLE);
seekBar.setMax(DrawerBaseActivity.mediaPlayer.getDuration());
Log.v(TAG, "getDuration= " + DrawerBaseActivity.mediaPlayer.getDuration());
}
});
} catch (IOException e) {
e.printStackTrace();
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
DrawerBaseActivity.mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!DrawerBaseActivity.mediaPlayer.isPlaying()) {
DrawerBaseActivity.mediaPlayer.start();
playCycle();
playButton.setBackgroundResource(R.drawable.pause);
} else {
DrawerBaseActivity.mediaPlayer.pause();
playButton.setBackgroundResource(R.drawable.play);
handler.removeCallbacks(runnable);
}
}
});
DrawerBaseActivity.selectedItem = 0;
handler = new Handler();
Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
#Override
public void run() {
if (DrawerBaseActivity.mediaPlayer != null) {
seekBar.setProgress(DrawerBaseActivity.mediaPlayer.getCurrentPosition());
}
handler.postDelayed(this, 1000);
}
});
return view;
}
private void playCycle() {
if (DrawerBaseActivity.mediaPlayer != null) {
if (DrawerBaseActivity.mediaPlayer.isPlaying()) {
runnable = new Runnable() {
#Override
public void run() {
playCycle();
}
};
handler.postDelayed(runnable, 1000);
seekBar.setProgress(DrawerBaseActivity.mediaPlayer.getCurrentPosition());
currentTime.setText(formatTime(DrawerBaseActivity.mediaPlayer.getCurrentPosition()));
Log.v(TAG, "getCurrentPosition= " + DrawerBaseActivity.mediaPlayer.getCurrentPosition());
} else {
seekBar.setProgress(0);
DrawerBaseActivity.mediaPlayer.seekTo(0);
DrawerBaseActivity.mediaPlayer.pause();
playButton.setBackgroundResource(R.drawable.play);
handler.removeCallbacks(runnable);
}
}
}
#SuppressLint("DefaultLocale")
private String formatTime(int millis) {
int seconds = millis / 1000;
int minutes = seconds / 60;
int hours = minutes / 60;
//you can after ? put "00:"
return (hours == 0 ? "" : hours + ":") + String.format("%02d:%02d", minutes % 60, seconds % 60);
}
}
XML Layout: "fragment_songs.xml"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#color/colorWhite"
tools:context=".SongsFragment">
<ScrollView
android:id="#+id/songLyricsScrollView"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_marginBottom="70dp"
android:layout_height="match_parent"
android:background="#color/colorWhite">
<TextView
android:id="#+id/lyricsTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:scrollbars="vertical"
android:text="#string/TestLyrics"
android:fontFamily="#font/rudebook"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp" />
</ScrollView>
<LinearLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="8dp"
android:layout_alignParentBottom="true"
tools:ignore="RtlHardcoded"
android:background="#color/colorPrimaryDark">
<SeekBar
android:id="#+id/seekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
/>
<TextView
android:id="#+id/currentTime"
android:layout_width="40dp"
android:layout_height="match_parent"
android:paddingTop="14dp"
android:textColor="#color/colorAccent"
android:text="#string/_00_00"
android:fontFamily="#font/rudelight"
android:textSize="12sp"
android:layout_weight="0.05"
android:layout_marginLeft="10dp" />
<RelativeLayout
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_weight="0.05"
android:layout_marginBottom="10dp"
tools:ignore="RtlHardcoded">
<Button
android:id="#+id/playButton"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="gone"
android:background="#drawable/play"
/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
PHP file:: "volleyLyrics.php"
<?php
$albumNumber = $_GET["albumNumber"];
$lyricsNumber = $_GET["lyricsNumber"];
$data = file_get_contents(__DIR__ . "/lyrics.txt") or die("Unable to open file!");
echo nl2br($data);
?>
Note: the text file of the lyrics is in the same directory as the PHP
file

Android timer,Broadcast Receiver,

Developing a timer application,
Have 4 buttons
start--Will start the timer
stop-- will stop timer
pause--will pause timer
lap time--will calculate lap time.
when button click it s working Good.
Now i am Modify the application like timer should start when phone is connected to charger and pause when phone is disconnected from charger.
The timer is starting fine when connected to the charger,
but during discharging the stop timer is not stopping at the accurate time it will be misplaced with some other time.i.e delay in minutes and seconds.
How to make the timer pause and show correct timer when disconnected from the charger...?
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
private static final String TAG ="Main Activity";
TextView textView;
Button start, pause, reset, lap;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L;
Handler handlerr;
int Seconds, Minutes, MilliSeconds;
ListView listView;
String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
TextView textview;
Button button;
IntentFilter intentfilter;
int deviceStatus;
String currentBatteryStatus = "Battery Info";
int batteryLevel;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textViewBatteryStatus);
intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
MainActivity.this.registerReceiver(broadcastreceiver, intentfilter);
textView = (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
pause = (Button)findViewById(R.id.button2);
reset = (Button)findViewById(R.id.button3);
lap = (Button)findViewById(R.id.button4) ;
listView = (ListView)findViewById(R.id.listview1);
handler = new Handler() ;
ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
ListElementsArrayList
);
listView.setAdapter(adapter);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
reset.setEnabled(false);
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
reset.setEnabled(true);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MillisecondTime = 0L ;
StartTime = 0L ;
TimeBuff = 0L ;
UpdateTime = 0L ;
Seconds = 0 ;
Minutes = 0 ;
MilliSeconds = 0 ;
textView.setText("00:00:00");
ListElementsArrayList.clear();
adapter.notifyDataSetChanged();
}
});
lap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListElementsArrayList.add(textView.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
public Runnable runnable = new Runnable() {
public void run() {
MillisecondTime = SystemClock.uptimeMillis() - StartTime;
UpdateTime = TimeBuff + MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
textView.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};
// Broadcasts receiver//
private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int batteryLevel=(int)(((float)level / (float)scale) * 100.0f);
if(deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING){
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
reset.setEnabled(false);
textview.setText(currentBatteryStatus+" = Charging at "+batteryLevel+" %");
}
if(deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){
textview.setText(currentBatteryStatus+" = Discharging at "+batteryLevel+" %");
}
if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL){
textview.setText(currentBatteryStatus+"= Battery Full at "+batteryLevel+" %");
}
if(deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN){
textview.setText(currentBatteryStatus+" = Unknown at "+batteryLevel+" %");
}
if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
reset.setEnabled(true);
textview.setText(currentBatteryStatus+" = Not Charging at "+batteryLevel+" %");
}
}
};
}
activity_main.xml
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#009688"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:id="#+id/button" />
<Button
android:text="Pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_centerHorizontal="true" />
<Button
android:text="Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button3" />
<Button
android:text="Save Lap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:id="#+id/button4"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button4"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:id="#+id/listview1"/>
<TextView
android:id="#+id/textViewBatteryStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/button2"
android:layout_below="#+id/textView"
android:text="Current Battery Status"
android:textAppearance="?android:attr/textAppearanceLarge" />
Guidance in editing code will be helpful.
If you want to catch the Charger Connected and Disconnected events, then you should not use the BATTERY_STATUS_CHARGING and BATTERY_STATUS_DISCHARGING at the first place.You should listen for -
<receiver android:name=".YourPowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
Thus you will get the broadcast only during charger connected and disconnected state.
Look here : https://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED

Show final time in Alert Dialog after 10 button clicks

Right now I have my app set to show an alert dialog after 10 button clicks as well as stop the timer. I cannot figure out how to display the final time the timer stops on in the alert dialog. I want to make an alert dialog that displays that the game is over and also displays the players final time. Any idea how I would do this? Please help if you can.
JAVA CODE:
package com.example.thirtytapgametest;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AnalogClock;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
public class MainActivity extends Activity {
private int mCount = 0;
private ImageButton startbutton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
timerValue = (TextView) findViewById(R.id.timerValue);
startbutton = (ImageButton) findViewById(R.id.imageButton1);
startbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mCount ==0) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
mCount++;
countTextView.setText("Taps: " + mCount);
if(mCount == 10) {
view.setEnabled(false);
customHandler.removeCallbacks(updateTimerThread);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Congratulations!")
.setMessage((R.id.timerValue))
.setIcon(R.drawable.ic_launcher)
.setCancelable(false)
.setPositiveButton(getString(R.string.play_again), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();}})
.setNegativeButton(getString(R.string.levels_menu), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();}});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
updatedTime = SystemClock.uptimeMillis() - startTime;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("Time: " + "" + mins + ":"
+String.format("%02d", secs) + ":"
+String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
}
XML CODE:
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/thirty_tap_game_background">
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="138dp"
android:background="#drawable/test_play_button" />
<TextView
android:id="#+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageButton1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:textSize="40sp"
android:textColor="#FFFFFF"
android:text="#string/timerVal" />
<TextView
android:id="#+id/TextViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:text="#string/countVal"
android:textSize="30sp"
android:textColor="#FFFFFF"/>
</RelativeLayout>
You can do this
int i =0; // declare this globally.
btn.setonclicklistener(new onClicklistener
onclick(View v){
i++;
if(i==10){
// show alert dialog
}
else{
// to do your stub here
}
}
You'll want to use the set message method in your AlertDialog builder.
.setTitle("Congratulations!")
.setMessage("Your time was: " + updatedTime)
.setIcon(R.drawable.ic_launcher)
why dont you use this?
http://developer.android.com/reference/android/widget/TextClock.html
and your code shows you using :
.setMessage((R.id.timerValue))
R.id.viewName refers to the hex id of the resource .Using this will not set the value that is contained in the textView.
you could try:
.setMessage(((TextView)R.id.timerValue).getText().toString())
or you could declare the text view earlier and call TextView.getText().toString() while creating the dialog.

Timer in three EditTexts not working properly

I have made a Timer Application in android.In application there are three (uneditable)EditText and a Button.When i press Button first time the timer in 1st EditText will start ,when i press it 2nd time the timer in 1st EditText will stop and at the same time the timer in 2nd EditText will be start,when i again press button same thing will be happened with 3rd EdtiText.NOw this code is working properly but when i press back button and again start it,its stopped working in 3rd EditText.The problem is sometimes the timer in 3rd EditText is not working(not displayed)..my code is as below:
mainActivity.java
package com.example.timerdemo2;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import org.w3c.dom.Text;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText et1,et2,et3;
TextView tv;
public int i=0;
long starttime = 0;
long lasttime,lasttime1;
final Handler handler = new Handler();
Handler h2 = new Handler();
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = (seconds%3600)/60;
int hours = seconds / 3600;
seconds = seconds % 60;
et1.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et2.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et3.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
h2.postDelayed(this, 500);
}
};
class firstTask extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
};
class secondTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et2.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
}
});
}
}
class thirdTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et3.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
h2.postDelayed(this, 500);
}
});
}
}
Timer timer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = this.getIntent().getExtras();
String title = bundle.getString("title");
tv = (TextView)findViewById(R.id.projectTitle);
tv.setText(title);
et1= (EditText)findViewById(R.id.timeEdit1);
et2= (EditText)findViewById(R.id.timeEdit2);
et3= (EditText)findViewById(R.id.timeEdit3);
Button b = (Button)findViewById(R.id.btn);
b.setText("Start");
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button b =(Button)v;
if(b.getText().equals("Stop")){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
Intent intent =new Intent(MainActivity.this,Timedetails.class);
Bundle bundle =new Bundle();
//Procedure for Showing time stamps on another page
String a = et1.getText().toString();
String b1 = et2.getText().toString();
String c = et3.getText().toString();
String t = tv.getText().toString();
intent.putExtra("titl1",t);
startActivity(intent);
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try{
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
Date date1 = (Date) format.parse(a);
Date date2 = (Date) format.parse(b1);
Date date3 = (Date) format.parse(c);
//time difference in milliseconds
long timeDiff = date2.getTime() - date1.getTime();
long timeDiff2 = date3.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
Date diffDate2 = new Date(timeDiff2);
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
long timeDiffSecs1 = timeDiff2/1000;
String timeDiffString1 = timeDiffSecs1/3600+":"+
(timeDiffSecs1%3600)/60+":"+
(timeDiffSecs1%3600)%60;
//formatted date string
// String timeDiffString = format.format(diffDate);
//System.out.println("Time Diff = "+ timeDiffString );
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
bundle.putString("dif1", timeDiffString);
bundle.putString("dif2", timeDiffString1);
}
catch(Exception e){
e.printStackTrace();
}
intent.putExtras(bundle);
startActivity(intent);
b.setText("Next");
}
else if(b.getText().equals("Lap1"))
{
timer.schedule(new secondTask(),0, 500);
h2.removeCallbacks(run);
b.setText("lap2");
}
else if(b.getText().equals("lap2")){
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
}
else {
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
// timer.schedule(new secondTask(), 0,500);
//timer.schedule(new thirdTask(), 0,500);
h2.postDelayed(run, 0);
b.setText("Lap1");
//long lastdown = System.currentTimeMillis();
}
}
});
}
}
MainActivity.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:background="#drawable/abs5"
android:orientation="vertical" >
<TextView
android:id="#+id/projectTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:layout_marginTop="5dp"
android:text="Project Title"
android:textColor="#CCCCCC"
android:textSize= "40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point1"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#CCCCCC" />
<EditText
android:id="#+id/timeEdit1"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false"
android:filterTouchesWhenObscured="false"
android:focusable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timing Point2"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit2"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:focusable="false"
android:filterTouchesWhenObscured="false"
android:background="#FFFFFF"
android:editable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point3"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit3"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal" >
<Button
android:id="#+id/btn"
android:layout_width="129dp"
android:layout_height="64dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="10dp"
android:background="#drawable/aqa"
android:textColor="#FFFFFF"
android:textSize="30dp" />
</LinearLayout>
</LinearLayout>
Please help me for this as fast ...really thanking you.....hav a gud tym
Look at this code in your lap2 handler:
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
You schedule a task and cancel the timer immediately afterwards.
I would suggest that you get rid of the Timer and just use the Handler.postDelayed() method, as you have done already for the time updates and to start the update of the first field:
h2.postDelayed(run, 0);
Use the same method to start the updates for second and third fields. You don't need the Timer and TimerTask instances at all.
Also, why do you need two handlers (handler, and h2)?

Taking double numbers back to previous activity

This is what i want to do with my application:
Open overview screen, go to calculator by button.
Than multiply two numbers.
By clicking calculate the intent will finish.
Outcome of multiply will be shown in first (main) activity.
I do not know how to do the last bit, someone any idea?
Code first (main) activity, OverviewpageActivity.java
package com.tip.calc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class OverviewpageActivity extends Activity {
private TextView multiplydisplay2;
private Button btntocalculator;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
multiplydisplay2 = (TextView)findViewById(R.id.multiplydisplay2);
btntocalculator = (Button)findViewById(R.id.btntocalculator);
btntocalculator.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
Intent intent = new Intent(OverviewpageActivity.this,
TipcalcActivity.class);
startActivity(intent);
}
});
}
}
Code calculator acticvity, TipcalcActivity.java:
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
// check if zero
if(number1.getText().toString().trim().length() < 1 ){number1calc=0;}
else{number1calc=Double.parseDouble(number1.getText().toString());}
if(number2.getText().toString().trim().length() < 1 ){number2calc=0;}
else{number2calc=Double.parseDouble(number2.getText().toString());}
//calculate
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
finish();
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
finish();
}
}
Layout file, overview.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btntocalculator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To the calculator" />
</LinearLayout>
Use startActivityforResult instead of startActivity in OverviewpageActivity.java and also override OnactivityResult in OverviewpageActivity.java.
Then in second activity you can set the result using setResult. Pass the intent in setresult which will have the double value.
In OnactivityResult you can get the intent from which you can extract double

Categories

Resources