Darth Vader
Darth Vader

Reputation: 921

Calling a messenger bound service from android Library

I am trying to make a custom android library.

Calling My LIb as :

            mylib = new Mylib();
            JSONObject dict = new JSONObject();
            dict.put("Daata",1);
            mylib.initialize(dict);

Mylib code:

public class Mylib  {

    public Mylib() {
    }

    public void initialize(JSONObject message) throws ParseException {
        System.out.println(message);
        System.out.println("done");
    }

}

Problem :

I want to start a non-activity class which can start messenger client side to interact with another app. So I tried this :

Intent intent = new Intent( Mylib.this , MySecondLib.class );

I got this:

Cannot resolve constructor error

So, I tried extending my Mylib class to extends AppCompatActivity. and writing

        Intent intent = new Intent( Mylib.this , MySecondLib.class );
        startActivity(intent);

and got this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

I see similar error when I pass: Intent intent = new Intent( getApplicationContext() , MySecondLib.class );

Now I pass the application context as parameter in the constructor of the Mylib class and run this :Intent intent = new Intent( context , MySecondLib.class ); But I still get the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

So, I did context.startActivity(intent); and it worked for an activity class.

But what if the Mysecondlib is also a non-activity class and I want to start a messenger client side in the Mysecondlib.

So, I tried .. the official sample Client side code for messenger service.

Few changes had to be made: Replaced the bindservice with context.bindservice

But Still unable to receive info from the server side.

Thanks a lot

Upvotes: 4

Views: 254

Answers (1)

Darth Vader
Darth Vader

Reputation: 921

Solved it :

Add delay in the execution of service.send()

So the solution:

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                mservice.send(msg)
            }
        }, 1000);

Upvotes: 2

Related Questions