stop watch logic - android

I want to develop a simple stop watch logic in android.
On clicking a list view the timer should start and on clicking the button the timer should stop. Can anyone please guide me. Any sample code will be of great help

Use the Stopwatch Class (For higher precision use System.nanoTime())
Add a Start() event and Stop() event on Button Presses. You'll need to update the UI so use a Thread/Handler Combination.
This should get you started.
EDIT: Added Code. (Nice Exercise! :) )
Use the Refresh_Rate to configure how often your UI is updated.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener{
final int MSG_START_TIMER = 0;
final int MSG_STOP_TIMER = 1;
final int MSG_UPDATE_TIMER = 2;
Stopwatch timer = new Stopwatch();
final int REFRESH_RATE = 100;
Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
tvTextView.setText(""+ timer.getElapsedTime());
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second,
break; //though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
tvTextView.setText(""+ timer.getElapsedTime());
break;
default:
break;
}
}
};
TextView tvTextView;
Button btnStart,btnStop;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvTextView = (TextView)findViewById(R.id.TextView01);
btnStart = (Button)findViewById(R.id.Button01);
btnStop= (Button)findViewById(R.id.Button02);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
public void onClick(View v) {
if(btnStart == v)
{
mHandler.sendEmptyMessage(MSG_START_TIMER);
}else
if(btnStop == v){
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
}
}

As st0le gave an excellent example by using Stopwatch class. I modified this class a little and add a few methods to it.
/*
Copyright (c) 2005, Corey Goldberg
StopWatch.java is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Modified: Bilal Rabbani bilalrabbani1#live.com (Nov 2013)
*/
package bilalrabbani1.at.live.com;
public class Stopwatch {
private long startTime = 0;
private boolean running = false;
private long currentTime = 0;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.running = false;
}
public void pause() {
this.running = false;
currentTime = System.currentTimeMillis() - startTime;
}
public void resume() {
this.running = true;
this.startTime = System.currentTimeMillis() - currentTime;
}
//elaspsed time in milliseconds
public long getElapsedTimeMili() {
long elapsed = 0;
if (running) {
elapsed =((System.currentTimeMillis() - startTime)/100) % 1000 ;
}
return elapsed;
}
//elaspsed time in seconds
public long getElapsedTimeSecs() {
long elapsed = 0;
if (running) {
elapsed = ((System.currentTimeMillis() - startTime) / 1000) % 60;
}
return elapsed;
}
//elaspsed time in minutes
public long getElapsedTimeMin() {
long elapsed = 0;
if (running) {
elapsed = (((System.currentTimeMillis() - startTime) / 1000) / 60 ) % 60;
}
return elapsed;
}
//elaspsed time in hours
public long getElapsedTimeHour() {
long elapsed = 0;
if (running) {
elapsed = ((((System.currentTimeMillis() - startTime) / 1000) / 60 ) / 60);
}
return elapsed;
}
public String toString() {
return getElapsedTimeHour() + ":" + getElapsedTimeMin() + ":"
+ getElapsedTimeSecs() + "." + getElapsedTimeMili();
}
}
Regards

Instead of using listview you simply use a text view for timer and 3 buttons for stop start and reset . Using these you can make the java code accordingly

Good example, just in case if someone wants that layout file to go with this (pretty simple though).
<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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<EditText
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginLeft="18dp"
android:layout_marginTop="49dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_marginTop="42dp"
android:layout_toRightOf="#+id/textView1"
android:text="Start" />
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Button01"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/textView1"
android:text="Stop" />

IntentService based, no non-SDK dependencies and on a single file:
import android.app.Activity;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Main extends Activity {
static final String BROADCAST_ACTION = "com.cirosantilli.android_cheat.intent_service_text_view.BROADCAST";
static final String EXTENDED_DATA_STATUS = "com.cirosantilli.android_cheat.intent_service_text_view.BROADCAST";
static final String TAG = "com.cirosantilli";
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
final LinearLayout linearLayout = new LinearLayout(this);
Button button;
final Intent intent = new Intent(Main.this, MyService.class);
button = new Button(this);
button.setText("start service");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "start button");
Main.this.startService(intent.putExtra(Main.EXTENDED_DATA_STATUS, Main.this.i));
}
});
linearLayout.addView(button);
button = new Button(this);
button.setText("stop service");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "stop button");
Main.this.stopService(intent);
}
});
linearLayout.addView(button);
final TextView textView = new TextView(this);
textView.setText(Integer.toString(i));
linearLayout.addView(textView);
this.setContentView(linearLayout);
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Main.this.i = intent.getIntExtra(Main.EXTENDED_DATA_STATUS, 0);
textView.setText(Integer.toString(Main.this.i));
}
}, new IntentFilter(Main.BROADCAST_ACTION)
);
}
public static class MyService extends IntentService {
private Handler mHandler;
private int i = 1;
private boolean done;
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent");
this.i = intent.getIntExtra(Main.EXTENDED_DATA_STATUS, 0);
this.done = false;
while(!done) {
Log.d(TAG, "while true");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
LocalBroadcastManager.getInstance(this).sendBroadcast(
new Intent(Main.BROADCAST_ACTION)
.putExtra(Main.EXTENDED_DATA_STATUS, MyService.this.i));
this.i++;
}
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
this.done = true;
super.onDestroy();
}
}
}
For low precision only. We could get increased precision by using System.currentTimeMillis inside onHandleIntent instead of using the integer value, and reducing the sleep time to reduce latency.
Tested on Android 22. Standard build boilerplate here.

Related

App crashes if no answer is given

My app is a timed math game. Answer as many questions as you can before the timer runs out. When the time runs out, The GameOverActivity is now the current activity. I've realized that if I give no answer, the app will crash. If I give at least 1 answer, the app doesn't crash and everything is normal. I'm not sure where the flaw in my code exista.
This is the Main Activity
package stormy.incremental.randomtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FastMathActivity extends AppCompatActivity {
int rand1, rand2, randDecider, correctAnswer, falseAnswer, problemsSolved;
String response,sumStr;
MyCountDownTimer myCountDownTimer;
int score;
Random r;
TextView randTV1, randTV2, scoreTV, sumTV, problemsSolvedTV, timerTV;
Button choice1, choice2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_test);
problemsSolved =0;
falseAnswer = 1;
//Initializing TextViews
timerTV = ((TextView) findViewById(R.id.timer));
randTV1 = ((TextView) findViewById(R.id.rand1));
randTV2 = ((TextView) findViewById(R.id.rand2));
sumTV = ((TextView) findViewById(R.id.sum));
scoreTV = ((TextView) findViewById(R.id.score));
problemsSolvedTV = ((TextView) findViewById(R.id.problemsSolved));
choice1 = ((Button) findViewById(R.id.choice1));
choice2 = ((Button) findViewById(R.id.choice2));
//Initializing a Random
r = new Random();
//Set the first question
setRandomProblem();
//Starting the timer
myCountDownTimer = new MyCountDownTimer(timerTV, 5000, 1000);
myCountDownTimer.start();
// Button Listeners
choice1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
choice2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
}
public void checkResponse(Button v) {
//Convert the response and correctAnswer to String in order to compare values
response = v.getText().toString();
sumStr = Integer.toString(correctAnswer);
//If the user clicks the correct answer, increment score
if ((response.equals(sumStr))) {
score++;
scoreTV.setText(score+"");
}
//Increment the total amount of problems solved
problemsSolved++;
problemsSolvedTV.setText(problemsSolved+"");
//Keep track of the score within the timer
myCountDownTimer.recordScore(score,problemsSolved);
}
private void setRandomProblem() {
//Assigning random values to ints
rand1 = r.nextInt(5 - 1) + 1;
rand2 = r.nextInt(5 - 1) + 1;
randDecider = r.nextInt(2) + 1;
//The correctAnswer of the randoms
correctAnswer = rand1 + rand2;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
//If the random deciding number is 1, set answer on choice1
if (randDecider == 1) {
choice1.setText(correctAnswer + "");
choice2.setText(correctAnswer + falseAnswer + "");
}
//If the random deciding number is 2, set answer on choice2
else {
choice1.setText(correctAnswer + falseAnswer + "");
choice2.setText(correctAnswer + "");
}
}
#Override
public void onStop(){
super.onStop();
//Stop the timer
myCountDownTimer.cancel();
}
}
This is the GameOverActivity
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* Created by kamalu on 12/25/2017.
*/
public class GameOverActivity extends AppCompatActivity {
TextView scoreTV, problemsSolvedTV, percentageTV;
int score, problemsSolved, percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
//Initializing TextViews
scoreTV = ((TextView)findViewById(R.id.score));
problemsSolvedTV = ((TextView)findViewById(R.id.problemsSolved));
percentageTV = ((TextView)findViewById(R.id.percentage));
//Opening Bundle and assigning values
Bundle extras = getIntent().getExtras();
score = extras.getInt("score");
problemsSolved = extras.getInt("problemsSolved");
//calculating the accuracy
percentage = (score/problemsSolved)*100;
//Displaying the score
percentageTV.setText(percentage+"");
scoreTV.setText(score+"");
problemsSolvedTV.setText(problemsSolved+"");
}
//Start the game over
public void retry(View v){
Intent retryIntent = new Intent(GameOverActivity.this, FastMathActivity.class);
startActivity(retryIntent);
}
public void onBackPressed()
{
}
}
This is the Timer. I believe it to be important to note that the onFinish() method in this class starts the GameOverActivity.
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.TextView;
public class MyCountDownTimer extends CountDownTimer {
TextView textCounter;
int score,problemsSolved;
public MyCountDownTimer(TextView textCounter, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
#Override
public void onTick (long millisUntilFinished){
textCounter.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish () {
Intent gameOverIntent = new Intent(textCounter.getContext(), GameOverActivity.class);
gameOverIntent.putExtra("score", score);
gameOverIntent.putExtra("problemsSolved", problemsSolved);
textCounter.getContext().startActivity(gameOverIntent);
}
//Keep track of the scores
public void recordScore(int score,int problemsSolved){
this.problemsSolved = problemsSolved;
this.score = score;
}
}
You should check:
//calculating the accuracy
percentage = (score/problemsSolved)*100;
if problemsSolved = 0, your app will crash with exeptions: java.lang.ArithmeticException
You can refer:
if (problemSolved != 0){
//calculating the accuracy
percentage = (score/problemsSolved)*100;
} else {
// handle with problemSolved = 0;
}
I hope it can help your problem!

Android: Stopwatch (Timer) in background Service

I want to make an android application that have punch in and punch out functionality. Scenario is when the user entered in an application it enters its task and press punch in button, When punch in button is press current date and time is saved in a local database and timer is running on background even i close an application but issue is it cannot run in background when i close an application and starts again timer starts from beginning.
How to figure out that my service is running and get that data?
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.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button startButton;
private Button pauseButton;
private TextView timerValue;
Intent intent;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
});
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
updateUI(intent);
}
};
private void updateUI(Intent intent) {
int time = intent.getIntExtra("time", 0);
Log.d("Hello", "Time " + time);
int mins = time / 60;
int secs = time % 60;
timerValue.setText("" + mins + ":" + String.format("%02d", secs));
}
#Override
protected void onStop() {
super.onStop();
intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(MyService.BROADCAST_ACTION));
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service
{
private Intent intent;
public static final String BROADCAST_ACTION = "com.example.wajid.service";
private Handler handler = new Handler();
private long initial_time;
long timeInMilliseconds = 0L;
#Override
public void onCreate() {
super.onCreate();
initial_time = SystemClock.uptimeMillis();
intent = new Intent(BROADCAST_ACTION);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 1 seconds
}
};
private void DisplayLoggingInfo() {
timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;
int timer = (int) timeInMilliseconds / 1000;
intent.putExtra("time", timer);
sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Why do you want to run a timer? Instead, simply save the check-in time in shared preferences. On check-out, the two can be compared and the relevant time calculated.
If you are worried that the user might try to manipulate the local device clock, then instead of getting the local time, you can use network time.

Android TimePickerDialog selected time not passing through to the actual Countdown Timer

I've been working on getting a timepicker dialog to set my countdown timer. I have tried many ways with many different results... none of them worked right. I decided to experiment with some basic code which I will put below.
I cannot get the selected time (I called it selectedStartTime in the code below) to pass through into the actual countdown timer as startTime. I can only get the timer to work right when I use the preset startTime = 10000 (or any number). I don't want the startTime to be a set number. I need it to come from the OnTimeSetListener in the time picker box.
I will be forever grateful to anyone that can show me how to change the code so that the selected time in the dialog box is actually used in the timer.
Complete XML code for: activity_simple_timer_test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start" />
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="10dip">
<TableRow>
<TextView
android:id="#+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:text="Time: " />
<TextView
android:id="#+id/timeElapsed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:text="Time elapsed: " />
</TableRow>
</TableLayout>
</LinearLayout>
Complete Java code for: SimpleTimerTest.java
package com.YOURPACKAGE INFO;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class SimpleTimerTest extends Activity implements OnClickListener {
private MalibuCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private Button startB;
private TextView text;
private TextView timeElapsedView;
int selectedStartTime;
// don't want to use a predefined startTime
private final long startTime = 10000;
private final long interval = 1000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_timer_test);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
timeElapsedView = (TextView) this.findViewById(R.id.timeElapsed);
countDownTimer = new MalibuCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime));
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
selectedStartTime = ((hourOfDay*3600000)+(minute*60000));
// I can't get this variable to pass through into the countdown timer
}
};
#Override
public void onClick(View v) {
TimePickerDialog d = new TimePickerDialog(SimpleTimerTest.this, onTimeSetListener, 1, 0, true);
d.setTitle("Pick Sleep Duration hour:min");
d.setCancelable(true);
d.setButton(DialogInterface.BUTTON_POSITIVE, "Start", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("Stop");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Timer was already running");
}
}
}
});
d.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Restart");
}
}
});
d.show();
}
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
Toast toast = Toast.makeText(getApplicationContext(), "finished", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
}
I'm not completely sure what you're trying to achieve, just create instance of your MalibuCountDownTimer in method onTimeSet, this method will be called only when user selected time.

Timer in Background

I'm developing an Android Application to a college work. In this work I want to create a background service with a timer and when I close the application, timer still running. When I open the app, I can see the time since I've started service.
Well, my problem is that when I close the app, the background timer stops and not increments more.
Can you help me please?
Thanks a lot
My launcher class
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button startButton;
private Button pauseButton;
private TextView timerValue;
Intent intent;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
intent = new Intent(MainActivity.this, CounterService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
});
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
int time = intent.getIntExtra("time", 0);
Log.d("Hello", "Time " + time);
int mins = time / 60;
int secs = time % 60;
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs));
}
}
and here, the service class
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
public class CounterService extends Service {
private Intent intent;
public static final String BROADCAST_ACTION = "com.javacodegeeks.android.androidtimerexample.MainActivity";
private Handler handler = new Handler();
private long initial_time;
long timeInMilliseconds = 0L;
#Override
public void onCreate() {
super.onCreate();
initial_time = SystemClock.uptimeMillis();
intent = new Intent(BROADCAST_ACTION);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 1 seconds
}
};
private void DisplayLoggingInfo() {
timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;
int timer = (int) timeInMilliseconds / 1000;
intent.putExtra("time", timer);
sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
you need to start your service in the onStop() method in your activity like this:
#Override
protected void onStop() {
super.onStop();
//write your code here to start your service
}
Kindly go through the link hope it will be helpful if you want to run timer in background Timer in background
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/et_hours"
android:hint="Hours"
android:inputType="time"
android:layout_marginRight="5dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_timer"
android:layout_above="#+id/btn_cancel"
android:text="Start Timer"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/btn_cancel"
android:text="cancel timer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_timer"
android:layout_centerInParent="true"
android:textSize="25dp"
android:textColor="#000000"
android:text="00:00:00"/>
</RelativeLayout>
MainActivity.java
package playstore.com.a02backgroundtimer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start, btn_cancel;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
}
}
private void listener() {
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
if (et_hours.getText().toString().length() > 0) {
int int_hours = Integer.valueOf(et_hours.getText().toString());
if (int_hours<=24) {
et_hours.setEnabled(false);
btn_start.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", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
}else {
Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
}
/*
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
} else {
Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
stopService(intent);
mEditor.clear().commit();
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Timer_Service.java
package playstore.com.a02backgroundtimer;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class Timer_Service extends Service {
public static String str_receiver = "com.countdowntimerservice.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 intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
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);
intent = 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();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.HOURS.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours > 0) {
String str_testing = diffHours2 + ":" + 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) {
intent.putExtra("time", str_time);
sendBroadcast(intent);
}
}
Once the app starts you need to mention the hours you want timer for ... Then also after killing the app when you restarts the app it will show the start time of the timer ... Now you customize you application a per your requirement .

Passing variables between service & activity and vice-versa

I've got a service which is passed a bundle of variables (song, artist album etc.), and includes a MediaPlayer, and a bunch of methods for that MediaPlayer (play next, previous etc.).
I've also got an activity, which displays the UI to the user, including next/previous buttons, a Seekbar, and the display of the artist/album/song.
What I'd like to know is how to get the UI activity to make changes to the service, and the service to update the activity depending on which song is selected..
For example: An artist/album/song combination is sent to the service. The service tells a MediaPlayer to begin playing that song. The song title/album/artist is displayed in the activity, and the user can press play/pause etc in the UI. Upon clicking, the service will act accordingly.
I don't know how to get all these things happening, and I'm getting caught up with broadcasts and intents and statics.. I would really appreciate some clear guidance, and a good example of how this could be done.
Thank you for your patience & help.
Please find the code below:
MusicService.java:
package awesome.music.player;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
public class MusicService extends Service implements OnCompletionListener,
OnSeekCompleteListener {
Intent intent;
MediaPlayer mediaPlayer = new MediaPlayer();
String isComplete;
String serviceStatus;
String sntSeekPos;
String artist;
String selection;
String album;
String numSongs;
int albumId;
String currentSongPath;
String[] selectionArgs;
Uri currentSongUri;
int songEnded;
int currentSongIndex;
int totalSongDuration;
int intSeekPos;
int mediaPosition;
int mediaMax;
ArrayList<String> pathList;
ArrayList<String> artistList;
ArrayList<String> albumList;
ArrayList<String> titleList;
ArrayList<String> idList;
ArrayList<String> durationList;
private final Handler handler = new Handler();
public final String BROADCAST_ACTION = "awesome.music.player.seekprogress";
public final String BROADCAST_OTHER = "awesome.music.player.displaysong";
Intent seekIntent;
Intent displayIntent;
Utilities utils;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.intent = intent;
Bundle extras = intent.getExtras();
artist = extras.getString("artist");
selection = extras.getString("selection");
selectionArgs = extras.getStringArray("selectionArgs");
album = extras.getString("album");
albumId = extras.getInt("albumId");
numSongs = extras.getString("numSongs");
currentSongIndex = extras.getInt("currentSongIndex");
currentSongPath = extras.getString("currentSongPath");
totalSongDuration = extras.getInt("totalSongDuration");
pathList = extras.getStringArrayList("pathList");
artistList = extras.getStringArrayList("artistList");
albumList = extras.getStringArrayList("albumList");
titleList = extras.getStringArrayList("titleList");
idList = extras.getStringArrayList("idList");
durationList = extras.getStringArrayList("durationList");
prepareSong(currentSongPath);
playSong();
displaySong();
utils = new Utilities();
seekIntent = new Intent(BROADCAST_ACTION);
displayIntent = new Intent(BROADCAST_ACTION);
setupHandler();
return START_STICKY;
}
/*
* #Override public void onCreate() { super.onCreate();
*
* utils = new Utilities();
*
* seekIntent = new Intent(BROADCAST_ACTION);
*
* setupHandler();
*
* prepareSong(currentSongPath); playSong(); }
*/
public void prepareSong(String currentSongPath) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(currentSongPath);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void playSong() {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCompletion(MediaPlayer mediaPlayer) {
playNext();
}
#Override
public void onStart(Intent intent, int startId) {
registerReceiver(broadcastReceiver, new IntentFilter(
MusicPlayer.BROADCAST_SEEKBAR));
super.onCreate();
prepareSong(currentSongPath);
playSong();
}
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000);
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
LogMediaPosition();
handler.postDelayed(this, 1000);
}
};
private void LogMediaPosition() {
if (mediaPlayer.isPlaying()) {
mediaPosition = mediaPlayer.getCurrentPosition();
MusicPlayer.currentDurationLabel.setText(""
+ utils.milliSecondsToTimer(mediaPosition));
mediaMax = mediaPlayer.getDuration();
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
private void displaySong() {
utils = new Utilities();
String title = titleList.get(currentSongIndex);
String artist = artistList.get(currentSongIndex);
String album = albumList.get(currentSongIndex);
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri currentSongUri = ContentUris.withAppendedId(sArtworkUri, albumId);
String totalDuration = utils.milliSecondsToTimer(totalSongDuration);
mediaPosition = mediaPlayer.getCurrentPosition();
MusicPlayer.currentDurationLabel.setText(""
+ utils.milliSecondsToTimer(mediaPosition));
displayIntent.putExtra("title", title);
displayIntent.putExtra("artist", artist);
displayIntent.putExtra("album", album);
displayIntent.putExtra("totalDuration", totalDuration);
displayIntent.putExtra("currentSongUri", currentSongUri);
sendBroadcast(displayIntent);
}
// receive seekbar position
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mediaPlayer.seekTo(seekPos);
setupHandler();
}
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
handler.removeCallbacks(sendUpdatesToUI);
// Unregister seek receiver
unregisterReceiver(broadcastReceiver);
}
public void onSeekComplete(MediaPlayer mediaPlayer) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
public void playNext() {
if (mediaPlayer.isPlaying()) {
if (currentSongIndex < (pathList.size() - 1)) {
currentSongIndex = currentSongIndex + 1;
currentSongPath = pathList.get(currentSongIndex);
prepareSong(currentSongPath);
playSong();
} else {
currentSongIndex = 0;
currentSongPath = pathList.get(currentSongIndex);
prepareSong(currentSongPath);
playSong();
}
} else {
if (currentSongIndex < (pathList.size() - 1)) {
currentSongIndex = currentSongIndex + 1;
currentSongPath = pathList.get(currentSongIndex);
prepareSong(currentSongPath);
} else {
currentSongIndex = 0;
prepareSong(currentSongPath);
}
}
displaySong();
}
void playPrevious() {
if (mediaPlayer.isPlaying()) {
if (currentSongIndex > 0) {
currentSongIndex = currentSongIndex - 1;
currentSongPath = pathList.get(currentSongIndex);
prepareSong(currentSongPath);
playSong();
} else {
currentSongIndex = pathList.size() - 1;
currentSongPath = pathList.get(currentSongIndex);
prepareSong(currentSongPath);
playSong();
}
} else {
if (currentSongIndex > 0) {
currentSongIndex = currentSongIndex - 1;
currentSongPath = pathList.get(Playlist.currentSongIndex);
prepareSong(currentSongPath);
} else {
currentSongIndex = pathList.size() - 1;
currentSongPath = pathList.get(currentSongIndex);
prepareSong(currentSongPath);
}
}
displaySong();
}
}
MusicPlayer.java:
package awesome.music.player;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MusicPlayer extends Activity implements OnSeekBarChangeListener {
public ImageButton play;
public ImageButton next;
public ImageButton previous;
public static ImageView albumArt;
static TextView songArtistAlbumLabel;
static TextView songTitleLabel;
static TextView currentDurationLabel;
static TextView totalDurationLabel;
static String serviceStatus;
private SeekBar seekBar;
private int seekMax;
boolean mBroadcastIsRegistered;
public static Utilities utils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playing);
play = (ImageButton) findViewById(R.id.playButton);
next = (ImageButton) findViewById(R.id.nextButton);
previous = (ImageButton) findViewById(R.id.previousButton);
albumArt = (ImageView) findViewById(R.id.imageView1);
songArtistAlbumLabel = (TextView) findViewById(R.id.songArtistAlbumLabel);
songTitleLabel = (TextView) findViewById(R.id.songTitleLabel);
totalDurationLabel = (TextView) findViewById(R.id.totalDurationLabel);
songArtistAlbumLabel = (TextView) findViewById(R.id.songArtistAlbumLabel);
play.setOnClickListener(playListener);
next.setOnClickListener(nextListener);
previous.setOnClickListener(previousListener);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
intent = new Intent(BROADCAST_SEEKBAR);
if (mBroadcastIsRegistered != true) {
registerReceiver(broadcastReceiver, new IntentFilter(
MusicService.BROADCAST_ACTION));
;
mBroadcastIsRegistered = true;
}
}
private OnClickListener playListener = new OnClickListener() {
public void onClick(View v) {
MusicService.playSong();
}
};
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
MusicService.playNext();
}
};
private OnClickListener previousListener = new OnClickListener() {
public void onClick(View v) {
MusicService.playPrevious();
}
};
public static final String BROADCAST_SEEKBAR = "awesome.music.player.sendseekbar";
Intent intent;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent serviceIntent) {
updateUI(serviceIntent);
}
};
private void updateUI(Intent serviceIntent) {
String counter = serviceIntent.getStringExtra("counter");
String mediamax = serviceIntent.getStringExtra("mediamax");
String strSongEnded = serviceIntent.getStringExtra("song_ended");
int seekProgress = Integer.parseInt(counter);
seekMax = Integer.parseInt(mediamax);
Integer.parseInt(strSongEnded);
seekBar.setMax(seekMax);
seekBar.setProgress(seekProgress);
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
int seekPos = seekBar.getProgress();
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
playing.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<SeekBar
android:id="#+id/seekBar"
android:layout_width="296dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_x="10dp"
android:layout_y="446dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:progressDrawable="#drawable/seekbar_progress"
android:thumb="#drawable/seek_handler" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="37dp"
android:layout_height="37dp"
android:layout_x="6dp"
android:layout_y="397dp"
android:src="#drawable/ic_tab_albums_white" />
<TextView
android:id="#+id/songTitleLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="55dp"
android:layout_y="395dp"
android:text="Song Label"
android:textSize="20sp" />
<TextView
android:id="#+id/songArtistAlbumLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="55dp"
android:layout_y="417dp"
android:text="Artist - Album Label"
android:textSize="15sp" />
<TextView
android:id="#+id/currentDurationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="10dp"
android:layout_y="481dp"
android:text="0:00" />
<TextView
android:id="#+id/totalDurationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="281dp"
android:layout_y="477dp"
android:text="3:30" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="41dp"
android:layout_y="312dp"
android:gravity="center_horizontal" >
<ImageButton
android:id="#+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="132dp"
android:layout_y="308dp"
android:src="#drawable/ic_previous" />
<ImageButton
android:id="#+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50sp"
android:layout_marginRight="50sp"
android:src="#drawable/ic_pause" />
<ImageButton
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_next" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="287dp"
android:layout_height="272dp"
android:layout_x="16dp"
android:layout_y="13dp"
android:background="#drawable/dummy_album_art"
android:scaleType="fitXY" />
</AbsoluteLayout>
as general
there a three main ways to commnicate with Services
1-Binder (in bind service)
2-Messenger
3-AIDL
On Android, one process cannot normally access the memory of another process. So to talk,
they need to decompose their objects into primitives that the operating system can
understand, and marshall the objects across that boundary for you. The code to do that
marshalling is tedious to write, so Android handles it for you with AIDL.
Using AIDL is necessary only if
1- you allow clients from different applications to access your service for IPC
2- you want to handle multithreading in your service. If you do not need to perform concurrent IPC
across different applications,
Using Binder
you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need
Using Messenger
to handle multithreading, implement your interface using a Messenger.
http://developer.android.com/guide/developing/tools/aidl.html
http://java.dzone.com/articles/android-aidl-and-remote-client
other then this can use
1- Broadcasting intent from service
2 -
You have to make a playback service that starts when the application is created you can start our service from a class that extends Application.
You can use aidl to communicate a service with activity.As activity is already startedit cant get killed when the activity stops.
You can use Mediastore content resolver to get data about tracks there artists albums etc..
MediaStore.Audio.Media.* Columns you want it provide all data and also path of the song
4.I am also currently in process of building player.......but all this is working as i use it

Categories

Resources