Usage of sendBroadcast()

2020-02-28 02:29发布

sendBroadcast() - Should it be called inside Activity? I am trying to call sendBroadcast() from my method of utility-class which doesn't extend Activity. I am getting compilation error as below

The method sendBroadcast(Intent) is undefined for the type MyWrapperClass MyWrapperClass.java

Here is the code snippet:

abstract class MyWrapperClass {

    public static void sendData()
         {
             Intent intent = new Intent ("com.proj.utility.mgr",null);

             intent.putExtra("example","Broadcasting "); 

            sendBroadcast(intent);

         }
    }

Is there any concept behind using sendBroadcast call inside my class. There is no issue in using sendBroadcast() inside Activity. Can someone here help me to resolve it? Or Any other suggestions are invited to return data from utility class to application asynchronously. Thanks in advance.

2条回答
我想做一个坏孩纸
2楼-- · 2020-02-28 03:28

You should pass the context from activity class to utility class to access the specific application resources like startActivity, sendBroadcast, etc.

context.sendBroadcast(intent);
查看更多
你好瞎i
3楼-- · 2020-02-28 03:28

If you extend Application object (main entry that is being called before the your first Activity) then you can keep a shared singletone for your application.

查看更多
登录 后发表回答