[英]starting BroadcastReceiver or IntentService from non-activity class
如何從非活動類啟動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謝謝
要啟動服務,您需要上下文實例。 您可以將其作為構造函數參數傳遞:
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);
}
});
或者您可以通過二傳手設置上下文
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.