如何从广播接收器onReceive方法中访问MainActivity findViewById?

时间:2016-12-14 02:58:47

标签: java android android-intent broadcastreceiver android-service

当我使用此代码时:

@Override
public void onReceive(Context context, Intent intent) {

    seconds += 0.1;

    if (seconds > 59.9) {
        seconds=0;
        minutes++;
    }

    TextView tv = (TextView)((MainActivity)context).findViewById(R.id.txtChron);
    tv.setText (String.valueOf(minutes) + ":" + String.valueOf(seconds));
}

尝试将上下文转换为MainActivity时出错。

这是错误/堆栈跟踪:

  

E / AndroidRuntime:致命异常:主要流程:   com.example.jordanbleu.lab8chronservjordanbleu,PID:22693   java.lang.RuntimeException:接收广播Intent时出错{   ACT = com.example.jordanbleu.lab8chronservjordanbleu.MY_TIME_TICK   flg = 0x10} in   com.example.jordanbleu.lab8chronservjordanbleu.ChronometerReceiver@d9365fe   在   android.app.LoadedApk $ ReceiverDispatcher $ Args.run(LoadedApk.java:1132)   在android.os.Handler.handleCallback(Handler.java:751)at   android.os.Handler.dispatchMessage(Handler.java:95)at   android.os.Looper.loop(Looper.java:154)at   android.app.ActivityThread.main(ActivityThread.java:6119)at   java.lang.reflect.Method.invoke(Native Method)at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)引起   by:java.lang.ClassCastException:android.app.Application不能   施放到com.example.jordanbleu.lab8chronservjordanbleu.MainActivity at   com.example.jordanbleu.lab8chronservjordanbleu.ChronometerReceiver.onReceive(ChronometerReceiver.java:41)   在   android.app.LoadedApk $ ReceiverDispatcher $ Args.run(LoadedApk.java:1122)   在android.os.Handler.handleCallback(Handler.java:751)at   android.os.Handler.dispatchMessage(Handler.java:95)at   android.os.Looper.loop(Looper.java:154)at   android.app.ActivityThread.main(ActivityThread.java:6119)at   java.lang.reflect.Method.invoke(Native Method)at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

所以我有一个MainActivity,它启动了一项服务。该服务创建一个新线程,并且该线程不断创建由BroadcastReceiver处理的隐式意图。此广播接收器将更新时钟,并使用更新的时间更新布局中的TextView。但是当我尝试通过context参数访问findViewByID时,我得到上面的错误。

3 个答案:

答案 0 :(得分:0)

If you want implement ajax in wordpress than you need use wp_ajax hook. https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action) add bellow code in function.php (theme folder) javascript add in wp_footer hook on function.php jQuery.post( ajaxurl, { 'action': 'add_foobar', 'data': 'foobarid' }, function(response){ alert('The server responded: ' + response); } ); bellow wp_ajax hook add on function.php add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' ); function prefix_ajax_add_foobar() { // Handle request then generate response using WP_Ajax_Response // Don't forget to stop execution afterward. wp_die(); } Those code will not update when you update wordpress. but if possible than add those code on function.php on child theme so in case if you want update theme than not update those code. 的{​​{1}}功能中初始化TextView

onCreate

然后在Activity函数

TextView tv = (TextView) findViewById(R.id.txtChron);

答案 1 :(得分:0)

您的错误是:

  

java.lang.ClassCastException:android.app.Application无法强制转换为com.example.jordanbleu.lab8chronservjordanbleu.MainActivity

这意味着“上下文上下文”是应用程序,而不是MainActivity。

我的建议是,在OnCreate中膨胀你的TextView。

TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    tv = (TextView) findViewById(R.id.txtChron); // This!
...
}

@Override
public void onReceive(Context context, Intent intent) {

    seconds += 0.1;

    if (seconds > 59.9) {
        seconds=0;
        minutes++;
    }

    tv.setText (String.valueOf(minutes) + ":" + String.valueOf(seconds));
}

答案 2 :(得分:0)

您也可以使用界面。这样,您将不必访问BroadcastReceiver中的UI元素。

1)创建一个界面:

public class YourBroadCastReceiver extends BroadCastReceiver{

    private ReceiverListener listener;

    @Override
    public void onReceive(Context context, Intent intent) {

        listener = (ReceiverListener)context;  // Initialize listener 

        // Your logic 
        String minutes = //get it
        String seconds = // get it

       listener.doSomething(minutes,seconds); 

    }

}

2)在您的BroadcastReceiver中实例化监听器

public YourActivity extends AppcompatActivity implements ReceiverListener{

     // Activity related code
    TextView tv;

    public void updateUI(String minutes,String seconds){
        tv.setText (minutes + ":" + seconds);
    }


    @Override 
    public void doSomething(String arg1, String arg2){
        updateUI(arg1,arg2);
    }

}

3)在“活动”中实现界面并覆盖方法

signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error)  in
    if error == nil {
        self.performSegue(withIdentifier: "loginToHome", sender: nil)
    } else {
        let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
    }
}

相关链接:

如果您想了解在这种情况下使用界面的优势,请READ THIS