Reputation: 75
I have a Broadcast Receiver. But it destroys when the activity closes....how do I keep it running in the background. I know I can do that by using a SERVICE...But how do I implement that in a service??
onStart:
@Override
protected void onStart() {
super.onStart();
private final BroadcastReceiver broadcast = new Broadcast();
IntentFilter filter = new IntentFilter("Update Player");
registerReceiver(broadcast, filter);
isReceiverRegistered = true;
}
Broadcast:
///BroadcastReceiver
public class Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, final Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("Update Player")) {
position = intent.getIntExtra("position_2", -1);
setTextView();
byte[] image = getArt(PlayingScreen_List.get(position).getPath());
if (image != null) {
Glide.with(getApplicationContext()).asBitmap()
.load(image)
.into(profile_image);
} else {
Glide.with(getApplicationContext()).asBitmap()
.load(R.drawable.allsongs)
.into(profile_image);
}
}
}
}
OnPause:
@Override
protected void onPause() {
super.onPause();
if (isReceiverRegistered) {
unregisterReceiver(broadcast);
isReceiverRegistered = false;
}
}
Upvotes: 2
Views: 3172
Reputation: 1470
You need to create class which extends to Service
. Add inner class to it which extends to BroadcastReceiver
. Check out this code.
public class MyService extends Service {
BroadcastReceiver broadcastReceiver;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do something
}
// constructor
public MyReceiver(){
}
}
@Override
public void onCreate() {
// create IntentFilter
IntentFilter intentFilter = new IntentFilter();
//add actions
intentFilter .addAction("com.example.NEW_INTENT");
intentFilter .addAction("com.example.CUSTOM_INTENT");
intentFilter .addAction("com.example.FINAL_INTENT");
//create and register receiver
broadcastReceiver = new MyReceiver();
registerReceiver(broadcastReceiver, intentFilter );
}
}
In your manifest add this code:
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.example.NEW_INTENT">
</action>
<action android:name="com.example.CUSTOM_INTENT">
</action>
<action android:name="com.example.FINAL_INTENT">
</action>
</intent-filter>
</receiver>
Upvotes: 1