这就是我的代码......而且由于注册和取消注册(多次)我的接收者(正在启动服务),我遇到了问题。
问题在于:我已经看到'receiver'变量在执行registerReceiver和unregisterReceiver命令后变为NULL ...具体来说,在我注册并取消注册然后再次注册接收器之后,接收器只有NULL,并且因此,当再次注销它时,它会出错!基本上,我的应用程序在取消注册一次后无法再次注册Receiver。为什么这是一个问题?
public class startScreen extends Activity {
/** Called when the activity is first created. */
private BroadcastReceiver receiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.MyService");
context.startService(serviceIntent);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.initial);
final IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.STATE_CHANGE");
Button button = (Button) findViewById(R.id.button1);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
try
{
... some code...
if(bool == true)
{
toggleButton.setChecked(true);
this.registerReceiver(receiver, filter);
}
else
toggleButton.setChecked(false);
}catch(Exception e) {
Log.e("Error", "Database", e);
} finally {
...
}
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if((toggleButton.isChecked()))
{
getBaseContext().registerReceiver(receiver, filter);
}
else
{
if (receiver != null){
getBaseContext().unregisterReceiver(receiver);
receiver = null;
}
}
}
});
}
@Override
protected void onResume(){
super.onResume();
if(bool == true)
{
if(receiver == null)
this.registerReceiver(receiver, filter);
}
}
@Override
protected void onPause(){
super.onPause();
if (receiver != null){
this.unregisterReceiver(receiver);
receiver = null;
}
}
}
答案 0 :(得分:0)
您在receiver
和toggleButton.setOnClickListener
内明确将onPause
设为空:
receiver = null;
尝试删除这些行并查看它是否解决了问题