您的位置:首页 > 其它

Broadcast receiver Activity

2015-02-27 12:15 120 查看


If you want to catch a broadcasted intent on an Activity, you may get the following error:

02-22 08:18:46.874: E/AndroidRuntime(276): java.lang.RuntimeException:Unable
to instantiate receiver com.helloandroid.broadcasttest.BroadcastTestActivity$MyBroadcastReceiver:

...

java.lang.InstantiationException:com.helloandroid.broadcasttest.BroadcastTestActivity$MyBroadcastReceiver

...

02-22 08:18:46.874: E/AndroidRuntime(276): Caused
by:java.lang.InstantiationException:com.helloandroid.broadcasttest.BroadcastTestActivity$MyBroadcastReceiver

This is because you can't instantiate a receiver in an inner class.
Instead of inner receiver, you can manually instantiate a broadcast receiver yourself in the activity.

private BroadcastReceiver myBroadCastReceiver =new BroadcastReceiver()

{

@Override

public void onReceive(Context context,
Intent intent )

{

Log.d( "Broadcastreceiver: " + intent.getAction() + "
package: "+intent.getPackage() + " @" + System.currentTimeMillis() );

}

};

No need to set this receiver in the manifest xml file, register it in the activity's onresume method and unregister in the onpause:

public void onResume() {

super.onResume();

....

registerReceiver(myBroadcastReceiver, newIntentFilter("your.custom.BROADCAST"));

}

public void onPause() {

super.onPause();

...

unregisterReceiver(myBroadcastReceiver);

}

...

}

Thats all, the receiver will catch the broadcasts, if the activity is on the screen.
To broadcast custom intents, use the following method:

Intent broadCastIntent = new Intent();

broadCastIntent.setAction( "your.custom.BROADCAST" );

broadCastIntent.setPackage("com.helloandroid.broadcasttest" );

ApplicationObject.applicationContext.sendBroadcast(broadCastIntent );

Log.d( "Broadcast sent" );

The setPackage() method set an explicit application package name that limits the components the Intent will resolve to.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐