這是我廣播接收器類,我想調用一個方法(重新連接();)在我MainActivity與顯示「連接如迷失一起!嘗試重新連接..「toast調用活動的方法從廣播接收器的Android
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;
public class ConnectionStablizerReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(isConnected(context)) Toast.makeText(context, "Connection Established!", Toast.LENGTH_SHORT).show();
else Toast.makeText(context, "Conection Lost! trying to reconnect..", Toast.LENGTH_LONG).show();
}
public boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
}
<receiver android:name="com.example.broadcastreceiversample.MyReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
使用EventBus庫來代替您的代碼! – Eenvincible
選中此鏈接(http://androhub.com/android-detect-internet-connection-using-broadcast-receiver/)。 –
以不同的動作發送來自廣播接收器的廣播,該動作將在活動中接收廣播接收器。在廣播接收器內部的那個方法中 – skyshine