如何从非活动类启动BroadcastReceiver或IntentService
开始我的意思是发送意图并运行BroadcastService或IntentService
即:
我上课了:
public class NumberOne{
@Override
public int functionOne(){
int i = 1 + 4;
if(/*something is true*/){
Intent intent = new Intent(this,intetServiceOne.class);
intent.putExtra("id","path");
context.startService(intent);
}
else {/*continue*/
}
return i;
}
//other functions
}
如果functionOne中的条件为true,则启动IntentService
public class IntentServiceClassOne extends IntentService {
public IntentServiceClassOne () {
super("IntentServiceClassOne ");
}
@Override
protected void onHandleIntent(Intent intent) {
String data = intent.getStringExtra("id");
Log.d("dataIs: ", data);
}
//more functions what to do
}
它不依赖于它是IntentService还是BroadcastReceiver 感谢
答案 0 :(得分:2)
启动服务您需要上下文实例。您可以将其作为构造函数参数传递:
public class NumberOne{
Context context;
public NumberOne(Context context){
this.context = context;
}
public int functionOne(Context context){
int i = 1 + 4;
if(/*something is true*/){
Intent intent = new Intent(this,intetServiceOne.class);
intent.putExtra("id","path");
context.startService(intent);
}
else {/*continue*/
}
return i;
}
//other functions
}
您不必传递Activity实例,Context就足够了。它可以是应用程序上下文。您可以通过getApplicationContext()
方法获取它
您还可以在Application对象中创建静态实例并从中获取它:
public class YourApplication extends Application {
public static YourApplication INSTANCE;
public void onCreate(){
super.onCreate();
INSTANCE = this;
}
}
你的课程将如下所示。
public class NumberOne{
public int functionOne(Context context){
int i = 1 + 4;
if(/*something is true*/){
Intent intent = new Intent(this,intetServiceOne.class);
intent.putExtra("id","path");
YourApplication.INSTANCE.startService(intent);
}
else {/*continue*/
}
return i;
}
//other functions
}
但不是好的解决方案。
最后你可以创建回调监听器并在你的类中设置它,如下所示:
public class NumberOne{
//add setter
YourListener yourListener;
public int functionOne(Context context){
int i = 1 + 4;
if(/*something is true*/){
if(yourListener != null){
yourListener.onFunctionOneCall();
}
}
else {/*continue*/
}
return i;
}
//other functions
public interface YourListener{
void onFunctionOneCall();
}
}
还有一些你有上下文的地方 - 例如在活动中:
numberOneInstance.setYourListener(new YourListener(){
@Override
public void onFunctionOneCall(){
Intent intent = new Intent(this,intetServiceOne.class);
intent.putExtra("id","path");
this.startService(intent);
}
});
或者您可以通过setter设置上下文
public class NumberOne{
Context context;
public setContext(Context context){
this.context = context;
}
public int functionOne(Context context){
int i = 1 + 4;
if(/*something is true*/){
if(context != null){
Intent intent = new Intent(this,intetServiceOne.class);
intent.putExtra("id","path");
context.startService(intent);
}
}
else {/*continue*/
}
return i;
}
//other functions
}