[英]Calling a messenger bound service from android Library
I am trying to make a custom android library.我正在尝试制作一个自定义 android 库。
Calling My LIb as:将我的 LIb 称为:
mylib = new Mylib();
JSONObject dict = new JSONObject();
dict.put("Daata",1);
mylib.initialize(dict);
Mylib code: Mylib 代码:
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.我想启动一个非活动 class 可以启动信使客户端与另一个应用程序交互。 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
.因此,我尝试将 Mylib class 扩展为
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 );
我通过时看到类似的错误:
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 );
现在我在 Mylib class 的构造函数中将应用程序上下文作为参数传递并运行:
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);
所以,我做了
context.startActivity(intent);
and it worked for an activity class.它适用于活动 class。
But what if the Mysecondlib is also a non-activity class and I want to start a messenger client side in the Mysecondlib.但是,如果 Mysecondlib 也是非活动 class 并且我想在 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
几乎没有什么改变:
Replaced the bindservice with context.bindservice
But Still unable to receive info from the server side.但仍然无法从服务器端接收信息。
Thanks a lot非常感谢
Solved it:解决了它:
Add delay in the execution of service.send()
在
service.send()
的执行中添加延迟
So the solution:所以解决方案:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mservice.send(msg)
}
}, 1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.