我已经在网上冲浪,但我还没有找到解决我的问题的方法。
在我的安卓应用程序中,我必须在每次用户关闭GPS时捕捉并向服务器发送一个通知。在这个时候,我已经写了这个代码
在Android清单中。
<receiver android:name="proguide.prosegur.scr.BL.receivers.GPSStatusBroadcastReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
在GPSStatusBroadcastReceiver类中。
public class GPSStatusBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// here I have to send the notification
}
}
问题是每当用户放下GPS时,这个函数就会被调用两次,其Context和Intent参数完全相同(一次只能发送一个通知)。
重要提示:它必须在API 8级别下工作。
那么,为什么会发生两次?我可以做什么(做得对,不弄乱代码)来一次只发送1个通知?谢谢,对不起我的英语。
试试这个。
public class GpsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
final String action = intent.getAction();
if (action.equals(LocationManager.PROVIDERS_CHANGED_ACTION)) {
// GPS is switched off.
if (!context.getSystemService(Context.LOCATION_SERVICE).isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// Do something.
}
}
}
}
}
还有,不要硬编码 "android.location.PROVIDERS_CHANGED"
,你应该使用变量 LocationManager.PROVIDERS_CHANGED_ACTION
由Android提供。
而不是将GPS接收器设置在你的 AndroidManifest.xml
文件,通过 Service
如下。
public class GpsService extends Service {
private BroadcastReceiver mGpsReceiver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
registerReceiver();
return Service.START_NOT_STICKY;
}
private void registerReceiver() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
this.mGpsReceiver = new GpsReceiver();
this.registerReceiver(this.mGpsReceiver, mIntentFilter);
}
}
}
你可以用sharedpreference和线程来避免这个问题,但这不是克服这个问题的正确方法。
我的方法如下
@Override
public void onReceive(Context context, Intent intent) {
boolean flage=MainActivity.getpreference();
if(!flage){
MainActivity.putPreferens(true);
Log.e("gpssss","gpssss");
Thread thread = new Thread() {
@Override
public void run() {
try {
sleep(2000);
MainActivity.putPreferens(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}}
}
到主类中创建一个sharedpreference和存储boolean值false的广义投递一次就可以了。