我使用以下代码注册接收器,但它显示错误说明 语法错误或标记,错位的构造函数 这是代码 此外,我希望即使应用程序关闭也能运行
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
if (!registered) {
MyReceiver mybroadcast = new MyReceiver(){
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:1)
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
if (!registered) {
MyBroadcast mybroadcast=new MyBroadcast();
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
private class MyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//TODO some code here
}
}
}
答案 1 :(得分:1)
您必须首先定义接收器,而不是注册它:
BroadcastReceiver mybroadcast = new BroadcastReceiver (){
@Override
public void onReceive(Context context, Intent intent) {
//define what you want the receiver to do when it is called
}
};
然后注册:
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
在你的情况下你想要放两个IntentFilter,所以这样做:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction((Intent.ACTION_SCREEN_OFF));
intentFilter.addAction((Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, intentFilter);
如果您不取消注册接收器,并且您希望服务继续工作,您将获得新的异常或警告,因此请在onDestroy中取消注册接收器:
/*
* (non-Javadoc)
*
* @see android.app.Service#onDestroy()
*/
@Override
public void onDestroy() {
unregisterReceiver(mybroadcast);
super.onDestroy();
}
答案 2 :(得分:0)
onCreate()
方法错过了右括号}
。格式化可帮助您解决这些错误。你还没有完全告诉我们你做了什么。请按照link了解