How to stop Music In background while using Music Services - java

When i play the app and then close after sometimes the apps Music again starts in background
Any help will be appreciated
Thanks
I have an activity class having Code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygame);
final Handler mHandler = new Handler();
Intent svc=new Intent(this, MusicService.class);
startService(svc);
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 500; // delay for 1 sec.
int period = 6000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);}
}, delay, period);}
public void onClick(View v) {
finish();
android.os.Process.killProcess(android.os.Process.myPid());
Intent srv=new Intent(SliderActivity.this, MusicService.class);
stopService(srv); }

Try Removing Callbacks of your handler in the onStop Method in your activity class :
#Override
protected void onStop() {
super.onStop();
mHandler.removeCallbacksAndMessages(null);
timer = null;
mHandler= null;
}
Hope it helps.

Related

How to show Toast Counting down before transfer to another activity-Android Studio

i have made this code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, EnterData.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 7000);
how i can show the count down by toast? for example i made this counting 7 seconds before go to another page i need toast dialog show counting 7.6.5.4,etc then transfer
Thanks
Use a second handler which will do the count down for you.
For this create a static variable countdown as follows in MainActivity.java
private static int countdown = 7;
This can be used in the new handler to show the toast for countdown.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(context,MainActivity.countdown+"",Toast.LENGTH_LONG).show();
MainActivity.countdown--;
}
}, 1000);
Also keep your handler, which will create the intent and start it after 7 seconds.
You should use a CountDownTimer
private CountDownTimer countDownTimer = new CountDownTimer(7000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Toast.makeText(context, String.valueOf(millisUntilFinished / 1000), Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
final Intent mainIntent = new Intent(MainActivity.this, EnterData.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
};
Somewhere you feel its appropriate you can start the count like this:
countDownTimer.start();
you can create timerClass as bellow
class SayCount extends TimerTask {
public void run() {
if(i == 0 ) {
timer.stop();
}
System.out.println(String.valueOF(i));
i--;
}
}
// And From your main() method or any other method
int i = 7;
Timer timer = new Timer();
timer.schedule(new SayCount(), 0, 1000);
or you can use Runnable() class as the answer above

Execute function after 5 seconds in Android

I am new in android development and now my launcher activity show only 5 seconds and after that I want to check the user is logged in or not function and perform the actions.
here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exactPreferences = getSharedPreferences("ExactPreference",MODE_PRIVATE);
setContentView(R.layout.activity_landing_page);
session = exactPreferences.getString(Model.getSingleton().SHARED_SESSION_ID,null);
Log.i("Session Id",session);
displayData(); // I want to perform this function after 5 seconds.
}
private void displayData() {
if(session.equals("")){
Intent loginIntent = new Intent(LandingPage.this,
LoginActivity.class);
startActivity(loginIntent);
Log.i("User Logged In", "False");
}
else
{
Intent objIntent = new Intent(LandingPage.this,
IndexPageActivity.class);
startActivity(objIntent);
Log.i("User Logged In", "True");
}
}
You can use the Handler to add some delay.Call the method displayData() as below so that it will be executed after 5 seconds.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
displayData();
}
}, 5000);
Note : Do not use the threads like Thread.sleep(5000); because it will block your UI and and makes it irresponsive.
Assign millisDelayTime variable with the milliseconds you desire to cause a delay. mActivity is an object of Activity for providing Application Context. In your case millisDelayTime should be initialized with 5000
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//your code here
}
}, millisDelayTime);
}
});
Use a CountDownTimer
// There's a TextView txtCount in Main Activity
final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
txtCount.setText("" + (int) (millisUntilFinished * .001f));
}
#Override
public final void onFinish()
{
txtCount.setText("GO!");
finish();
// Time's up - Start the Login Activity
final Intent tnt =
new Intent(getApplicationContext(), LoginActivity.class);
startActivity(tnt);
}
}.start();
Since, Handler is now deprecated so use this code :
new Handler(Looper.myLooper()).postDelayed(new Runnable() {
#Override
public void run() {
//do what you want
}
}, 5000);
Try this, code create CountDownTimer with one tick
timer = new CountDownTimer(5000, 5000)
{
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
displayData();
}
};
timer.start();
long delay = 1000;
long period = 50000;
Timer task = new Timer();
task.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
getDriver(sessionManager.getKEY(), ride_id);
}
}, delay, period);
For kotlin way
Handler().postDelayed({
//do something
}, 5000)
When possible, try to avoid using postDelayed. It is a bad practice, since it can lose the reference to the objects that you want to draw on your screen and cause a NPE. Use a Handler instead. First of all, create a global variable Handler in which you will have to "handle" the logic for your code. Do so by using the function handleMessage.
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
if(msg.what == 1){
// your code here
}
}
};
Then, wherever you want to execute it, just call the function:
// 1 is the ID of your process
handler.sendEmptyMessageDelayed(1, 5000);
Please remember that in the onDestroyView method (in a Fragment) or the onDestroy (in an Activity) you will have to call
handler.removeMessages(1)
The best option to achieve this is using a Handler:
int TIME = 5000; //5000 ms (5 Seconds)
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
function(); //call function!
}
}, TIME);

Terminating timer in android

I am a begineer in android app development, i have stoptimertask function in my mainactivity, and a button stop in another activity. What i want to do is when i press this stop button from my 2nd activity(which is maps.class), i want the stoptimertask to stop i.e. stop the tasks. However the app crashes.
Here is my code of mainactivity.java
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
count = 0;
}
MainActivity.this.finish();
}
}
Here is the maps.java(2nd activity)
public class maps extends FragmentActivity implements LocationListener {
MainActivity call=new MainActivity();
GoogleMap googleMap;
Button stop;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.maps);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View aView)
{
Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
startActivityForResult(toAnotherActivity, 0);
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
maps.this.finish();
call.stoptimertask(aView);
}
});
here is the logcat
FATAL EXCEPTION: main
Process: com.example.textmessage, PID: 19869
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.example.textmessage.MainActivity.stoptimertask(MainActivity.java:167)
at com.example.textmessage.maps$1.onClick(maps.java:49)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Best use for this kind of scenario is Singleton pattern.
MainActivity.java
public class MainActivity extends FragmentActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeTools();
// Find reference of "sendBtn" with "findViewById" or other stuff
sendBtn.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startTimer();
}
});
// Rest of your code
}
private void initializeTools()
{
// Give context to Timers instance
Timers.getInstance().giveContext(this);
}
private void startTimer()
{
// Starts the timer when you click on "sendBtn"
Timers.getInstance().startTimers();
}
}
Timers.java
public class Timers
{
private final ScheduledExecutorService scheduledExecutorService;
private final Runnable myTask;
private ScheduledFuture<?> futureTask;
private int count = 0;
private Context _context;
private static volatile Timers _timers;
private Timers()
{
super();
// Your "futureTask manager"
scheduledExecutorService = Executors.newScheduledThreadPool(5);
// Good use is to instanciate task since it won't change on runtime
myTask = new Runnable()
{
#Override
public void run()
{
// Your code to run after the delay has expired
Toast.makeText(_context, "your message has been sent, the message(s) sent are:-" + count++, Toast.LENGTH_LONG).show();
// Same as the whole example, you should use the Singleton pattern to handle communications thanks to the Singleton class "Communicator"
Communicator.getInstance().sendSMSMessage();
}
};
}
// Allow only one instance of the class running. Anyone can get reference of the class with the static function Timers.getInstance();
public static Timers getInstance()
{
if (Timers._timers == null)
{
synchronized (Timers.class)
{
if (Timers._timers == null)
{
Timers._timers = new Timers();
}
}
}
return Timers._timers;
}
// For Toasts and other useful stuff
public void giveContext(Context context)
{
this._context = context;
}
// Stop the timer
public void stopTimer()
{
if (futureTask != null)
{
futureTask.cancel(true);
}
}
// Starts the task to happen in 10 seconds
public void startTimers()
{
futureTask = scheduledExecutorService.schedule(myTask, 10, TimeUnit.SECONDS);
}
}
And inside any class of your application, use Timers.getInstance().stopTimer(); to stop the timer and Timers.getInstance().startTimer(); to start it again.
Did you try?
mTimer = new Runnable() {
#Override
public void run() {
**return;**

Calling from wrong thread exception

I am trying to develop an application, that uses threads to implement slideshow. I am retrieving the image path from SQLite and displaying them on the ImageView. The problem, where I got struck is, I got confused and so I am unable to understand, from which thread I am calling images() method, where I am actually implementing the slideshow.
I got the Logcat as follows -
09-03 13:47:00.248: E/AndroidRuntime(10642): FATAL EXCEPTION: Thread-151
09-03 13:47:00.248: E/AndroidRuntime(10642): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
09-03 13:47:00.248: E/AndroidRuntime(10642): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
09-03 13:47:00.248: E/AndroidRuntime(10642): at com.example.fromstart.MainActivity.images(MainActivity.java:90)
09-03 13:47:00.248: E/AndroidRuntime(10642): at com.example.fromstart.MainActivity$2.run(MainActivity.java:59)
09-03 13:47:00.248: E/AndroidRuntime(10642): at java.lang.Thread.run(Thread.java:841)
MainActivity.java:
public class MainActivity extends Activity
{
ImageView jpgView;
TextView tv;
//adapter mDbAdapter;
adapter info = new adapter(this);
String path;
Handler smHandler = new Handler()
{
public void handleMessage(Message msg)
{
TextView myTextView =
(TextView)findViewById(R.id.textView1);
myTextView.setText("Button Pressed");
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jpgView = (ImageView)findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
final Runnable runnable = new Runnable()
{
public void run()
{
images();
}
};
int delay = 1000; // delay for 1 sec.
int period = 15000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
smHandler.post(runnable);
}
}, delay, period);
Thread mythread = new Thread(runnable);
mythread.start();
return true;
}
public void handleMessage(Message msg)
{
String string = "sample";
TextView myTextView = (TextView)findViewById(R.id.textView1);
myTextView.setText(string);
}
public void images()
{
try
{
for(int i=0;i<=20;i++)
{
path = info.getpath();
Bitmap bitmap = BitmapFactory.decodeFile(path);
jpgView.setImageBitmap(bitmap);
}
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
}
I am a newbie to android, just now started working on Threads. If you find any mistakes in my code, please point out those and please suggest me, the right way to deal with this problem.
Thanks in advance.
UPDATE:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler mHandler = new Handler();
// Create runnable for posting
runOnUiThread(new Runnable()
{
public void run()
{
images();
}
});
int delay = 1000; // delay for 1 sec.
int period = 15000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
images();
}
}, delay, period);
}
public void images()
{
try
{
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG).show();
path = info.getpath();
Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_LONG).show();
Bitmap bitmap = BitmapFactory.decodeFile(path);
Toast.makeText(getApplicationContext(), "3", Toast.LENGTH_LONG).show();
jpgView.setImageBitmap(bitmap);
Toast.makeText(getApplicationContext(), "4", Toast.LENGTH_LONG).show();
}
catch(NullPointerException er)
{
String ht=er.toString();
Toast.makeText(getApplicationContext(), ht, Toast.LENGTH_LONG).show();
}
}
}
You cannot update/access ui from from a thread.
You have this
public void run()
{
images();
}
And in images you have
jpgView.setImageBitmap(bitmap);
You need to use runOnUiThread for updating ui.
runOnUiThread(new Runnable() {
#Override
public void run() {
// do something
}
});
TimerTask also runs on a different thread. So you have use a Handler for updati ui.
You can use a handler.
Edit:
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something. call images()
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
If you still wish to use a timer task use runOnUiThread
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
runOnUiThread(new Runnable() {
#Override
public void run() {
images();
}
});
}
}, delay, period);
To update UI from any other Thread you must use
runOnUiThread(<Runnable>);
which will update your UI.
Example:
runOnUiThread(
new Runnable()
{
// do something on UI thread Update UI
});

Use timertask to update clock each X seconds?

I'm trying to update my digital clock using timertask. I have created a function called updateClock() which sets the hours and minutes to the current time but I haven't been able to get it to run periodically. From what I've read in other answers one of the best options is to use timertask however I haven't been able to make any example I found online work inside an Android activity.
This is what I've written so far:
public class MainActivity extends Activity {
TextView hours;
TextView minutes;
Calendar c;
int cur_hours;
int cur_minutes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clock_home);
hours = (TextView) findViewById(R.id.hours);
minutes = (TextView) findViewById(R.id.minutes);
updateClock();
}
public void updateClock() {
c = Calendar.getInstance();
hours.setText("" + c.get(Calendar.HOUR));
minutes.setText("" + c.get(Calendar.MINUTE));
}
public static void init() throws Exception {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateClock(); // ERROR
}
}, 0, 1 * 5000);
}
}
How can I make it work?
Use runOnUiThread for updating Ui from Timer Thread
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
MainActivity.this.runOnUiThread (new Runnable() {
public void run() {
updateClock(); // call UI update method here
}
}));
}
}, 0, 1 * 5000);
}
if you just need updates every minute, you can also listen to the ACTION_TIME_TICK broadcast event.
private boolean timeReceiverAttached;
private final BroadcastReceiver timeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateClock();
}
};
private Handler handler = new Handler();
#Override
protected void onResume() {
super.onResume();
updateClock();
if (!timeReceiverAttached) {
timeReceiverAttached = true;
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(timeReceiver, filter, null, handler);
}
}
#Override
protected void onPause() {
super.onPause();
if (timeReceiverAttached) {
unregisterReceiver(timeReceiver);
timeReceiverAttached = false;
}
}
OR, periodically post the Runnable to the Handler of UI thread. Also, pause and resume tasks to save battery.
public class MyActivity extends Activity {
private final Handler mHandler = new Handler();
private final Timer mTimer = new Timer();
#Override
protected void onResume() {
super.onResume();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
//---update UI---
}
});
}
},0,5000);
}
#Override
protected void onPause() {
super.onPause();
mTimer.cancel();
}
}

Categories

Resources