从调用的BroadcastReceiver在Android的一个活动的方法 [英] Calling a Activity method from BroadcastReceiver in Android

查看:102
本文介绍了从调用的BroadcastReceiver在Android的一个活动的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我创建一个在线应用程序,只依赖于互联网。

Here i am creating a online application that depends only on Internet.

所以,只要有网络错误就必须通知到,我已经创建了一个接收来电时,网络连接丢失一个BroadcastReciver的user.For(互联网)。

So whenever there is a network error it must notifies to the user.For that i have created a BroadcastReciver that receives call when network connection gets lost(Internet).

这一切工作perfectly.Now我需要的是,我必须从这个广播接收器,在那里我已经创建了一个警报对话呼叫活动的方法。

All this works perfectly.Now what i need is that i have to call a method of Activity from this Broadcast Receiver,where i have created a Alert Dialogue.

我已经阅读stack-overflow.com很多答案,我可以声明静态方法和仅使用活动的名字叫

I have read many answers on stack-overflow.com that i can declare that method static and call by using only Activity name,

例如 MyActivityName.myMethod()

但我不能宣布我的方法静态的,因为我使用的警报对话那里,它显示了我的错误就行,

But i can't declare my method static,because i am using Alert Dialogue there and it shows me error on line,

AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

,即不能在静态的情况下使用

那么,如何从广播接收呼叫活动的方法(一定不是静态的,不启动该活动)?

So,how can i call a method of Activity(must not static and without starting that activity) from a Broadcast Receiver ?

和我可以从广播接收器目前正在运行得到活动(或片段)的名字?

And can i get Activity(or fragment) name from Broadcast Receiver which currently running ?

推荐答案

试试这个code:

您的BroadcastReceiver类互联网失去类:

your broadcastreceiver class for internet lost class :

public class InternetLostReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    context.sendBroadcast(new Intent("INTERNET_LOST"));
}
}

在您的活动添加此调用广播:

in your activity add this for calling broadcast:

public class TestActivity  extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_LOST"));
}

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // internet lost alert dialog method call from here...
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(broadcastReceiver);
}
}

这篇关于从调用的BroadcastReceiver在Android的一个活动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆