How to solve an IntentReceiverLeaked after pressing the backbutton - android

I'm having problems with android 6, with my WifiDirect connection. After connecting WIFI direct and pushing the backbutton to my app. The app leaks the intentreceiver
public class WifiDirectController
extends ServerController
implements WifiP2pManager.ConnectionInfoListener,
WifiP2pManager.ChannelListener,
WiFiDirectBroadcastReceiver.WiFiDirectBroadcastListener,
WifiDirectServer.WifiDirectServerListener {
private static final String TAG = "WP2P.Controller";
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private WifiP2pDevice mDevice;
private BroadcastReceiver mReceiver;
private boolean isWifiP2pEnabled = false;
private boolean isDiscovering = false;
private boolean isConnected = false;
private boolean retryChannel = false;
//added by Frank
private boolean isReceiverRegistered = false;
private final IntentFilter mIntentFilter = new IntentFilter();
private Handler mHandler;
private WifiDirectServer serverThread = null;
public WifiDirectController(ServerListener listener) {
super(listener);
//mManager = (WifiP2pManager) mListener.getSystemService(Context.WIFI_P2P_SERVICE);
mManager = (WifiP2pManager) mListener.getApplicationContext().getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(listener.getApplicationContext(), mListener.getMainLooper(), this);
// Indicates a change in the Wi-Fi P2P status.
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
// Indicates the state of Wi-Fi P2P connectivity has changed.
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
// Indicates this device's details have changed.
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
// Indicates that discovery has started or stopped
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION);
mHandler = new Handler();
}
#Override
public void onStart()
{
Log.d(TAG, "onStart() called");
}
#Override
public void onResume() {
Log.d(TAG, "onResume() called");
Log.e(TAG, "FRANK onResume() called");
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
if (!isReceiverRegistered) {
mListener.registerReceiver(mReceiver, mIntentFilter);
isReceiverRegistered = true;
}
}
#Override
public void onPause()
{
Log.d(TAG, "onPause() called");
mListener.unregisterReceiver(mReceiver);
isReceiverRegistered = false;
stopDiscovery();
}
#Override
public void onStop()
{
Log.d(TAG, "onStop() called");
//added frank
if (isReceiverRegistered) {
mListener.unregisterReceiver(mReceiver);
isReceiverRegistered = false;
}
//
cancelDisconnect();
stopServer();
}
#Override
public void restart()
{
Log.d(TAG, "restart() called");
Log.e(TAG, "FRANK onRestart() called");
cancelDisconnect();
stopServer();
startDiscovery();
}
private boolean startServer()
{
Log.d(TAG, " = startServer() called");
Log.e(TAG, "FRANK startServer() called");
this.serverThread = new WifiDirectServer(this);
this.serverThread.start();
return true;
}
ActivityThread: Activity com.android.settings.SubSettings has leaked IntentReceiver android.net.wifi.WifiManager$1#61ae52a that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity com.android.settings.SubSettings has leaked IntentReceiver android.net.wifi.WifiManager$1#61ae52a that was originally registered here. Are you missing a call to unregisterReceiver()?

You must use a method to check if the receiver is registered, this is because when you press back button, the activity is destroyed, so the variables come back to it's original values, for that reason in the Resume method the variable isReceiverRegistered is always false, and it tries to register the receiver again.
You could unregister the receiver in the OnPause method instead of
OnStop method.
Or you can store the value of the variable overriding
onSaveInstanceState method and recoverit in onRestoreInstanceState
method.
Or you can use a ViewModel to persist the variable's values.
Or you can try using a class to manage your receivers. slinden77
gave a possible solution to this, in this thread
public class ReceiverManager {
private static List<BroadcastReceiver> receivers = new ArrayList<BroadcastReceiver>();
private static ReceiverManager ref;
private Context context;
private ReceiverManager(Context context){
this.context = context;
}
public static synchronized ReceiverManager init(Context context) {
if (ref == null) ref = new ReceiverManager(context);
return ref;
}
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter intentFilter){
receivers.add(receiver);
Intent intent = context.registerReceiver(receiver, intentFilter);
Log.i(getClass().getSimpleName(), "registered receiver: "+receiver+" with filter: "+intentFilter);
Log.i(getClass().getSimpleName(), "receiver Intent: "+intent);
return intent;
}
public boolean isReceiverRegistered(BroadcastReceiver receiver){
boolean registered = receivers.contains(receiver);
Log.i(getClass().getSimpleName(), "is receiver "+receiver+" registered? "+registered);
return registered;
}
public void unregisterReceiver(BroadcastReceiver receiver){
if (isReceiverRegistered(receiver)){
receivers.remove(receiver);
context.unregisterReceiver(receiver);
Log.i(getClass().getSimpleName(), "unregistered receiver: "+receiver);
}
}
}
I hope it helps you

Related

Android Wifi Direct onPeersAvailable doesn't shows anything

I'm trying to develop a simple app using Wifi Direct. The problem is I can't get a list of available peers using onPeersAvailable method. I tried the solutions mentioned here and here but no luck.There is nothing at logs, tried using Toast instead of log but nothing showed up on the screen either. Here is my Main and BroadCastReceiver classes.
Main Class:
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().toString();
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
Button btn_discover = (Button) findViewById(R.id.btn_discover);
btn_discover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
/*Toast.makeText(getApplicationContext(), "Discovery is a success.",
Toast.LENGTH_SHORT).show();*/
//startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(getApplicationContext(), "Discovery is a failure "+reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
});
}
/* register the broadcast receiver with the intent values to be matched */
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}}
BroadCastReceiver class:
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private final String LOG_TAG = this.toString();
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Log.i(LOG_TAG, "Wifi Direct is enabled");
} else {
Log.i(LOG_TAG, "Wifi Direct is not enabled");
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
Log.i(LOG_TAG, "Found some peers!!! "+wifiP2pDeviceList.getDeviceList().size());
}
});
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}}
I am sure my device (2012 Nexus 7 running Android 4.4.4) supports Wifi Direct.
I think the issue is because you are creating new "PeerListListener" inside the "WiFiDirectBroadcastReceiver".
Try to add it to your main activity instead:
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener
And then add new method to you main activity to listen to available peers:
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
Log.i(LOG_TAG, "Found some peers!!! " + peerList.getDeviceList().size());
}
Note: Don't forget to create new listener variable instead "WiFiDirectBroadcastReceiver" and pass the main activity as a reference to it.
Hope this helps.

Service that detects screen lock: "Unable to start service Intent"

I'm trying to catch when my device screen is turned off or on. I looked at this answer here. However I haven't quite figured it out. When I test it, I get a warning saying that the service wasn't able to be created: Unable to start service Intent... not found. I'm new to services so I was hoping someone could look over the code and see what I'm doing wrong. Here is my Receiver and Service:
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
Home.locked = true;
Log.i("screenstate", "off");
} else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("screenstate", "on");
}else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}}
Service:
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
Boolean isRunning;
Context context;
Thread backgroundThread;
#Override
public void onCreate() {
super.onCreate();
context = this;
isRunning = false;
// register receiver that handles screen on and screen off logic
Log.i("UpdateService", "Started");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_ANSWER);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
isRunning = false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}}
Here is my main activity:
public class Home extends Activity {
static boolean locked = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Home.this, UpdateService.class));
if(locked)
setContentView(R.layout.activity_home2);
else
showApps(null);
}
public void showApps(View v){
locked = false;
Intent i = new Intent(this, AppsList.class);
startActivity(i);
}}
Thanks in advance.
It looks like the service hasn't been declared in the manifest file. Add its declaration within the <application> tag:
<service android:name=".UpdateService"/>

Let a subscriber in service react on an event posted in activity with otto eventbus

I have the launcher activity in my app that should fire an event with otto event bus in onCreate(). The activity itself makes sure that a service is started. The bus is implemented as a singleton via a BusProvider of a derived class of the bus. Whenever I post to the bus from my activity, the activity itself receives the event (I subscribed for debugging purposes) but not the service, although it should both be sent on the main thread.
Because I receive the event in the activity, otto basically seams to work. I assume that the difference between service (background) and activity (ui) may be the cause why I don't receive the event in the service, but why?
Here is the code of My derived Bus Class:
public class MainBus extends Bus {
private final Handler handler = new Handler(Looper.getMainLooper());
public MainBus(ThreadEnforcer any) {
super(any);
}
#Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
super.post(event);
} else {
handler.post(new Runnable() {
#Override
public void run() {
MainBus.super.post(event);
}
});
}
}
}
Here is the BusProvider Singleton
public final class BusProvider {
// Also tried with ThreadEnforcer.MAIN
private static final MainBus BUS = new MainBus(ThreadEnforcer.ANY);
public static MainBus getInstance() {
return BUS;
}
private BusProvider() {
// No instances.
}
}
Here is the relevant code of my Activity
public class Splashscreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BusProvider.getInstance().register(this);
// Start the Service if not yet started.
if (!isMyServiceRunning()) {
startMyService();
}
LogProvider.getInstance().d("Splashscreen", "Activity started.");
BusProvider.getInstance().post(new SplashscreenStartupCompletedEvent());
LogProvider.getInstance().d("Splashscreen",
"After Startup Event posted");
setContentView(R.layout.splashscreen);
}
/**
* private function to check if the service is running
*
* #return boolean True if the service is running, false otherwise
*/
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (MyApplicationService.class.getName().equals(
service.service.getClassName())) {
LogProvider.getInstance().i("Splashscreen",
"Service is already running.");
return true;
}
}
LogProvider.getInstance().n("Splashscreen", "Service is not running.");
return false;
}
/**
* private function to start the Backgroundservice
*/
private void startMyService() {
LogProvider.getInstance().i("Splashscreen", "Service will be started.");
Context context = getApplicationContext();
Intent service = new Intent(
context,
com.classpath.MyApplicationService.class);
context.startService(service);
}
#Subscribe
public void afterStartEvent(SplashscreenStartupCompletedEvent event) {
LogProvider.getInstance().d("afterStartEvent", "Event received");
}
}
And the relevant part of the Service
public class MyApplicationService extends Service {
#Override
public void onCreate() {
BusProvider.getInstance().register(this);
super.onCreate();
}
#Subscribe
public void afterStartupCompleted(SplashscreenStartupCompletedEvent event) {
LogProvider.getInstance().d("MyApplicationService",
"StartupCompletedEvent empfangen");
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

onReceive method of BroadcastReceiver is not getting called

I know there are many SO posts related to this topic but none is working here.
I am doing sendBroadcast call from the class UserEntry.java: ---
final Intent intent = new Intent(DeviceScanActivity.ACTION_DISCONNECTED);
intent.putExtra(DeviceScanActivity.EXTRAS_DEVICE_NAME, bdDevice.getName());
intent.putExtra(DeviceScanActivity.EXTRAS_DEVICE_ADDRESS, bdDevice.getAddress());
getActivity().sendBroadcast(intent);
I have defined my broadcast receiver in class DeviceScanActivity.java: as ---
private final BroadcastReceiver mUpdateReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
device_name = intent.getExtras().getString(DeviceScanActivity.
EXTRAS_DEVICE_NAME);
device_address = intent.getExtras().getString(DeviceScanActivity.
EXTRAS_DEVICE_ADDRESS);
if (ACTION_CONNECTED.equals(action)) {
mConnected = "Connected";
invalidateOptionsMenu();
} else if (ACTION_DISCONNECTED.equals(action)) {
mConnected = "Disconnected";
invalidateOptionsMenu();
} else if (ACTION_CONNECTING.equals(action)) {
mConnected = "Connecting";
invalidateOptionsMenu();
}
else
{
mConnected = "";
invalidateOptionsMenu();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mUpdateReceiver, makeUpdateIntentFilter());
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUpdateReceiver);
}
So, user clicks connect button and sendBroadcast is called from class UserEntry then user switch to class DeviceScanActivity and still onReceive is never get called.
You are registering the BroadcastReceiver in DeviceScanActivity.java which means it won't be registered until DeviceScanActivity is active.
In other words the broadcast will simply get lost because there isn't a receiver available to receive the broadcast.

ServiceConnection.onServiceConnected() never called after binding to started service

In a game application I have the following scenario:
From the main game Activity, the player starts several game tasks that run in the background with varying duration.
The player should be able to view the progress of the running game tasks in a separate View.
To do this, I created two Activitys and a Service, defined as follows:
Service ProgressService handles several ProgressBars running simultaneously on parallel threads.
Activity WorkScreen2 creates a game task, starts the Service with startService() with task parameters passed in a Bundle.
Activity ProgressScreen binds to the Service to get and display the ProgressBars of the running tasks.
Both activities run under separate TabHosts of one TabActivity.
The problem I'm having is that the ServiceConnection.onServiceConnected() method is never called. I get a Java.lang.NullPointerException because I try to call a method of the Service object that should be assigned in this method. See code below.
I use getApplicationContext().bindService() to bind the Activity to the Service because TabSpec cannot bind to Services. This method returns true. Therefore, binding is successful.
Here is the Service:
public class ProgressService extends Service implements GameConstants {
public static final String BROADCAST_PROGRESS = "com.mycompany.android.mygame.progressbroadcast";
private static final long UPDATE_INTERVAL = 500;
private IBinder mBinder;
private List<ProgressBar> mProgressBarList;
private List<String> mStaffNameList;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
ProgressBar progressBar = new ProgressBar(ProgressService.this);
mProgressBarList.add(progressBar);
Bundle bundle = msg.getData();
String staffName = bundle.getString(WorkScreen2.STAFF_NAME);
mStaffNameList.add(staffName);
int taskDurationMillis = bundle.getInt(WorkScreen2.TASK_DURATION) * 1000;
progressBar.setMax(taskDurationMillis / 1000);
long startTimeMillis = SystemClock.uptimeMillis();
long elapsedTimeMillis = SystemClock.uptimeMillis()
- startTimeMillis;
Intent intent = new Intent();
intent.setAction(BROADCAST_PROGRESS);
while (elapsedTimeMillis < taskDurationMillis) {
try {
Thread.sleep(UPDATE_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
elapsedTimeMillis = SystemClock.uptimeMillis()
- startTimeMillis;
int elapsedTimeSeconds = (int) elapsedTimeMillis / 1000;
progressBar.setProgress(elapsedTimeSeconds);
sendBroadcast(intent);
}
progressBar.setVisibility(View.GONE);
mProgressBarList.remove(progressBar);
mStaffNameList.remove(staffName);
sendBroadcast(intent);
if (mProgressBarList.isEmpty()) {
stopSelf(msg.arg1);
}
}
}
#Override
public void onCreate() {
super.onCreate();
mBinder = new ProgressServiceBinder();
mProgressBarList = Collections
.synchronizedList(new ArrayList<ProgressBar>());
mStaffNameList = Collections.synchronizedList(new ArrayList<String>());
}
/*
* Creates a thread for each game task with parameters passed in
* <code>intent</code>
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "starting service", Toast.LENGTH_LONG).show();
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
Handler serviceHandler = new ServiceHandler(thread.getLooper());
Message msg = serviceHandler.obtainMessage();
msg.arg1 = startId;
msg.setData(intent.getExtras());
serviceHandler.sendMessage(msg);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class ProgressServiceBinder extends Binder {
ProgressService getService() {
return ProgressService.this;
}
}
public List<ProgressBar> getProgressBarList() {
return mProgressBarList;
}
public List<String> getStaffNameList() {
return mStaffNameList;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service done", Toast.LENGTH_SHORT).show();
}
}
And this is the Activity that binds to it:
public class ProgressScreen extends ListActivity {
private final String TAG = "ProgressScreen";
private ProgressScreenAdapter mAdapter;
private ProgressService mProgressService;
private List<ProgressBar> mProgressBarList;
private List<String> mStaffNameList;
#Override
public void onCreate(Bundle bundle) {
Log.i(TAG, "ProgressScreen oncreate");
super.onCreate(bundle);
setContentView(R.layout.progress_screen_layout);
IntentFilter filter = new IntentFilter();
filter.addAction(ProgressService.BROADCAST_PROGRESS);
registerReceiver(receiver, filter);
doBindService();
mAdapter = new ProgressScreenAdapter(this, mStaffNameList, mProgressBarList);
setListAdapter(mAdapter); // Returns true
/*
* This is where I get the NullPointerException
* mProgressService is null here
*/
mProgressBarList = mProgressService.getProgressBarList();
mStaffNameList = mProgressService.getStaffNameList();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(ProgressService.BROADCAST_PROGRESS);
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
boolean doBindService() {
return getApplicationContext().bindService(new Intent(this, ProgressService.class), mConnection, Context.BIND_AUTO_CREATE);
}
void doUnbindService() {
getApplicationContext().unbindService(mConnection);
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
mProgressService = ((ProgressService.ProgressServiceBinder) binder).getService();
Toast.makeText(ProgressScreen.this, "Connected to ProgressService", Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName name) {
mProgressService = null;
}
};
private BroadcastReceiver receiver = new BroadcastReceiver () {
#Override
public void onReceive(Context context, Intent intent) {
mAdapter.notifyDataSetChanged();
}
};
}
And the Service is started from the main Activity as follows:
Intent intent = new Intent(WorkScreen2.this, ProgressService.class);
intent.putExtra(TASK_DURATION, task.getDuration());
intent.putExtra(STAFF_NAME, staff.getName());
startService(intent);
The AndroidManifest.xml contains
<service
android:name=".ProgressService"
android:label="#string/progress_service">
</service>
ServiceConnection's onServiceConnected() is called, but nobody guarantees that it will be called before onCreate continues execution. So, what happens here - you successfuly bind to the service (that's why onBind returns true), but you're not fully connected - onServiceConnected() has not yet been called, so your local mProgressService object is not yet initalized, and therefore you get the NullPointerException.
Solution:
Move these two lines:
mProgressBarList = mProgressService.getProgressBarList();
mStaffNameList = mProgressService.getStaffNameList();
from onCreate() to onServiceConnected() function (use the service object after it is initialized in onServiceConnected()).
Check AndroidManifest.xml of yours and add service that you tried to bind.
You have to return your Binder inner class from
private final IBinder mBinder = new ServiceBinder();
public class ServiceBinder extends Binder {
public PlayerActivity getService() {
return PlayerActivity.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}

Categories

Resources