2015-11-07 140 views
-1

這是我廣播接收器類,我想調用一個方法(重新連接();)在我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

回答

0

創建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

相關問題