I have an android app in which I have an activity and a service.
The service is supposed to play music and switch between four songs (depends on what button you press)
The problem is that a few minutes/seconds (it's not always at the same time) after you start the service by playing a song a notification pop ups which claims that the 'app has stopped responding' (with the option to wait and the option to exit). If you press the wait button the notification just goes away and the app and music continues the same. The notification will keep coming back though and unfortunately I am not sure why.
Should probably mention that this only happens to me when the service is on. I have tested this app many times. Never have a notification like that. Only when music is played.
My service:
package com.example.project25112021;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyService extends Service {
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
MediaPlayer mediaPlayer3;
MediaPlayer mediaPlayer4;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.stronger);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
mediaPlayer2 = MediaPlayer.create(this, R.raw.silksonic);
mediaPlayer2.setLooping(true); // Set looping
mediaPlayer2.setVolume(100, 100);
mediaPlayer3 = MediaPlayer.create(this, R.raw.davidguetta);
mediaPlayer3.setLooping(true); // Set looping
mediaPlayer3.setVolume(100, 100);
mediaPlayer4 = MediaPlayer.create(this, R.raw.beatit);
mediaPlayer4.setLooping(true); // Set looping
mediaPlayer4.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
int number = intent.getIntExtra("key", 0);
mediaPlayer.start();
mediaPlayer2.start();
mediaPlayer3.start();
mediaPlayer4.start();
mediaPlayer.seekTo(0);
mediaPlayer2.seekTo(0);
mediaPlayer3.seekTo(0);
mediaPlayer4.seekTo(0);
mediaPlayer.pause();
mediaPlayer2.pause();
mediaPlayer3.pause();
mediaPlayer4.pause();
if (number == 0){
mediaPlayer.start();
}
if (number == 1){
mediaPlayer2.start();
}
if (number == 2){
mediaPlayer3.start();
}
if (number == 3){
mediaPlayer4.start();
}
return startId;
}
//public void onStart(Intent intent, int startId) { }
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
The activity in which you choose what song to play:
package com.example.project25112021;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class SettingsMain extends AppCompatActivity {
Button button;
Button song1;
Button song2;
Button song3;
Button song4;
ImageView album1;
ImageView album2;
ImageView album3;
ImageView album4;
Drawable drawable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_main);
drawable = CameraBackground.getInstance().getBitmap();
LinearLayout relative = (LinearLayout) findViewById(R.id.ButtonFinBack);
if(drawable!= null) {
relative.setBackgroundDrawable(drawable);
}
else
relative.setBackgroundResource(R.drawable.bacckga1);
button = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SettingsMain.this, MainActivity.class);
startActivity(intent);
}
});
song1 = findViewById(R.id.song1);
song2 = findViewById(R.id.song2);
song3 = findViewById(R.id.song3);
song4 = findViewById(R.id.song4);
album1 = findViewById(R.id.album1);
album2 = findViewById(R.id.album2);
album3 = findViewById(R.id.album3);
album4 = findViewById(R.id.album4);
album1.setImageResource(R.drawable.kanye);
album2.setImageResource(R.drawable.silksonic);
album3.setImageResource(R.drawable.davidguetta);
album4.setImageResource(R.drawable.mjthriller);
song1.setText("Play");
song2.setText("Play");
song3.setText("Play");
song4.setText("Play");
song1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",0);
startService(intent);
}
});
song2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",1);
startService(intent);
}
});
song3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",2);
startService(intent);
}
});
song4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",3);
startService(intent);
}
});
}
}
Thanks
Related
I am new to software developing and i am trying to make an application that will play a sound when it charges. The first time i connect it to the charging cable, it plays the sound two times, which is not expected. Also, when i connect and disconnect the cable too quick, it also plays it twice.
Does anyone know the solution to this problem?
package com.mccharginggimmick;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter;
BroadcastReceiver broadcastReceiver;
MediaPlayer mediaPlayerOff;
MediaPlayer mediaPlayerOn;
boolean playedOnceOn;
boolean playedOnceOff;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging){
onCharge();
}
else{
onDisconnect();
}
}
};
MainActivity.this.registerReceiver(broadcastReceiver, intentFilter);
}
public void onCharge(){
if(!playedOnceOn){
imageView.setVisibility(View.INVISIBLE);
mediaPlayerOn = MediaPlayer.create(this, R.raw.btnon);
mediaPlayerOn.start();
mediaPlayerOn.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOn.stop();
playedOnceOn = true;
playedOnceOff = false;
}
});
}
}
public void onDisconnect(){
if(!playedOnceOff){
imageView.setVisibility(View.VISIBLE);
mediaPlayerOff = MediaPlayer.create(this, R.raw.btnoff);
mediaPlayerOff.start();
mediaPlayerOff.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOff.stop();
playedOnceOff = true;
playedOnceOn = false;
}
});
}
}
}
define isCabelConnected inside class
boolean isCabelConnected = false;
then in your onClick
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
boolean isFullCharged = status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging && !isCabelConnected){
onCharge();
isCabelConnected = true;
} else if (isFullCharged && isCabelConnected){
onCharge();
}
else{
onDisconnect();
isCabelConnected = false;
}
this code will make a sound when cable connected and another sound when full charge
I tried a lot with my code below . there is no compile error at all. when I used to start the MP3 which I added , in the logcat window it shows "start called in state 0". please help me with this code . Thanks in advance .I also want to know when we pause the audio , i need to get the song resume from there when i click the start button (or) Is there any resume function for it , Let me know in the comments section . Thanks in advance. Here's my Java code
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.btnStart);
Button mButton1 = (Button) findViewById(R.id.btnStop);
Button mButton2 = (Button) findViewById(R.id.btnPause);
mp = new MediaPlayer();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer.create(MainActivity.this, R.raw.ch);
mp.pause();
}
});
create a class named AudioClip
public class AudioClip {
public static boolean loop = false;
public static MediaPlayer mediaPlayer;
private static SoundPool soundPool;
public static boolean isplayingAudio = false;
public static void playAudio(Context c, int id) {
mediaPlayer = MediaPlayer.create(c, id);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
if (!mediaPlayer.isPlaying()) {
isplayingAudio = true;
mediaPlayer.start();
mediaPlayer.setLooping(loop);
}
}
public static void stopAudio() {
isplayingAudio = false;
mediaPlayer.stop();
}
}
on other activity to play music
Context m = CuteActivity.this;
AudioClip.playAudio(m, R.raw.ch);\
and to stop
if (AudioClip.isplayingAudio) {
AudioClip.stopAudio();
}
i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);
Can you tell me how to play mediaPlayer in Android when I press the home button of emulator or phone? I want it so that when it receives a phone call to stop the video and be able to resume video again that point. How should I do this in this code?
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.MediaController;
import android.widget.VideoView;
public class VideoActivity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video2);
VideoView videoView = (VideoView)this.findViewById(R.id.videoView2);
videoView.setVideoURI(Uri.parse("android.resource://"+
getPackageName() +"/"R.raw.song1));
videoView.setMediaController(new MediaController(this));
videoView.requestFocus();
videoView.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.video_activity2, menu);
return true;
}
public void startVideoActivity3(View v) {
Intent intent = new Intent(VideoActivity2.this, VideoActivity3.class);
startActivity(intent);
}
public void startVideoActivity(View v) {
Intent intent = new Intent(VideoActivity2.this, VideoActivity.class);
startActivity(intent);
}
public void startMainActivity(View v) {
Intent intent = new Intent(VideoActivity2.this,
MainActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
startActivity(intent);
}
}
I never use VideoView class, but according to documentation, this should work:
#Override
public void onPause() {
super.onPause();
VideoView videoView = (VideoView)findViewById(R.id.videoView2);
videoView.pause();
}
#Override
public void onResume() {
super.onResume();
VideoView videoView = (VideoView)findViewById(R.id.videoView2);
videoView.resume();
}
Adding to cyanide's answer, I found the videoView.pause() to not always capture the position of the video - resulting in a black videoView onResume. By adding the videoStopPosition variable this issue is avoided.
//Allows video to resume from same location as the pause
private static int videoStopPosition = 0;
#Override
public void onPause() {
super.onPause();
VideoView videoView = (VideoView)findViewById(R.id.videoView2);
videoStopPosition = videoView.getCurrentPosition();
videoView.pause();
}
#Override
public void onResume() {
super.onResume();
VideoView videoView = (VideoView)findViewById(R.id.videoView2);
videoView.seekTo(videoStopPosition);
videoView.resume();
}
so I'm fairly new to Android. Lemme just explain first:
I'm trying to make a small portable music app, just for my phone and to test my skills/review what I've learned. I have the mainactivity setup to pick a song with 1 of 4 buttons, and it'll start another activity with buttons to pause, resume, and go back to the song selection screen (MainActivity). I'm trying to get the back button to both release the player and finish the activity, and I've tried many different things but nothing seems to work; the app closes due to some exception (a common one being NullPointerException).
So here's MainActivity:
package me.lemmy.portablemusic.app;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button wreckingBall, happy, lig, ligMulti;
Intent songPickedActivity = new Intent("me.lemmy.portablemusic.app.SONGPICKED");
public static MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set buttons
wreckingBall = (Button) findViewById(R.id.song_wreck);
happy = (Button) findViewById(R.id.song_happy);
lig = (Button) findViewById(R.id.song_lig);
ligMulti = (Button) findViewById(R.id.song_lig_multi);
//listeners
wreckingBall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.wrecking_ball);
player.start();
}
});
happy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.happy);
player.start();
}
});
lig.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.let_it_go);
player.start();
}
});
ligMulti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.let_it_go_multi);
player.start();
}
});
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static MediaPlayer getPlayer(){
return player;
}
}
and here's my SongPicked activity:
package me.lemmy.portablemusic.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.media.MediaPlayer;
import android.widget.TextView;
/**
* Created by Lemuel on 6/20/14.
*/
public class SongPicked extends Activity {
TextView text;
Button pause, resume, back;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songpicked);
text = (TextView) findViewById(R.id.tvPlaying);
pause = (Button) findViewById(R.id.buttonPause);
resume = (Button) findViewById(R.id.buttonResume);
back = (Button) findViewById(R.id.buttonBack);
player = MainActivity.getPlayer();
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.pause();
}
});
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.start();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
player.release();
}
});
}
#Override
protected void onPause(){
super.onPause();
finish();
}
}
Any help is appreciated, thanks!
P.S. I know I can't use copyrighted music in my apps, this is just a test.
I suggest to first make sure the activity is in the AndroidManifest file. Second is to change your intent from this:
Intent songPickedActivity = new Intent("me.lemmy.portablemusic.app.SONGPICKED");
into:
Intent songPickedActivity = new Intent(this, SongPicked.class);
Do it as well on the songPickedActivity when going back to MainActivity. You can use putExtra to send data to next intent. For more information click this link.