Mock a method to get code coverage in Android - java

I am writing an Android OpenGL ES 2.0 application in a test driven fashion. Here goes my code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean checkCompatability = checkForDeviceCompatablity();
if(checkCompatability)
{
Toast.makeText(this, "Your device is opengl compatible", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Your device does not support OpenGL", Toast.LENGTH_LONG).show();
}
}
public boolean checkForDeviceCompatablity() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = manager.getDeviceConfigurationInfo();
boolean result = info.reqGlEsVersion >= 0x20000
|| (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1);
return result;
}
}
And this is my test
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity mActivity;
public MainActivityTest(Class<MainActivity> activityClass) {
super(activityClass);
}
public MainActivityTest(){
super(MainActivity.class);
}
//The below method would always return me a true as I test it in a real device.
public void testIntegrationCheckForConfiguration() {
mActivity = getActivity();
mActivity.startActivity(mActivity.getIntent());
boolean resultConfiguration = mActivity.checkForDeviceCompatablity();
assertNotNull(resultConfiguration);
}
//I need to mock the above method into something like the below method so that I can get coverage for the else block.
public void testCheckForConfigurationWhenDeviceIsOfInCorrectConfiguration(){
mActivity = new MainActivity(){
#Override
public boolean checkForDeviceCompatablity() {
return false;
}
};
mActivity.startActivity(mActivity.getIntent());
boolean compatability = mActivity.checkForDeviceCompatablity();
assertTrue(compatability);
}
}
I know I'm doing it incorrectly. But I need a way to mock the checkForDeviceCompatability to make it return false. When I run the test I get a NullPointerException at the startActivity call. How do I mock the function checkForDeviceCompatability and get the code cover the else part in MainActivity class?
Also is this possible with any kind of mocking framework?

Not that I have much experience with this sort of thing but you could try Mockito.
Noticed it in the examples when integrating Dagger dependency injection to my app.

Related

assertion- problems with internal call

hi guys Im having some problems with my frist Testing
im writing this snippet but i keep get this problem:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at org.junit.Assert.assertNotNull(Assert.java:722)
someone know hot to help me? and maybe also which are the correct thing to test in this class? thanks a lot
I already have Junit implementation in gradle
the test class is :
public class QrActivityTest {
public QrActivity tester;
#Before
public void setUp(){
tester = new QrActivity();
}
#Test
public void onCreate() {
//barcodeDetector = new BarcodeDetector.Builder(tester.getApplicationContext()).setBarcodeFormats(Barcode.QR_CODE).build();
// Assert.assertNotNull(barcodeDetector);
Assert.assertNotNull(tester);
Assert.assertNotNull(tester.cameraSource);
}}
the class is:
public class QrActivity extends AppCompatActivity {
SurfaceView surfaceView;
CameraSource cameraSource;
TextView textView;
BarcodeDetector barcodeDetector;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_scanner_layout);
surfaceView = (SurfaceView) findViewById(R.id.camera);
textView = (TextView) findViewById(R.id.txt);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this, barcodeDetector).setRequestedPreviewSize(640, 480).setAutoFocusEnabled(true).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(QrActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(holder);
} catch (IOException e) {
Toast.makeText(QrActivity.this, "errore fotoamera", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
//this is to take data
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(300);
textView.setText(qrCodes.valueAt(0).displayValue);
if (qrCodes.valueAt(0).displayValue.equals("129063")) {
Intent intent = new Intent(QrActivity.this, AttrezzaturaRecycleView.class);
startActivity(intent);
Utility.showToast(QrActivity.this, "Dispositivo trovato!");
}
}
});
}
Assertions check internal the values. If the assertion isn't met they throw an exception. So you might check the full stack trace.
The exception probably occur in the line Assert.assertNotNull(tester.cameraSource);. This is caused because cameraSource will be null. This is caused because you only create an instance of the class but no Events like onCreate are called. A simple Unit test isn't enough for front end testing.
You might need an instrumented test case. Pleas try to use the JUnit testrules to instantiate the Activity. Concider that you need a device or emulator to run this tests.
As #finder2 sais, the problem is, that tester.cameraSource is null.
I think, this is because the method onCreate() is never executed.
You may start your Application like normal or run onCreate by using Reflection.
You could also move the necessary code inside the constructor or a public method.

How to send event from MainActivity onCreate to React Native?

I'm working on an alarm clock and I can't figure out how to sendEvent to React Native from MainActivity. This is what I managed to do so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
mInitialProps = new Bundle();
final Bundle bundle = mActivity.getIntent().getExtras();
ReactInstanceManager mReactInstanceManager = getReactNativeHost().getReactInstanceManager();
ReactApplicationContext context = (ReactApplicationContext) mReactInstanceManager.getCurrentReactContext();
if (context == null) {
mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
public void onReactContextInitialized(ReactContext context) {
if (bundle != null && bundle.containsKey("sendAlarm")) {
if (bundle.getString("sendAlarm").equals("sendAlarmOn")) {
LauncherModule.startAlarm(mActivity); // works
LauncherModule.sendAlarmEvent(); // doesn't work. Should run after alarm manager starts app which previously had been killed
}
}
}
});
} else {
if (bundle != null && bundle.containsKey("sendAlarm")) {
if (bundle.getString("sendAlarm").equals("sendAlarmOn")) {
LauncherModule.startAlarm(mActivity); // works
LauncherModule.sendAlarmEvent(); // works and sends event only when app was left open
}
}
}
super.onCreate(savedInstanceState);
}
The code works only If app is left open and alarm manager restarts app itself. If I close the app and alarm manager starts it then it seems that only startAlarm function (it has sound effect) is beeing triggered..
No matter what I do whether I put sendEvent function inside Mainactivity or elsewhere (e.g. external module) it simply won't send event if I close the app. I also tried getReactInstanceManager().getCurrentReactContext() combined with while from this question Send data from Android activity to React Native to no avail.
Also tried to create bolean beeing set to true onCreate and then send event onStart or onRestart. Also to no avail.
Any suggestions?
EDIT: Here is how sendEvent function looks like:
public final void sendEvent(String eventName, boolean isAlarmOn) {
getReactInstanceManager().getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, isAlarmOn);
}
SOLUTION
Well I think that the answer is not to use sendEvent method onCreate because (I might be wrong) listener seems to be initialized after the event had been sent. So nothing is going to listen to this event.
It seems to work pretty well inside onStart, onRestart, onPause though.
What can we do? React Native provides ReactActivityDelegate with initial props. And it does the job!
ReactActivityDelegate in MainActivity should look as below:
public class ActivityDelegate extends ReactActivityDelegate {
private Bundle mInitialProps = null;
private final #Nullable Activity mActivity;
public ActivityDelegate(Activity activity, String mainComponentName) {
super(activity, mainComponentName);
this.mActivity = activity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
mInitialProps = new Bundle();
final Bundle bundle = mActivity.getIntent().getExtras();
if (bundle != null && bundle.containsKey("sendAlarm")) {
if (bundle.getString("sendAlarm").equals("sendAlarmOn")) {
mInitialProps.putBoolean("alarmOn", true);
}
}
super.onCreate(savedInstanceState);
}
#Override
protected Bundle getLaunchOptions() {
return mInitialProps;
}
};
#Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ActivityDelegate(this, getMainComponentName());
}
Then in your main app component (usually index.android.js) call your propTypes and use them to run your code:
static propTypes = {
alarmOn: PropTypes.boolean
}
componentDidMount() {
if (this.props.alarmOn === true) {
// your code
}
}
Voila!
You can find full example here: https://github.com/vasyl91/react-native-android-alarms

FusedLocationProviderClient.removeLocationUpdates always returns failure

I have an activity that extends a base class called LocationAwareActivity all this LocationAwareActivity activity does is creates a location service client
LocationServices.getFusedLocationProviderClient and listens to
location updates.
Source for this activity is here
https://github.com/snijsure/MultiActivity/blob/master/app/src/main/java/com/example/subodhnijsure/multiactivity/LocationAwareActivity.java
And when activity is destroyed it calls removeLocationUpdates . What I am finding is
removeLocationUpdate returns a task that always returns not-successful
More concerning is because location activities is not removed, the activity is not getting being garbage collected.
- So if I start the any activity that inherits from LocationAwareActivity that activity always stays on heap.
So the question is what is the correct way to stop receiving location updates thus allowing activity to be garbage collected.
Entire source for this project can be accessed here - https://github.com/snijsure/MultiActivity
In removeLocationUpdates you should pass locationCallback, current implementation is wrong.
Still, there is chance of memory leak somewhere else. You should try integrating Leakcanary in your app and it can give you reference tree and will tell you which field or listener is causing this memory leak.
You can refer one of my only blog post here
public void stopLocationUpdates() {
if (locationProviderClient != null) {
try {
final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);
if (voidTask.isSuccessful()) {
Log.d(TAG,"StopLocation updates successful! ");
} else {
Log.d(TAG,"StopLocation updates unsuccessful! " + voidTask.toString());
}
}
catch (SecurityException exp) {
Log.d(TAG, " Security exception while removeLocationUpdates");
}
}
}
Hi #Subodh Nijsure Please check below code and paste into your code and after checked it:
final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);
voidTask.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.e(TAG, "addOnCompleteListener: "+task.isComplete());
}
});
voidTask.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.e(TAG, "addOnSuccessListener: " );
}
});
voidTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "addOnFailureListener: ");
}
});
I think voidTask.isSuccessful() this method is not working when you put this listener at that time it working fine and i also see into memory it's release all memory when come to previous Activity.
And when you are redirecting to any activity then please stopLocationUpdates() called once into onPause() and remove from other method like onDestroy(),onStop() because it stop once so why should we call multiple time.
Hope this helps you.
By looking at the code in the repository I discovered some issues in your design that maybe cause the leaking of your Activity.
1) You are using two different LocationCallbacks. One in the start and one in the stop method, but you should actually use the same. So one time instantiating it would be sufficient and would lead probably also to a successful result of your Task when removing the LocationCallback.
2) Since your instantiating the LocationCallback twice with an Anonymous Class you are keeping a non-static reference of an inner class even if you finish the containing class and this causes your Memory Leak. You can read more about this here.
3) IMHO it is better to use a separate manager class for handling your location requests than abstracting an Activity.
That said here is my...
Solution
GpsManager.java
public class GpsManager extends LocationCallback {
private FusedLocationProviderClient client;
private Callback callback;
public interface Callback {
void onLocationResult(LocationResult locationResult);
}
public boolean start(Context context, Callback callback) {
this.callback = callback;
client = LocationServices.getFusedLocationProviderClient(context);
if (!checkLocationPermission(context)) return false;
client.requestLocationUpdates(getLocationRequest(), this, null);
return true;
}
public void stop() {
client.removeLocationUpdates(this);
}
#Override
public void onLocationResult(LocationResult locationResult) {
callback.onLocationResult(locationResult);
}
private boolean checkLocationPermission(Context context) {
int permissionCheck = ContextCompat.checkSelfPermission(
context, android.Manifest.permission.ACCESS_FINE_LOCATION);
return permissionCheck == PackageManager.PERMISSION_GRANTED;
}
private LocationRequest getLocationRequest() {
return LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(30_000L)
.setFastestInterval(20_000L);
}
}
and calling this from your Activity like this
YourActivity.java
public class MapsActivity extends AppCompatActivity implements GpsManager.Callback {
private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;
private GpsManager mGpsManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mGpsManager = new GpsManager(getApplicationContext(), this);
// check if user gave permissions, otherwise ask via dialog
if (!checkPermission()) {
getLocationPermissions();
return;
}
mGpsManager.start();
...
}
#Override
protected void onStop() {
super.onStop();
mGpsManager.stop();
}
#Override
public void onLocationResult(LocationResult locationResult) {
// do something with the locationResult
}
// CHECK PERMISSIONS PART
private boolean checkPermission() {
return isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)) &&
isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION));
}
#TargetApi(Build.VERSION_CODES.M)
private void getLocationPermissions() {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_FINE_LOCATION);
}
#Override
public void onRequestPermissionsResult(int code, #Nullable String permissions[], #Nullable int[] results) {
switch (code) {
case PERMISSION_REQUEST_FINE_LOCATION:
if (isPermissionGranted(results)) {
getLocationRequest();
}
}
}
private boolean isPermissionGranted(int[] results) {
return results != null && results.length > 0 && isGranted(results[0]);
}
private boolean isGranted(int permission) {
return permission == PackageManager.PERMISSION_GRANTED;
}
}
This is just a guess because I didn't try your code but the solution should help you anyways. Please correct me if I'm wrong ;)
The reason why the Task object returns false is in your stopLocationUpdates method, you are again creating a local **LocationCallback** reference and then using this reference to as an argument in locationProviderClient.removeLocationUpdates(cL);
where your local LocationCallBack is never present in the locationProviderClient
So what you have to do is , instead of creating another LocationCallBack object ,you have to pass the same global object which you are instantiating in your startLocationUpdates method
your code should be like this
final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);

show app lock pattern dialog when unlocking the phone

I have MainActivity and on its onResume method I call pattern lock to create and confirm user identity. User visits and leave this MainActivity back and forth while active on the app as well as when phone is in sleep mode and user unlocks it. These both scenarios will call onRestart, onStart and onResume methods, but I only want to revoke the pattern in unlock scenario.
handlePattern() method needs a proper distinguishing to be called.
How to distinguish this when I call the handlePattern method ?
MainActivity.class
onCreate(){}
onResume(){
//help needed to know that user is just visiting activity in app back and forth
or came back after unlocking the screen.
if(isPatternCallRequired){
handlePattern()
}
}
In your onStop() method call you can check if the player is in sleep mode and cache the boolean.
PowerManager pm = (PowerManager)
_context.getSystemService(Context.POWER_SERVICE);
boolean isInSleepMode = !pm.isScreenOn();
Check for the build version
if( Build.VERSION.SDK_INT >= 20)
// use isInteractive()
else
// use isScreenOn()
in onRestart which will get called when you resume from sleep - based on the cached value you can show the pattern to unlock.
You may need to reset the cached value once you are done using it.
onResume may not be a right API for the call as it will be called even when your activity loads.
Edited answer based on your comment
You can try ActivityLifecycleCallbacks too like this,
First, Register your Application in your Application class.
public class StackApp extends Application {
private static final String TAG = StackApp.class.getSimpleName();
public static final String INTENT_ACTION_APP_STATE_CHANGE = "intent_action_app_state_change";
public static final String INTENT_DATA_IS_IN_BACKGROUND = "intent_data_is_in_background";
private static int mNumRunningActivities = 0;
private static AtomicBoolean mIsAppInForeground = new AtomicBoolean();
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 14) {
// registerActivityLifecycleCallbacks is supported only from the SDK version 14.
registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
mNumRunningActivities++;
if (mNumRunningActivities == 1) {
notifyAppState(false);
Log.i(TAG, "APP IN FOREGROUND");
}
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
mNumRunningActivities--;
if (mNumRunningActivities == 0) {
notifyAppState(true);
}
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
}
/**
* To notify App state whether its in ForeGround or in Background
*
* #param isInBackground
*/
private void notifyAppState(boolean isInBackground) {
if (isInBackground) {
mIsAppInForeground.set(false);
} else {
mIsAppInForeground.set(true);
}
sendAppStateChangeBroadcast(isInBackground);
}
public static boolean isInForeground() {
return mIsAppInForeground.get();
}
private void sendAppStateChangeBroadcast(boolean isInBackground) {
Log.i(TAG, "sendAppStateChangeBroadcast - isInBackground : " + isInBackground);
Intent intent = new Intent();
intent.setAction(INTENT_ACTION_APP_STATE_CHANGE);
intent.putExtra(INTENT_DATA_IS_IN_BACKGROUND, isInBackground);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And register the broadcast and listen whether the App is going background or foreground like this Sample Activity example
public class SampleMyActivity extends AppCompatActivity {
private OnAppStateReceiver mAppStateReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_my);
mAppStateReceiver = new OnAppStateReceiver();
IntentFilter filter = new IntentFilter(StackApp.INTENT_ACTION_APP_STATE_CHANGE);
LocalBroadcastManager.getInstance(this).registerReceiver(mAppStateReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mAppStateReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mAppStateReceiver);
}
}
private class OnAppStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!TextUtils.isEmpty(action) && StackApp.INTENT_ACTION_APP_STATE_CHANGE.equalsIgnoreCase(action)) {
boolean isGoingBackground = intent.getBooleanExtra(StackApp.INTENT_DATA_IS_IN_BACKGROUND, false);
if (isGoingBackground) {
//Your app is not vissible to the use
} else {
// App is visible to the user.
}
}
}
}
}
Note: If you want to listen in Multiple Activity you can create a base
class and add the listener there and you can do the operation, In that
case you can reduce a lot of code.

Access from AsyncTask to Application Class or any other Global variables from any Classes

I can't access from AsyncTask to Application Class, or issue with SharedPreferences with last updated data, etc..
Basically why I need my Global variable is to keep track currently active activity, and it should be accessable from any type of class, like Activity, AsyncTask, Service, Receiver, Application, Etc...
I know there is lot of questions=answers in here, but none of those helped me.
I tried several ways to do this, but couldn't find any real resolution for this.
With SharedPreferences, I can use it, but after preferences updated and readed, returned previous value, works only after restart app.
With Application Class, no luck, can't access to Application from AsyncTask and service
Service runs AsyncTask on every 5sec, and AsyncTask should know if MainActivity is opened and running, so it can update contents to it.
I got pretty much everything working but, with this, I spend way too many hours on searching.
So please, if anybody can help me with this, it would be nice. :)
Here is little example how I do..
MainActivity.java
public class MainActivity extends Activity {
private boolean active = false;
SharedPreferences prefs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
this.prefs = context.getSharedPreferences("com.my.app", Context.MODE_PRIVATE);
storeActivity("MainActivity");
this.active = true;
((App) this.getApplication()).setTopActivity("MainActivity");
}
public void storeActivity(String TOP_ACTIVITY) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("TOP_ACTIVITY", TOP_ACTIVITY);
editor.apply();
editor.commit();
}
#Override
public void onResume() {
super.onResume();
((App) this.getApplication()).setTopActivity("MainActivity");
this.active = true;
storeActivity("MainActivity");
}
#Override
public void onPause() {
super.onPause();
((App) this.getApplication()).setTopActivity("");
this.active = false;
storeActivity("");
}
#Override
public void onStart() {
super.onStart();
((App) this.getApplication()).setTopActivity(ACTIVITY_NAME);
this.active = true;
storeActivity("MainActivity");
}
#Override
public void onStop() {
super.onStop();
((App) this.getApplication()).setTopActivity("");
this.active = false;
storeActivity("");
}
}
Here is my Application Object,
App.java
public class App extends Application {
private String TOP_ACTIVITY;
public String getTopActivity() {
return TOP_ACTIVITY;
}
public void setTopActivity(String CURRENT_ACTIVITY) {
this.TOP_ACTIVITY = CURRENT_ACTIVITY;
}
public static Application getApplication() {
return new App();
}
}
And here is some AsyncTask getting information from server
Socket.java
public class SocketUpdater extends AsyncTask<String,Void,String> {
private Context context;
private SharedPreferences prefs;
public SocketUpdater(Context context) {
this.context = context;
this.prefs = context.getSharedPreferences("com.my.app", Context.MODE_PRIVATE);
}
#Override
protected String doInBackground(String... arg0) {
StringBuffer result = new StringBuffer("");
return new String(result);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, "RESULT: " + result, Toast.LENGTH_SHORT).show();
String TOP_ACTIVITY = ((App) this.getApplication()).getTopActivity();
// THIS CANT WORK, NO this.getApplication()!!!
boolean MainActivityActive = MainActivity.active;
// THIS RETURNS ME FALSE ALL THE TIME
SharedPreferences.Editor editor = prefs.edit();
String PREF_TOP_ACTIVITY = prefs.getString("TOP_ACTIVITY", "");
if(MainActivityActive) {
Toast.makeText(context, "NEVER FIRES!", Toast.LENGTH_LONG).show();
}
if(TOP_ACTIVITY.equals("MainActivity")) {
Toast.makeText(context, "NEVER FIRES!", Toast.LENGTH_LONG).show();
}
if(PREF_TOP_ACTIVITY.equals("MainActivity")) {
Toast.makeText(context, "NEVER FIRES!", Toast.LENGTH_LONG).show();
}
}
}
Why not use "Otto" library from Square? You can send objects with ease between activity and service. I'm using it within my application for similar purpose.
I spent days for searching what causes the problem.
I found simple solution for this, and got all methods working like I wanted.
The thing was that I had my service running own separated process like this:
<service android:name="fi.hgs.apps.MyService"
android:process=":myService"
</service>
And just removed android:process=":myService" from AndroidManifest.xml

Categories

Resources