我正在尝试实现自定义bradcastreciever。但是当我注册它时,我的意图返回null。我不知道这里出了什么问题 ?
我的活动就在这里
private MyReciever mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mReceiver = new MyReciever();
Intent result=registerReceiver(this.mReceiver, new IntentFilter(
"com.example.Broadcast"));
int status = result.getIntExtra("HighScore",0);
System.out.println(status+" Yahoo");
setContentView(R.layout.activity_main);
for (int i = 0; i < 10; i++) {
try {
if (i == 7) {
// MyReciever mr=new MyReciever();
Intent intent = new intent();
intent.setAction("com.example.Broadcast");
intent.putExtra("HighScore", 1000);
sendStickyBroadcast(intent);
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
unregisterReceiver(mReceiver);
}
和Reciever是
public class MyReciever extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//int data= intent.getIntExtra("HighScore",0);
Toast.makeText(context, "Highest Score", Toast.LENGTH_LONG).show();
}
}
我已获得android mainfest文件的许可
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
答案 0 :(得分:3)
它将返回null
,因为在您拨打registerReceiver()
时,尚未为该操作广播任何内容。
答案 1 :(得分:0)
在清单文件中声明您的接收器
<receiver
android:name=".MyReceiver"
</receiver>