调用活动的方法从广播接收器的Android

问题描述:

这是我广播接收器类,我想调用一个方法(重新连接();)在我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> 
+0

使用EventBus库来代替您的代码! – Eenvincible

+0

选中此链接(http://androhub.com/android-detect-internet-connection-using-broadcast-receiver/)。 –

+0

以不同的动作发送来自广播接收器的广播,该动作将在活动中接收广播接收器。在广播接收器内部的那个方法中 – skyshine

创建ConnectionStablizerReceiver类作为活动的内部类。它将工作

public class Splash_screen extends Activity { 
    private static int SPLASH_TIME_OUT = 4000; 
    Global global; 
    SharedPreferences pref; 
    String base_url_final=""; 
    private static String checkurlonetag ="sdfasdf"; 
    private static String checkurltwotag ="sdfasdfgsdfhsfdhasdf"; 




// Dbhelper dbhelper; 
    @Override 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_splash_screen); 
     global= (Global) getApplicationContext(); 


    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.splash_screen, menu); 
     return true; 
    } 





    class ConnectionStablizerReceiver extends BroadcastReceiver{ 


     @Override 
     public void onReceive(Context context, Intent intent) { 


//dont forget to register reciver permision 

if(intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")){ 
      //do your onreceive action 
     } 



     } 
    } 

} 
+0

请填写完整代码段? – MaggotSauceYumYum

+0

检查已编辑的答案。 –

+0

它在检测到网络更改时强制关闭 – MaggotSauceYumYum