How to stop spending broadcast in Android? - java

I have an Android project which is sending a Broadcast every second and am trying to figure out how to stop it after a click.
My broadcast code is:
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
stoptimertask(); //it is stopping broadcast for a second.

You can define two methods: one that start a Timer to send a broadcast every second and a second one that stop the Timer.
Timer timer;
private void startBroadcastLoop() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Send broadcast
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
}
},0,1000); // Send broadcast every second
}
private void stopBroadcastLoop() {
if(timer!=null){
timer.cancel();
timer = null;
}
}
And then on your button, call the right function according to the state of a boolean:
sendBroadcastBool = false;
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// If broadcast not sent yet
if (!sendBroadcastBool) {
startBroadcastLoop();
sendBroadcastBool = true;
}
else {
stopBroadcastLoop();
sendBroadcastBool = false;
}
}
});
Best

Related

How to build a notification in android and implement click listener?

Hello friends i am creating mp3 player application my application is successfully build i want implement click event notification when user goes on background they control media from notification panel my notification also build successfully but problem is that how control music and change image on notification .addaction() when user click on pause the image change to play and when song is play image back change to pause and media player is also and i am also want get songs title, and artist here my code you can easily understand!
public void play(int songindex) {
song = songList.get(songindex);
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
Uri uri = Uri.parse("file:///" + song.getGetpath());
mediaPlayer = MediaPlayer.create(mContext, uri);
title.setText(song.getTitle());
artist.setText(song.getArtist());
notificationTitleText=title.getText();
notificationDescText=artist.getText();
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(handler);
mediaPlayer.start();
seekBar.setProgress(0);
seekBar.setMax(100);
updateProgressBar();
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (checked) {
mediaPlayer.setLooping(true);
mediaPlayer.start();
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songList.size() - 1) - 0 + 1) + 0;
play(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
}
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public void shownotification(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.dog);
Notification channel = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID_1)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(notificationTitleText
)
.setContentText(notificationDescText)
.setLargeIcon(largeImage)
.addAction(R.drawable.ic_like,"like",null)
.addAction(R.drawable.ic_prev,"prev",null)
.addAction(R.drawable.ic_pause,"pause",null)
.addAction(R.drawable.ic_next,"next",null)
.addAction(R.drawable.ic_dislike,"dislike",null)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle().
setShowActionsInCompactView(1,2,3))
.build();
mNotificationManagerCompat.notify(1,channel);
}
gettext()method is working fine but it work on first when any clicked event is happen if song play oncomplete and next song is not get text value
I am assuming that you are playing songs from an Activity but this will also work for a service.
Put this in your activity or service
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("com.mypackage.ACTION_PAUSE_MUSIC")){
//Do whatever you want. Ex. Pause
}
//Similarly this can be done for all actions
}};
Make your show notification method like this
public void shownotification(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.dog);
Intent pauseIntent = new Intent("com.mypackage.ACTION_PAUSE_MUSIC");
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 1, pauseIntent, 0);
// Similarly you can create an intent and pending intent pair for each action you want just change the string in intent constructor
Notification channel = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID_1)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(notificationTitleText
)
.setContentText(notificationDescText)
.setLargeIcon(largeImage)
.addAction(R.drawable.ic_like,"like",null)
.addAction(R.drawable.ic_prev,"prev",null)
.addAction(R.drawable.ic_pause,"pause",pausePendingIntent) //like this attach every action with respective pending intent
.addAction(R.drawable.ic_next,"next",null)
.addAction(R.drawable.ic_dislike,"dislike",null)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(1,2,3))
.build();
mNotificationManagerCompat.notify(1,channel);}
I want to add one more thing to #Kumar Manas answer
i.e We need to register reciever that is being created in activity.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("com.mypackage.ACTION_PAUSE_MUSIC")){
//Do whatever you want. Ex. Pause
}
//Similarly this can be done for all actions
}};
To register your Reciever add these lines in onCreate()
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("com.mypackage.ACTION_PAUSE_MUSIC");
registerReceiver(receiver,intentFilter);
Note: You can add as many actions you want
You may get your answer by following this tutorial "Android Music Player Controls on Lock Screen and Notifications"

How to gracefully shut down all activities and close all running threads in an Android app?

At the moment, in each one of my activities I have this method:
private void registerReceiverClose(){
Activity activity = this;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLOSE_ALL");
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
activity.finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
and this one as well:
#Override
protected void onDestroy() {
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
They're triggered by the following logout button:
Button logout = findViewById(R.id.logout_button);
logout.setOnClickListener(click -> {
Intent intent = new Intent("CLOSE_ALL");
this.sendBroadcast(intent);
});
One thing that I'm sure is not closing in the right way, is that I have this code:
private static final ScheduledExecutorService pollingScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
private static final Object lock = new Object();
private static ScheduledFuture<?> currentRunningTask;
public void longPoll() {
synchronized (lock) {
if (currentRunningTask != null) {
currentRunningTask.cancel(true);
}
try {
currentRunningTask = pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
}
}
public void request() {
Thread requestThread = new Thread(this);
requestThread.start();
}
which continues to issue requests even after I think I should be logged out, which causes errors on the server.
How can I make sure all the threads stop gracefully and the application closes down in the right way?
You could wrapthe polling code inside of a Service. This service can then be stopped using
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
Inside of the service, you can override onDestroy() to clean resources up.

Displaying new screen takes too much time! (threads maybe...?)

TL;DR: My intent takes too much time to start from a different thread, whereas starting from the main thread is very fast. I dont actually know if this is a problem with threads or with the onFinish method
So, I have a countdown timer. It counts down from twenty seconds, and onFinish() I have an intent. I am also periodically setting the text of my textView based on millisUntilFinished. I noticed, that after the textView says 1 second left, the intent starts after 3 seconds.
But, if I am switching activities by using an intent from OUTSIDE of the onFinish method the next activity starts quickly. So,
Why does starting an intent from a the onFinish method take longer than usual?
According to my little test with my timer, I decided that I need a better and faster way to start my intent, since clearly, the onFinish method launches after more time then the timer actually starts. So, what should I do to start my intent faster? I need it to be immediate...
public void startTimer() {
timer = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished/1000;
timetext.setText(seconds + ":00");
}
public void onFinish() {
Intent intent = new Intent(MainActivity.this, GameOver.class);
intent.putExtra("score", score); // pass your values and retrieve them in the other Activity using keyName
intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
startActivity(intent);
}
}.start();
}
Thanks,
Ruchir
Try placing the startActivity(intent) outside of the timer as such:
public void startTimer() {
timer = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished/1000;
timetext.setText(seconds + ":00");
}
public void onFinish() {
Intent intent = new Intent(MainActivity.this, GameOver.class);
intent.putExtra("score", score); // pass your values and retrieve them in the other Activity using keyName
intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
}
}.start();
startActivity(intent);
}
You can have a try :
public void onFinish() {
cancel(); //Cancel the countdown
Intent intent = new Intent(MainActivity.this, GameOver.class);
intent.putExtra("score", score); // pass your values and retrieve them in the other Activity using keyName
intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
startActivity(intent);
}
`

Cant get ProgressDialog to show up in android

I cant get a progress dialog to show when I need it to. I have tried putting it in my asyncTask the ui class and the its own thread that runs on the ui and none have worked. Can anyone help me?
the method where the progressDialog method is called:
public void shareTest(View view){ //method called to jump to share activity if criteria matched
if(checkInputs()) { //call to check inputs
Share start = new Share();
boolean isConnected=start.connectToServer(); //connectToServer
Intent intent = new Intent(HomeScreen.this, Share.class); //create intent to move to share class from this activity
startProgressDialog();
if (isConnected) { //check to see if isconnected was succesful
if (Share.matchFound ){ //check to see if a match was found
progress.dismiss();
startActivity(intent); //if true jump to share activity
} else {
while (!Share.timedOut) { //While the time has not timedOut
if (Share.matchFound) { //if a share has been found
startActivity(intent); //start share activity
break; //if true then break
}
}
if (Share.timedOut) {
//send an notice that a match wasn't found
sendToast(getString(R.string.noShare)); //if not true then send Toast
}
}
}
else sendToast(getString(R.string.errServCon)); //if connection to server failed then send toast
}
}
this is the method:
void startProgressDialog() {
new Thread(new Runnable() {
#Override
public void run() { //creates a new runnable thread
// Issue command() on a separate thread
while (!Share.matchFound) { //while havent been asked to disconnect //if a new location has been recieved
activity.runOnUiThread(new Runnable() {
#Override
public void run() { //run on the ui thread act
progress.show(); //call the method that does the update
}
});
}
progress.dismiss();
}
}).start();
}
Declare a global variable like this:
ProgressDialog progress;
Wherever you want to show the progress, paste this code:
progress = ProgressDialog.show(this, "Please wait",
"Loading..", true);
When you are done, simply dismiss it:
progress.dismiss();

Android-Starting new Activity in Handler/runnable is really slow

I am making an android app that requires a runnable. I am starting a new activity from the runnable. The new activity comes up and works fine. The issue is that when the call is made to start the activity, it is incredibly slow. It takes a full 5 seconds to start the activity when I want it to be instantaneous.
Boolean handlerrun=true;
Intent intent= new Intent(this,newactivity.class);
int somevalue=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameactivity);
handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
if(handlerrun){somevalue++;}
if(somevalue>500){
handlerrun=false;
startActivity(intent);
finish();
}
handler.postDelayed(this, 1);}
}
};
handler.postDelayed(r, 1);
}
The activity starts when somevalue is greater than 500. To stop the handler from increasing the value of somevalue, I use a boolean handlerrun, which only runs the handler when it is true. When somevalue is greater than 500, handlerrun= false so the handler doesn't increase the value. I tried using the handler.removeCallbacksandMessages() method but it didn't work. Logcat doesn't give me any errors.Any help would be appreciated.
You could try something like this:
#Override
protected void onResume() {
super.onResume();
if(done){
return;
}
done = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), YourActivity.class));
finish();
overridePendingTransition(0, 0);
}
}, 5000);
}
That will start YourActivity after 5 seconds approximately.
Hope it helps.

Categories

Resources