Android: How to change TextView periodically - android

I'm recently working on a ShoutCast radio project. By using streamscrapper library I'm able to get the current song name and the current artist. Here is the problem. Once I open the app, it gets the song name and the artist name, however since then it does not update it. I tried to do it with timer but couldn't figure out.
And here is the method which I get the current song id:
private void initializeMediaPlayer() {
player = new AACPlayer();
scraper = new ShoutCastScraper();
try {
streams = scraper.scrape(new URI("http://sunucu2.radyolarburada.com:5000/"));
String str = "asd";
for (Stream stream: streams) {
str = stream.getCurrentSong();
currPlayView.setText("Now Playing: " + str);
}
} catch (ScrapeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Maybe something like a runnable:
private Handler handler = new Handler();
handler.postAtTime(timeTask, SystemClock.uptimeMillis() + 500);
private Runnable timeTask = new Runnable() {
public void run() {
//do stuff here
//do it again soon
handler.postAtTime(timeTask, SystemClock.uptimeMillis() + 500);
}
};
Before you leave make sure to stop the tasks:
handler.removeCallbacksAndMessages(null);

use a Handler to update it ,
Handler handler=new Handler();
int FREQ=5000; // the update frequency
handler.postDelayed(new Runnable()
{
public void run()
{
try
{
String currStr; // get your next song name
currPlayView.setText(currStr);
}
finally
{
handler.postDelayed(this, FREQ);
}
}
}, FREQ);

Related

Android Timed Async Task

Hi currently i have the following code which utilizes Asycn Task and Timer.
My async task is basically trying to send a HTTP GET method from a URL where the response from the server could varies depending on connection and load.
What i would like to do is to have a timed async task. Where, it will schedule an AsyncTask every X second BUT if there is currently an Async Task in progress i would have to kill it first. Then start a new one.
Here is the code that i have at the moment:
private static boolean running = false;
Timer myTimer;
protected void onCreate(Bundle savedInstanceState) {
/* REST OF CODE OMITTED */
MyTimerTask myTask = new MyTimerTask();
myTimer = new Timer();
myTimer.schedule(myTask, 0, 10000);
}
/* REST OF CODE OMITTED */
private class MyTimerTask extends TimerTask {
public void run() {
if(!running){
Log.i("TAG", "NEW TIMER STARTED.");
RetrieveChatMessage task = new RetrieveChatMessage();
task.execute();
running = true;
}else{
running = false;
}
}
}
private class RetrieveChatMessage extends AsyncTask<String, Void, ArrayList<Chat>> {
#Override
protected ArrayList<Chat> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<Chat> cList = null;
String jResult = null;
Log.i("TAG", "RETRIEVING CHAT MESSAGE");
try {
jResult = ((new HttpRetriever())).getChatList(mAccount.email, mAccount.passwd);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(jResult != null){
Log.i("TAG", "JSON DATA: " + jResult);
cList = (new ChatHandlers()).getChatList(jResult);
}else{
cList = null;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("TAG", "JSON Exception " + e.toString());
}
return cList;
}
#Override
protected void onPostExecute(final ArrayList<Chat> result) {
Log.i("TAG", "ON POST EXECUTE");
if(result != null){
// Do something here
}
}
}
To be honest the code above works with slight issues:
1. It seems to execute the Async randomly, instead of every 10 seconds.
2. When i go to another activity, somewhat it prevents other Async task from doing its job (Which is also trying to retrieve JSON response from server).
I am not too worried about the later problem (and that is not the question i am asking). I just would like to know how to have a proper timed Async Task. Can anyone point me to a direction.
Thank you.
EDIT #1:
after reading #thepoosh comment's i tried the following (i put it in onCreate):
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// Parsing RSS feed:
// myFeedParser.doSomething();
Log.w("THUMBQOO", "NEW TASK STARTED");
retrieveChat();
}
}, 0, 15, TimeUnit.SECONDS);
Result: i have a consistent execution of Task. However, it seems that retrieveChat(); is never be called after the first execution.
Actually AsyncTask is not used for long operations .Check Here
You should use a Thread that uses a interface to notify UI or you can simply use a Handler which is the most Preffered way in android. Simply you can do a task repeatedly for every 10 seconds by
handler.postDelayed(new Runnable() {
#Override
public void run() {
// do work
handler.postDelayed(10000);
}
}, 10000);
Declare a Handler object to maintain future task executor...
private Handler mTimerHandler = new Handler();
Write a thread which will execute your future task...
private Runnable mTimerExecutor = new Runnable() {
#Override
public void run() {
//write your code what you want to do after the specified time elapsed
if(!running){
RetrieveChatMessage task = new RetrieveChatMessage();
task.execute();
running = true;
}else{
running = false;
}
}
};
Call your future tast executor with time using hanlder...
mTimerHandler.postDelayed(mTimerExecutor, 10000);
You can cancle your future task executor any time by this...
mTimerHandler.removeCallbacks(mTimerExecutor);
I am not sure if this is a very good way of accomplishing this (my answer here below) :
Use a Handler, create a HandlerThread and keep posting messages to this handler.
For the handlers "handleMessage" method, you can do your task and again send a message back to the MessageQueue.
HandlerThread thread = new HandlerThread(<name>);
thread.start();
Looper looper = thread.getLooper();
CustomHandler handler = new CustomHandler(looper);
// The CustomHandler class
class CustomHandler extends Handler {
public CustomHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
//Do your operation here
handler.sendEmptyMessageDelayed(msg, <delayTime>);
}
}

Android service with handler and thread

I have an application which starts a new service. In this service I currently have a handler that does some work every minute and then sends the results to the main activity through a BroadcastReceiver. I want the following thing: Every minute create a new thread inside the service, make it do the work and send a message to the handler that it is finnished and then the handler will send to the main activity through a BroadcastReceiver. How can i combine the Thread and the Handler? Here is what I have so far -only part of code of interest-
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
try {
getAppResources(); //this is the work i want to place in a new thread
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intent.putExtra(key,value);
sendBroadcast(intent);
handler.postDelayed(this, 60*1000);
}
};
Here is what i understand i need to do
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
/* try {
getAppResources();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Thread t = new Thread() {
#Override
public void run(){
try {
getAppResources();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
};
handler.postDelayed(this, 60*1000);
}
};
And where do i place the handleMessage ? If i place it inside the Runnable it says it is never used locally. I just place it right before the Runnable ?
public void handleMessage(Message msg){
if(msg.what == 0){
intent.putExtra(key,value);
sendBroadcast(intent);
}
}
Is this how I should do it ?
EDIT: Handler code that sends to the main activity some data
private final Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == 0){
Log.d("HANDLE","Am primit mesaj");
//Notify preparations
intent.putExtra("RunningApps", runningApps.size());
intent.putExtra("CPU", highestDrainPackageCPU);
intent.putExtra("GPS",highestDrainPackageGPS);
intent.putExtra("WIFI", highestDrainPackageWIFI);
//Now i have all my data, time to send them to the activity
//First , send the strings to be set in the TextViews
//Each running app has 7 messages to display -> ArrayList<String>
for(int i=0;i<runningApps.size();i++){
intent.putStringArrayListExtra(String.valueOf(i), appInfo.get(i));
}
//Next send values to plot the chart
//CPU energy consumption for highest draining application
double [] currValues_cpu = new double[tableCPU.get(highestDrainPackageCPU).size()];
Log.d("CPUSIZE",String.valueOf(currValues_cpu.length));
for(int j=0;j<tableCPU.get(highestDrainPackageCPU).size();j++){
currValues_cpu[j]=tableCPU.get(highestDrainPackageCPU).get(j);
Log.d("CPUVALUE",String.valueOf(currValues_cpu[j])+"For application"+highestDrainPackageCPU);
}
intent.putExtra("highestDrainPackageCPU", currValues_cpu);
//GPS energy consumption for highest draining application
double [] currValues_gps = new double[tableGPS.get(highestDrainPackageGPS).size()];
for(int j=0;j<tableGPS.get(highestDrainPackageGPS).size();j++){
currValues_gps[j]=tableGPS.get(highestDrainPackageGPS).get(j);
}
intent.putExtra("highestDrainPackageGPS", currValues_gps);
//WIFI energy consumption for highest draining application
double [] currValues_wifi = new double[tableWIFI.get(highestDrainPackageWIFI).size()];
for(int j=0;j<tableWIFI.get(highestDrainPackageWIFI).size();j++){
currValues_wifi[j]=tableWIFI.get(highestDrainPackageWIFI).get(j);
}
intent.putExtra("highestDrainPackageWIFI", currValues_wifi);
sendBroadcast(intent);
}
}
};
Here is the BroadcastReceiver in the Main Activity and the UpdateUI function:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
public void updateUI(Intent intent){
resourceTab.removeAllViews();
//statisticsTab.removeAllViews();
int apps_no = intent.getIntExtra("RunningApps", 0);
String highestDrainPackageCPU = intent.getStringExtra("CPU");
String highestDrainPackageGPS = intent.getStringExtra("GPS");
String highestDrainPackageWIFI = intent.getStringExtra("WIFI");
//TO-DO: Get information for each app and store it in textview.Then add it to a linearlayout
for(int i=0;i<apps_no;i++){
//Setup delimiter
View delimitator = new View(this);
delimitator.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,1));
delimitator.setBackgroundColor(Color.parseColor("#50FFFFFF"));
//Extract values
ArrayList<String> info = new ArrayList<String>();
info=intent.getStringArrayListExtra(String.valueOf(i));
for(int j=0;j<info.size();j++){
TextView infoApp = new TextView(this);
//////Setup textview//////////
infoApp = new TextView(this);
infoApp.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
infoApp.setTextColor(Color.parseColor("#FFFFFF"));
infoApp.setText(info.get(j));
resourceTab.addView(infoApp);
}
//Add delimiter
resourceTab.addView(delimitator);
}
double [] cpu_values = intent.getDoubleArrayExtra("highestDrainPackageCPU");
double [] gps_values = intent.getDoubleArrayExtra("highestDrainPackageGPS");
double [] wifi_values = intent.getDoubleArrayExtra("highestDrainPackageWIFI");
//Now plot the graph
createGraphOverall(cpu_values, gps_values, wifi_values, highestDrainPackageCPU, highestDrainPackageGPS, highestDrainPackageWIFI);
//Update the table
updateTable(cpu_values, gps_values, wifi_values, highestDrainPackageCPU, highestDrainPackageGPS, highestDrainPackageWIFI);
}
My Activity was successfully updated before I tried to create a new thread to do the heavy work inside the service.
EDIT: Sorry, I think I noticed it earlier, and got side tracked with the handler.
You create Thread t, but you never run it.
t.start();
You define handleMessage() as a method of the handler, like this:
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//TODO: Handle different types of messages
}
};

How to animate footer view in all Activity from SD card images (Like footer Adds googleadds,etc)

I am new in developing apps for android and I need some help.
I need to animating images in footer from specific path folder in SDCARD for all activity, i use footer layout as common for all layout.
I have writen code for animating images by writing below code:
public void AnimateActionHandler() {
try {
Toast.makeText(this, "My Service AnimateActionHandler", Toast.LENGTH_LONG).show();
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 500; // delay for 1 sec.
int period = 1000; // repeat every 2 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
} catch (Exception e) {
// TODO: handle exception
}
}
public void AnimateandSlideShow() {
try {
Toast.makeText(this, "My Service AnimateandSlideShow", Toast.LENGTH_LONG).show();
if (Config.ImageFilelist.isEmpty()) {
Config.ImageFilelist = GetFileList(AddsPath);
}
if (Config.ImageFilelist.size() <= Config.currentimageindex) {
Config.currentimageindex = 0;
}
Toast.makeText(this, "ImageFilelist::"+Config.ImageFilelist.size(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Config.currentimageindex::"+Config.currentimageindex);
Config.FooterBitmap = BitmapFactory.decodeFile(Config.ImageFilelist.get(Config.currentimageindex).toString());
Log.d(TAG, "Addbmp"+Config.FooterBitmap.getHeight());
Config.slidingimage = (ImageView) findViewById(R.id.goeasy_footer);
Config.slidingimage.setImageBitmap(Config.FooterBitmap);
Log.d(TAG, "JOSEafter");
Animation rotateimage = AnimationUtils.loadAnimation(this,R.anim.splash_anim);
Config.slidingimage.startAnimation(rotateimage);
Config.currentimageindex = Config.currentimageindex + 1;
if (Config.ImageFilelist.size() <= Config.currentimageindex) {
Config.currentimageindex = 0;
}
} catch (Exception e) {
Log.e(TAG, "Set image EXC"+e.toString());
e.printStackTrace();
// TODO: handle exception
}
catch (OutOfMemoryError oe) {
try{
}
catch (Exception e) {
// TODO: handle exception
}
// TODO: handle exception
}
}
Now i would like to play this animation in footer for all screens by service, How can i fix this one, Anyone can help me.
Why you animate with code though you have facility of Animation Classes in android.
Try following example.
Animation Drawable ,Frame Animation and Other animation exmples

How to pause app in simple way on android?

I am trying to make view of random text 3 times with time pausing between.
I just can't! It all run all together. I admit I don't know thread subject at all, I just need simple solution.
public void loading3() {
Random randomDouble = new Random();
temp = (double) randomDouble.nextInt(100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setText(temp + "%");
}
This is the code. I want to use it let's say 3-4 times in a row. How can i do it? I try inside loop or writing same methods in a row but it won't work because it doesn't wait for the first method to end before start the new one.
You should not sleep on the main thread. This can easily be done with a Handler or Timer. Here is an example with a Handler:
private int mCount = 0;
private Handler mHandler = new Handler();
private Runnable mUpdater = new Runnable() {
public void run() {
Random randomDouble = new Random();
temp = (double) randomDouble.nextInt(100);
result.setText(temp + "%");
mCount++;
if (mCount < 3)
mHandler.postDelayed(mUpdater, 1000);
}
}
public void loading3() {
mHandler.postDelayed(mUpdater, 1000);
}

How to implement handlers in Android from a thread in seperate file

I was wondering how to use a handler in android to send two messages from a separate thread to update UI. The thread is declared in another file. I understand that using java Thread is not desirable in Android, but I have given up using android methods, they are terrible. The handler messages are sent every 200 miliseconds from my declared thread. I cannot find a decent example of how to implement it.
Here is my extended thread. This is called from the activity.
import java.io.IOException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
public class MPlayer extends Thread {
private volatile boolean playing = false;
private volatile boolean finished = false;
MediaPlayer player;
Message msg;
Bundle bundle;
String filepath;
/* other fields, constructor etc. */
public MPlayer(String path) {
filepath = path;
player = new MediaPlayer();
bundle = new Bundle();
msg = new Message();
start();
}
public void seekMPlayer(int i) {
// TODO Auto-generated method stub
player.seekTo(i);
}
public boolean getPlaying() {
// TODO Auto-generated method stub
return playing;
}
#Override
public void run() {
try {
player.setDataSource(filepath);
player.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (!finished) {
while (playing && !finished) {
try {
Thread.sleep(200);
if (playing && !finished) {
bundle.putString("progval", songTime());
// msg.setData(bundle);
// threadHandler.sendMessage(msg);
} else
break;
} catch (InterruptedException e) {
}
}
}
}
public synchronized void pauseMPlayer() {
playing = false;
player.pause();
}
public synchronized void PlayMPlayer() {
playing = true;
player.start();
// call notify() here when you switch to wait/notify.
}
public void stopMPlayer() {
playing = false;
finished = true;
player.release();
// call notify() here too.
}
private String songTime() {
// TODO Auto-generated method stub
if (filepath != null) {
int progressseconds = (int) ((player.getCurrentPosition() / 1000) % 60);
int progressminutes = (int) ((player.getCurrentPosition() / 1000) / 60);
int durationseconds = (int) ((player.getDuration() / 1000) % 60);
int durationminutes = (int) ((player.getDuration() / 1000) / 60);
String progmin, progsec, durmin, dursec;
if (progressminutes >= 10)
progmin = Integer.toString(progressminutes);
else
progmin = "0" + Integer.toString(progressminutes);
if (progressseconds >= 10)
progsec = Integer.toString(progressseconds);
else
progsec = "0" + Integer.toString(progressseconds);
if (durationminutes >= 10)
durmin = Integer.toString(durationminutes);
else
durmin = "0" + Integer.toString(durationminutes);
if (durationseconds >= 10)
dursec = Integer.toString(durationseconds);
else
dursec = "0" + Integer.toString(durationseconds);
return (progmin + ":" + progsec + "/" + durmin + ":" + dursec);
} else {
return ("No File!");
}
}
}
Handler should bind a Looper of the thread. Use this constructor to specify a thread looper
Handler handler = new Handler(Looper.getMainLooper());
And now the you can send message to the main thread
There is nothing wrong in using Java threads in Android but it is a bit overkill to use it just for sending periodic messages. The recommended way to do it is to use Handler.postDelayed. This article suggests following method: put all your updating code into a Runnable and add postDelayed call to the end of this Runnable's run() to schedule it again. This approach eliminates overhead of having a background thread.
However it is easy to use Handler to send messages from the other thread. As I understand you are trying to send messages to some UI component so it can update itself.
In my application I faced a similar problem. I declared a handler inside the UI component and passed this handler to a background thread in a constructor parameter.
The UI part looks like:
class MyActivity extends Activity {
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
// update UI according to a content of msg from background thread
// ...
}
};
private Thread mBackgroundWorker = new BackgroundThread(mHandler);
protected void onCreate(Bundle savedInstanceState) {
// ...
mBackgroundWorker.start();
// ...
}
protected void onDestroy() {
// we created the thread in this activity
// so we should manage its lifecycle here
mBackgroundWorker.interrupt();
}
}
And the background thread is implemented like
class BackgroundThread extends Thread {
private final mHandler;
public BackgroundThread(Handler h) {
mHandler = h;
}
public void run() {
// do some processing...
mHandler.sendMessage(/*some message to update an UI*/);
// ...
}
}

Categories

Resources