我正在实施一个广播接收器来检查连接性。我想从接收器的 onReceive 方法调用服务的方法。
如何从接收器调用服务方法?
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if ((intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)))) {
boolean status = NetworkUtil.isOnline(context);
if (status) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
// Here I want to invoke a method in the service to consume api and check new results ;
updateAllWidgets(context, appWidgetManager, appWidgetIds);
}
Toast.makeText(context, "Network change " + msg, Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
如果您愿意开始不需要执行UI操作的长时间操作,您可以使用IntentService
代替Service
,因为Service
会运行在MainThread
。
比如说你的服务就像 -
public class MyActionService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
// Data will be available in intent
// Normally we would do some work here, like download a file.
}
}
您可以使用
开始服务startService(new Intent(context, MyActionService.class));
一旦你开始服务,你的onHandleIntent()
就会被召唤,如果你愿意做任何手术,这就是你做的地方
答案 1 :(得分:0)
找到解决方案
创建BroadcastReciever
public class NetworkInfoReceiver extends BroadcastReceiver {
NetworkInfoListener infoListener;
@Override
public void onReceive(Context context, Intent intent) {
if (null != intent) {
try {
infoListener = (NetworkInfoListener) context;
if (infoListener != null) {
infoListener.onNetWorkStatusChange(LegionUtils.isOnline(context));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2.Create Interface
public interface NetworkInfoListener {
void onNetWorkStatusChange(boolean isConnected);
}
在您的活动中注册接收者onResume()
public static void doRegisterConnectivityReceiver(NetworkInfoReceiver receiver, Context context) {
try {
if (receiver != null && context != null) {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(receiver, filter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
当您在活动中实施NetworkInfoListener时,以下覆盖方法将在网络更改时调用
@Override
public void onNetWorkStatusChange(boolean isConnected) {
LegionUtils.doUpdateNetworkStatus(ShiftDropSucessActivity.this, offlineTv, isConnected);
}
在您的活动中取消注册BroadcastReciver
public static void doUnRegisterConnectivityReceiver(Context context, NetworkInfoReceiver networkInfoReciver) {
try {
if (networkInfoReciver != null && context != null) {
context.unregisterReceiver(networkInfoReciver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
我按照以下步骤解决了这个问题: