Android, How to stop Service playing music when pausing app , - android

I am building a simple android application and it has two Activities and a IntentService. My IntentService plays music over every activity(thats what I want) but if I leave the app the music still plays (example: if I press the home button it will take me to the desktop, putting my activity in the onpause state but the music from that app is still playing). Any help would be appreciated....
code below
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent= new Intent(this, BackgroundMusic.class);
startService(serviceIntent);
}
public void ShipPick(View view){
Intent activityIntent= new Intent(this, ShipChoiceActivity.class);
startActivity(activityIntent);
}
}
Background Music Service
public class BackgroundMusic extends IntentService {
MediaPlayer mp;
public BackgroundMusic() {
super("BackgroundMusic");
}
Handler HN = new Handler();
private class PlayMusic implements Runnable {
public void PLayMusic(){
}
public void run(){
mp = MediaPlayer.create(getApplicationContext(), R.raw.musicfile);
mp.start();
}
}
#Override
protected void onHandleIntent(Intent intent) {
HN.post(new PlayMusic());
}
public void onPause() {
mp.pause();
}
public void onResume() {
mp.start();
}
protected void onStop() {
mp.stop();
mp = null;
}
}
second activity
public class ShipChoiceActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ship_choice);
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.starwars"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".BackgroundMusic" />
<activity
android:name="com.example.ship.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="ShipChoiceActivity"/>
</application>
</manifest>

For controlling BackgroundMusic Service from Activity you will need to use custom BroadcastReceiver to communicate with service when application is going in onpause state.
Register BroadcastReceiver In BackgroundMusic :
public class MusicServiceBroadCast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
if(<Match for action>){
if Action is for pause then call pause for MediaPlayer
}else{
if Action for Play ...
}
}
}
#Override
protected void onHandleIntent(Intent intent) {
//... Register BroadcastReceiver
registerReceiver(new MusicServiceBroadCast(), new IntentFilter(
"com.xx.PAUSE_MUSIC_ACTION"));
HN.post(new PlayMusic());
}
Send BroadcastReceiver from Activity onPause :
Intent intent = new Intent();
intent.setAction("com.xx.PAUSE_MUSIC_ACTION");
sendBroadcast(intent);

Related

how to Create and register the BroadcastReceiver in code

i am new on android .
I am trying register the BroadcastReceiver in code at my activity. this is my code:
MyReciever class:
public class MyReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("===>", "onReceive: "+ intent.getAction());
Toast.makeText(context, "I got it "+ intent.getIntExtra("MyValue",0), Toast.LENGTH_SHORT).show();
}
}
myActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReciever = new MyReciever();
intentFilter = new IntentFilter();
intentFilter.addAction("test");
}
#Override
protected void onResume() {
registerReceiver(myReciever, intentFilter);
super.onResume();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.safarayaneh.mybroadcastreciever">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
when i run my app, nothing happen and toast not comes up! I've read this and this article and i don't understand that where is my problem.
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this line makes the broadcastreceiver
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I got it "+ intent.getIntExtra("MyValue",0), Toast.LENGTH_SHORT).show();
}
};
//this line register broadcastreceiver
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mBroadcastReceiver, new IntentFilter("test"));
//this line calls the broadcastreceiver
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("test"));
}
}
Register your broadCast receiver in OnResume and unregister it in OnPause like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReciever = new MyReciever();
intentFilter = new IntentFilter();
intentFilter.addAction("test");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(reMyreceive);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(reMyreceive, filter);
}

Why LocalBroadcastManager is not working?

I tried to learn LocalBroadcastManager. Searched in web and implemented a simple app with Two activity to perform LocalBroadcastManager. But it's not working. I can't found what's wrong with my code. please help me!
here is my code.
FirstActivity.java
public class FirstActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
Intent intent = new Intent("localReceiver");
LocalBroadcastManager.getInstance(FirstActivity.this).sendBroadcast(intent);
}
});
} }
SecondActivity.java
public class SecondActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textView = (TextView) findViewById(R.id.hi_text);
LocalBroadcastManager.getInstance(this).registerReceiver(message, new IntentFilter("localReceiver"));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(message);
}
private BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("SecondActivity", "Receiver Initiated...");
textView.setText("Intent receiver activated");
}
}; }
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:windowSoftInputMode="adjustResize|stateHidden"
android:label="SecondActivity" />
</application>
you are broadcasting something from FirstActivity, and you expect that SecondActivity receives it. In order this to happen you should be able to run two different Activitys at the same time, which is, by design, not possible. By the time you broadcast the string, you don't have anybody listening for it. Try using a Service to broadcast the String, with the receiving Activity resumed, and it will work
SecondActivity would looks like this:
private BroadcastReceiver uiUpdateReceiver;
onStart():
#Override
protected void onStart() {
LocalBroadcastManager.getInstance(SecondActivity.this).registerReceiver((uiUpdateReceiver), new IntentFilter("Your_Data");
super.onStart();
}
onCreate():
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
uiUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
onStop():
#Override
protected void onStop() {
LocalBroadcastManager.getInstance(ChatActivity.this).unregisterReceiver(uiUpdateReceiver);
super.onStop();
}
Hope it will help you.

BroadcastReceiver not working as expected on Android

I know this was asked already many times but I can't get this to work. I looked all around Android docs and other sources. I got this activity that has a broadcast receiver variable inside and starts a service as such in the constructor:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Received", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compass);
Intent mIntent = new Intent(this, GPSTracker.class);
startService(mIntent);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, new IntentFilter());
}
#Override
protected void onStop() {
unregisterReceiver(mReceiver);
super.onStop();
}
I put the service down in the manifest and I am sure it works properly. Any help will be appreciated.
Broadcast receiver is supposed to receive 2 floats from the service periodically.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jemboy.compass" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".GPSTracker"></service>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".CompassActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OtherActivity"></activity>
</application>
In the activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UPDATE_PLAYER)) {
updateMediaPlayerToggle();
} else if (intent.getAction().equals(BUFFERING)) {
showMediaPlayerBuffering();
}
}
};
private void registerBroadcastReceiver() {
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter updateIntentFilter = new IntentFilter();
updateIntentFilter.addAction(UPDATE_PLAYER);
updateIntentFilter.addAction(BUFFERING);
broadcastManager.registerReceiver(broadcastReceiver, updateIntentFilter);
}
in the service.
private void sendUpdatePlayerIntent() {
Log.d(TAG, "updatePlayerIntent");
Intent updatePlayerIntent = new Intent(MainActivity.UPDATE_PLAYER);
LocalBroadcastManager.getInstance(this).sendBroadcast(updatePlayerIntent);
}
Example from a media player service.

Broadcast Receiver Registration

I am new to android.
My project is having one activity and one service. My service is having one broadcast receiver and activity is having broadcast sender which is in PeriodSender method .Dynamically when i am registering the receiver then at the start of the service it is not invoking but if i send some thing after few moment then it invokes.
But I want to register it in Manifest ,I have included the receiver details in Manifest but the receiver is not invoking . My receiver class name is MyReceiver21 and the intent action is MY_ACTION1. actually I want my broadcast receiver to be registered at the starting it self.
Following is my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.experiment.Test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="3" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.experiment.Test.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver21" >
<intent-filter>
<action android:name="com.experiment.Test.MainActivity.MY_ACTION1" />
</intent-filter>
</receiver>
<service
android:name="Myservice21"
android:enabled="true" />
</application>
</manifest>
my activity code is
public class MainActivity extends Activity {
MediaPlayer OurSong;
Context SavedThis=this;
int i=0;
public Handler handler1 = new Handler();
public Handler handler2= new Handler();
Button Start;
Button Stop;
Button Button21;
Button StopButton;
public int GProgreess=0;
int Rc=0;
int BitCount=0;
int SeekPos=0;
int Period=500;
MyReceiver myReceiver;
final static String MY_ACTION1 = "MY_ACTION1";
public int Data=0;
public int beat=0;
int BreakVar=0;
Thread myThread ;
static public TextView text1,text2,text3,text4;
private SeekBar bar;
private TextView textProgress,textAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StopButton=(Button)findViewById(R.id.buttonstop);
StopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
stopService(new Intent(SavedThis,Myservice21.class));
BitCount=0;
}/****End of on clk******/
});/*****End of set on clk listener*****/
Button21.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Rc=0;
BitCount=13;
stopService(new Intent(SavedThis,Myservice25.class));
SystemClock.sleep(200);
startService(new Intent(SavedThis,Myservice21.class));
PeriodSender();
}/****End of on clk******/
});/*****End of set on clk listener*****/
}
public void PeriodSender()
{
Intent intent1 = new Intent();
intent1.setAction("MY_ACTION1");
intent1.putExtra("kz", Period);
sendBroadcast(intent1);
text3.setText(""+Period);
Toast.makeText(getApplicationContext(), "PeriodSent",Toast.LENGTH_SHORT).show();
}
#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;
}
}
my service class
public class Myservice21 extends Service {
int BitCount=0;
int Rc=0;
int Period=500;
Intent intent = new Intent();
MyReceiver21 myReceiver21;
public Handler handler1 = new Handler();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
intent.setAction(MY_ACTION);
myReceiver21 = new MyReceiver21();
IntentFilter intentFilter1 = new IntentFilter();
intentFilter1.addAction(com.experiment.Test.MainActivity.MY_ACTION1);
registerReceiver(myReceiver21, intentFilter1);
Intent intent1 = new Intent(Myservice21.this,MainActivity.class);
startService(intent1);
handler1.post(runnable1);
}
public class MyReceiver21 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
int data = intent.getIntExtra("kz", 0);
Period=data;
Toast.makeText(getApplicationContext(), "PeriodRceived21",Toast.LENGTH_SHORT).show();
}
}
public void onStart(Intent intent,int StartId)
{
Rc=0;
}
public void onDestroy()
{
}
}
can any one help me to register the receiver in manifest. Thanks in advance
You don't have to add the intent filter for your own broadcasts. Just register the service for that broadcasts with registerReceiver() when the service is started.
Note, that you have to start the service manually when your App starts, for instance in the MainActivity.onCreate():
startService(new Intent(this, Myservice21.class));
When the MainActivity has been created, it will start the service, which itself registers for BroadcastIntents and starts listening for them. This should work.

Unable to start service Intent { cmp=com.marie.mainactivity/.BackgroundService }: not found

I've been studying from the book "Pro Android 2." I'm working through a Service example that consists of two classes: BackgroundService.java and MainActivity.java. The MainActivity claims (erroneously?) it starts the Service as indicated by output to logcat from the Log.d call below:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(TAG, "starting service");
Button bindBtn = (Button)findViewById(R.id.bindBtn);
bindBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent backgroundService = new Intent(MainActivity.this, com.marie.mainactivity.BackgroundService.class);
startService(backgroundService);
}
});
Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
unbindBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
stopService(new Intent(MainActivity.this, BackgroundService.class));
}
});
}
}
What puzzles me is the UI provides two buttons: Bind and UnBind as shown above. But according to the documentation if onBind() as shown below returns null that indicates you don't want to allow binding. But as shown above the onClick() method of (the Bind button) bindBtn.setOnClickListener(new OnClickListener() calls startService(backgroundService) which gives this error:"Unable to start service Intent { cmp=com.marie.mainactivity/.BackgroundService }: not found"
public class BackgroundService extends Service {
private NotificationManager notificationMgr;
#Override
public void onCreate() {
super.onCreate();
notificationMgr = NotificationManager)getSystemService(NOTIFICATION_SERVICE);
displayNotificationMessage("starting Background Service");
Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
thr.start();
}
class ServiceWorker implements Runnable
{
public void run() {
// do background processing here...
//stop the service when done...
//BackgroundService.this.stopSelf();
}
}
#Override
public void onDestroy()
{
displayNotificationMessage("stopping Background Service");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void displayNotificationMessage(String message)
{
Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Background Service", message, contentIntent);
notificationMgr.notify(R.id.app_notification_id, notification);
}
}
I don't understand the point of this example. If onBind() returns null what's the point of having a Bind button (bindBtn)? I thought the point was to show how to start a BackgroundService. But it doesn't seem to work unless I'm missing something.
I should add I have added to my AndroidManifest.xml:
<service android:name=".BackgroundService"></service>
as follows:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<service android:name=".BackgroundService"></service>
</activity>
</application>
Remove the service from inside the activity. It is at the same level as the activity within the application. Eg:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BackgroundService"></service>
</application>

Categories

Resources