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



这是我的广播接收器类,我想调用一个方法(reconnect()),同时显示"Conction Lost!trying to reconnect.."toast

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>

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

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
        }

        }
    }
}

最新更新