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

时间:2015-11-07 10:01:27

标签: android

这是我的广播接收器类,我想在我的 MainActivity 中调用一个方法( reconnect(); )并显示“Conection Lost!试图重新连接..”吐司

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>

1 个答案:

答案 0 :(得分: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
        }



        }
    }

}