Context in android - java

i am a newbie.Please explain what all things are passed through a context.Like when constructing an object for the following class..
public class myclass{
public myclass (Context context){....}
}

You get a lot of possibilities to check for or change System or application properties.
You will find a detailed version of all the functions that are available with the context in the api documentation of android:
http://developer.android.com/reference/android/content/Context.html
So you will be able for example to start a service (to run part of the application in the background) through context.startService(Intent service). You'll need to pass an Intent (if you don't know what an intent is I would read the Dev Guide: http:**developer.android.com/guide/topics/fundamentals.html first. You could do that anyway, there are plenty of good descriptions and examples.).
Sorry for the crippled link, I'm not allowed to post more than one link per post...

Related

Android looped at OnMAMCreate method

I try to incorporate Intune app protection policies into my native Android app. I follow instructions from https://learn.microsoft.com/en-us/intune/app-sdk-android. After I changed all classes into their MAM equivalents, my app looped at MAMApplication's onMAMCreate method. My main class derived from MAMApplication class instead of Application class.
Below is my method:
#Override
public void onMAMCreate() {
super.onCreate();
buildObjectGraphAndInject();
setOrmProject(null);
setOrmTemplate(null);
//rest of method
}
And there is a message I got in debug console.
I/MAMInfo: Agent config file does not exist, will use test agent
I/MAMInfo: MAMInfo initialized. Debug=true, UseTestAgent=true,
ManagedDialogDisabled=false, DeprecationDialogDisabled=false,
PolicyRequired=false, MultiIdentityEnabled=false,
FullBackupContent=true, UseDefaultEnrollment=false,
ExceptionOnInit=false
I/MAMWERetryScheduler: task thread waiting for tasks.
I/MAMComponents: Not initializing MAM classes because the MDM package
is not installed.
I/MAMComponents: Not initializing MAM classes because the MDM package
is not installed.
Application do not throw an exception, it just looped at that method and stuck.
I read that MDM is not required to use MAM classes. Have anybody go any idea how to resolve that problem?
Bit of a late answer here - I've only just starting using the SDK myself, but you need to call super.onMAMCreate() which in turn will call super.onCreate() internally.

Android 25 Java : Using methods that require Context in a different Class - Require assistance

I created a simple little directory listing method in the default MainActivity.class
I was able to get it to function the way I wanted it to, however, when I moved the method to a different class and called it in MainActivity, I wound up getting a lot of Context Errors all over the place. After searching the web I am stumped and require assistance.
The code where it errors out is for the Context for FileArray:
(public class Utilities extends Activity)
arrayAdapter = new FileArrayAdapter(getApplicationContext(),R.layout.custom_explorer,dir);
Method Name:
public void listDirectories(ListView listView, File directory)
It errors out on the getApplicationContext, this method worked just fine in MainActivity.
I have not implemented Fragments to MainActivity yet, wanted to get the working functionality first then spread out for OOP; then call by Fragment.
Hope someone can help, any further info I am happy to share.
Thank you for the timely response: ρяσѕρєя K & Nilabja.
Ya I guess it just needed another person to suggest feeding Context as a param. I did that once but it did not work so I passed it off, attempted once again from Nilabja suggestion. Yip that was the solution.
utilities.ListDirectory(mainList, root, getApplicationContext());
public void listDIR(ListView listView, File directory, Context setContext)

AIDL registerCallback() google docs

google docs have a tutorial on how to make an AIDL service. However, when I tried to do the same, I got an error "The method registerCallback(IRemoteInterface) is undefined for the type IRemoteInterface.
I have not seen this "registerCallback" method in any tutorial that I have been googling and my question is why is this not working/why do other places not use it?
I feel like part of my issue is a fundamental misunderstanding about services and their 'callback' to send information to what it is bound to it.
Thanks!
AIDL:
package com.mine.ben;
import com.mine.servicenexus.RelPoint;
interface IRemoteInterface {
Location getLastLocation();
RelPoint getRelPoint();
int logControlActivity(in String text,in int severity);
int getRunningStatus();
}
Updated question:
I get a syntax error in my AIDL file when i add
void registerCallback(IRemoteServiceCallback);
void unregisterCallback(IRemoteServiceCallback);
I have cleaned my workspace and it builds automatically. Is this a problem with the gen file?
Few lines from my application:
interface IGpsService {
Bundle getNavigationMessage();
void resetStatistics();
void recordingEnable(boolean recordingEnabled, boolean continueLastTrack);
void registerCallback(IGpsChanged cb);
void unregisterCallback(IGpsChanged cb);
boolean isRecordingEnabled();
void setGhost(int trackId);
void startGhost();
void sendUserEvent(int eventId);
}
second file for calback interface itself:
interface IGpsChanged{
oneway void onLocationChanged(out Bundle message);
}
Best of all - usually you do not need those .aidl definitions. This is necessary only when exposing service methods outside of the application.
It's also helpful to understand how it works - forst aidl defines basic service's methods. registerCallback is not a "special" method, it's as oridinary as any other, just enables defining callbacks for two-way communication (in this particular case - to send some position info from sesrvice to binded activity (or other component).
As you mentioned in comment - you do not want to create service, just consume some service from outside of application. In that case you need those external aidl file, not the one written by you. Stubs for consuming service's method will be generated in the /gen directory.
google docs have a tutorial on how to make an AIDL service.
That is not a tutorial. It is just ordinary documentation.
However, when I tried to do the same, I got an error "The method registerCallback(IRemoteInterface) is undefined for the type IRemoteInterface.
That is because you do not have a method named registerCallback() in your AIDL.
I have not seen this "registerCallback" method in any tutorial
It is not in a tutorial. The only occurrences of registerCallback() in the Web page that you linked to are from "some sample code demonstrating calling an AIDL-created service, taken from the Remote Service sample in the ApiDemos project". The ApiDemos project is in your SDK installation, if you elected to download sample code from the SDK Manager.
Code example from AIDL guide that you have referenced is taken from the Remote Service sample in the ApiDemos project.
And registerCallback() in it is implemented by using android.os.RemoteCallbackList<E extends android.os.IInterface> object.
Make an .aidl file like:
package com.example;
oneway interface IRemoteServiceCallback {
/**
* Goes to client.
*/
void valueChanged(int value);
}
Make another .aidl file where you import this interface and use it as a method's parameter like:
package com.example;
import com.example.IRemoteServiceCallback;
interface IRemoteService {
/**
* Goes to service.
*/
void registerCallback(IRemoteServiceCallback cb);
}
Generate code from .aidl on both sides.
Implement IRemoteService.Stub in service and return it in onBind()
Implement IRemoteServiceCallback.Stub in client and pass it in ServiceConnection's onServiceConnected() callback to the received from IRemoteService.Stub.asInterface() instance of IRemoteService.
Now you service can talk back to the client over the passed IRemoteServiceCallback implementation.

Testing SQLiteOpenHelper subclass with JUnit

I am writing JUnit tests for my Android app. I have read through the Android developer resources (testing fundamentals, Spinner example test, etc.). Now I want to test my SQLiteOpenHelper subclass independently of the Activities which use it. My idea is to extend ActivityInstrumentationTestCase2<Activity>. Is it okay to simply use Activity as the generic parameter or do I need a subclass? Also, am I headed in the right direction here, or is there a better way to test my SQLiteOpenHelper subclass?
I was looking for an answer to exactly this problem, and found this link as well as another interesting related question here:
Android JUnit test for SQLiteOpenHelper
The accepted answer by #Pietro shows some simple code, using a basic AndroidTestCase, which will help directly to answer the question.
public class DatabaseTest extends AndroidTestCase {
private MyDatabase db;
public void setUp(){
RenamingDelegatingContext context
= new RenamingDelegatingContext(getContext(), "test_");
db = new MyDatabase(context);
}
public void testAddEntry(){
// Here I have my new database which is not connected to the standard database of the App
}
public void tearDown() throws Exception{
db.close();
super.tearDown();
}
}
I was happy at how simple it looks. In my case I'm new to Android testing, so even the simple stuff seems difficult at the moment.
But the interesting part which is key, is using the RenamingDelegatingContext class as your "context" instead of just using a normal context. This seems to build on the comments made by #Jens.
This class wraps a given context and delegates most operations to that context. The useful part is that it performs database and file operations with a renamed database/file name (see documentation online).
This allows your TEST code to use an actual different instance of the database to your PRODUCTION code - at least in my case this is going to be useful.
Here is another related post where the accepted answer says pretty much the same thing:
Testing database on Android: ProviderTestCase2 or RenamingDelegatingContext?
Some useful tips in there about using ContentProvider instead (but that's a different issue for another day).
following link talk about testing in android:
http://developer.android.com/tools/testing/testing_android.html
may be you have already seen it just posting it in case you have missed going through it.. it is a very good resource to learn about junit in android...
For testing with Android Studio,
You should use MockContext instead of RenamingDelegatingContext.
If you use RenamingDelegatingContext, You would get context as null.
For AndroidTestCase, getContext() would return null. And for InstrumentationTestCase, getInstrumentation().getContext() would return null.
For further information, see this answer. https://stackoverflow.com/a/29063736/1020456

Can't use a public static method?

This is confusing. I'm look at the Android 2.2.2_r1 source code for the NotificationManager class, and I see the method getService() which is defined as public and static. However, eclipse is telling me:
The method getService() is undefined for the type NotificationManager
on the line
Object o = NotificationManager.getService();
My project is building against Android 2.2/ API Level 8. I tried to use reflection to see the method names and modifiers, and sure enough, I got back
public static getService
Am I missing something here? Why would eclipse tell me this method doesn't exist?
You will find a very detailed answer in this post.
In short: Because you compile against the android.jar, which has all hidden methods (like the one you are trying to access) removed. They will only be there on runtime, for internal android usage.
But since you perhaps also need it. The right way to access the NotificationManager is via the getSystemService method of a context:
NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
With context being a valid context (like your current activity).

Categories

Resources