简体   繁体   English

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

[英]calling a method in an activity from a broadcast receiver android

this is my broadcast receiver class and i want to call a method ( reconnect(); ) in my MainActivity along with showing the "Conection Lost! trying to reconnect.." toast这是我的广播接收器类,我想在我的MainActivity 中调用一个方法( reconnect(); ),同时显示“连接丢失!试图重新连接..”吐司

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>

create ConnectionStablizerReceiver class as inner class of your activity.;创建 ConnectionStabilizerReceiver 类作为活动的内部类。 It will work它会工作

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
        }



        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM