如何取消注册android中服务类的广播接收器?

时间:2014-06-20 17:49:15

标签: android service broadcastreceiver

我想要startreceiver和stopreceiver buttonon和butttonoff点击 单击接收器上的按钮启动但按钮点击不停止它给我错误

buttonon.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Calendar cur_cal = Calendar.getInstance();
        cur_cal.setTimeInMillis(System.currentTimeMillis());
        Intent intent = new Intent(MainActivity.this, WifiScanService.class);
        PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(), 10*1000, pintent);    
        startService(new Intent(MainActivity.this,WifiScanService.class));  
    }
}

buttonoff..setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {   
    Calendar cur_cal = Calendar.getInstance();
    cur_cal.setTimeInMillis(System.currentTimeMillis());
    Intent intent = new Intent(MainActivity.this, WifiScanService.class);
    PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pintent);
    stopService(new Intent(MainActivity.this,WifiScanService.class));       
}

Wifiscanservice.class

public class WifiScanService extends Service{

    private static String TAG="WifiScanService";
    WifiManager mainWifi;
    WifiReceiver receiverWifi;
    List<ScanResult> wifiList;
    String wifinetworkname;


    String userid="";
    String longitude="";
    String latitude="";
    String terminalid="";
    String wifiname="";
    String timestamp="";
    String sid="";
    String success="";
    String message="";

 // for session
    SharedPreferences spreferences;
    Editor edit;

    public WifiScanService(){
        super();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        Log.i(TAG, "ondestroy");

        unregisterReceiver(receiverWifi);

    }




        @Override
    public void onCreate(){
        Log.i(TAG, "onCreate");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {

        Log.d("WifiScanService","In Service");

        wifinetworkname = getString(R.string.wifinetworks);
        mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        receiverWifi = new WifiReceiver();
        registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        if (mainWifi.isWifiEnabled() == false)
        {  
                // If wifi disabled then enable it
                Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
                Toast.LENGTH_LONG).show();

                mainWifi.setWifiEnabled(true);
        } 
        mainWifi.startScan();
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }




/////////////////////////////////////////////////////////////////////////////////////

    class WifiReceiver extends BroadcastReceiver 
    {

        // Classes For Database
        private     SQLiteDatabase  mSQLiteDatabase = null;
        private     DB_Helper       mDB_Helper = null;

        // get latitude and longitude
        GPSTracker gps;

        String result="";
        // This method call when number of wifi connections changed
        public void onReceive(Context c, Intent intent) 
        {


            spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            sid=spreferences.getString("id","");

             // for get the location
            gps = new GPSTracker(getApplicationContext());

            Log.d("WifiReceiver","In Receiver");
            wifiList = mainWifi.getScanResults();
            for(int i = 0; i < wifiList.size(); i++)
            {
                  //  Vibrator v = (Vibrator)c.getSystemService(Context.VIBRATOR_SERVICE);
                     // Vibrate for 500 milliseconds
                    // v.vibrate(500);

                /*
                     ArrayList<HashMap<String,String>>  dbwifilist= new ArrayList<HashMap<String,String>>();

                     Open_Database();

                     dbwifilist=DB_Helper.CheckWifiFound(mSQLiteDatabase, 
                                            DB_Constant.TABLE.MYWIFI, 
                                            DB_Constant.MYWIFI.WIFINAME,
                                            wifiList.get(i).SSID.toUpperCase().toString());
                     Close_Database();

                     if(dbwifilist.size()>0)
                     {
                        if(gps.canGetLocation())
                        {   
                           double   mlatitude = gps.getLatitude();
                           double   mlongitude = gps.getLongitude();
                           latitude=Double.toString(mlatitude);
                           longitude=Double.toString(mlongitude);
                        }
                        else
                        {
                            ///Toast tx=Toast.makeText(c,"GPS IS DISABLE",Toast.LENGTH_SHORT);
                           // tx.show();

                        }
                        wifiname=wifiList.get(i).SSID;
                        terminalid=dbwifilist.get(0).get(DB_Constant.MYWIFI.TERMINAL_ID).toString();
                        if(!sid.equals(""))
                        {   

                            if(CheckConnection.getInstance(getApplicationContext()).isOnline(getApplicationContext()))
                            {
                                new StoreUserLocationAsync().execute("");
                            }
                            else
                            {
                                 Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",Toast.LENGTH_SHORT).show();
                            }



                        }
                     }

                   //  Toast tx=Toast.makeText(c,"PingCM2C Network Found - " + wifiList.get(i).SSID,Toast.LENGTH_SHORT);
                   //  tx.show();

                   //  Log.d("WifiReceiver","In Receiver"+wifiList.get(i).SSID);
                */
            }

        }


        public class StoreUserLocationAsync extends AsyncTask<String,String,String>
        {

            @Override
            protected String doInBackground(String... params) 
            {
                JsonParser jparser= new JsonParser();


                Date date = new Date();
                SimpleDateFormat formatdate = new SimpleDateFormat("MM/dd/yyyy%20HH:mm:ss");
                timestamp=formatdate.format(date);

                String url="http://ringmyserver.com/Pingm2c/rest/userservice/storeUserLocation?userID="+sid+"&Longitude="+longitude+"&Latitude="+latitude+"&TerminalID="+terminalid+"&ConnectedWiFiNAme="+wifiname+"&TimeStamp="+timestamp+"";
                String data=jparser.geturldata(url);
                Log.e("StoreUserLocation","----->"+data);
                Log.e("StoreUserLocation","----->"+url);
                try 
                {
                    JSONObject jobject = new JSONObject(data);
                    success=jobject.getString(WS_Constant.REGISTER.SUCCESS);
                    if(success.equals("0"))
                    {
                        message=jobject.getString(WS_Constant.REGISTER.MESSAGE);

                    }
                    else
                    {
                        message=jobject.getString(WS_Constant.REGISTER.MESSAGE);

                    }



                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }

                return message;
            }

            @Override
            protected void onPostExecute(String result) 
            {
                Toast.makeText(getApplicationContext(),"User Location Update ",Toast.LENGTH_SHORT).show();

            }



        }

        /* Opening DB */
        private void Open_Database() 
        {
               mDB_Helper = new DB_Helper(getApplicationContext());
              mSQLiteDatabase = mDB_Helper.getWritableDatabase();

        }

        /* Closing DB */
        private void Close_Database() 
        {

            if (mSQLiteDatabase != null && mDB_Helper != null) 
            {       
                    mSQLiteDatabase.close();
                    mDB_Helper.close();
            }

        }
    }    
}
  

错误日志

06-20 23:20:15.460: E/ActivityThread(10269): Service com.pingm2c.WifiScanService has leaked IntentReceiver com.pingm2c.WifiScanService$WifiReceiver@40deb568 that was originally registered here. Are you missing a call to unregisterReceiver()?
06-20 23:20:15.460: E/ActivityThread(10269): android.app.IntentReceiverLeaked: Service com.pingm2c.WifiScanService has leaked IntentReceiver com.pingm2c.WifiScanService$WifiReceiver@40deb568 that was originally registered here. Are you missing a call to unregisterReceiver()?
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:820)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:614)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1312)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ContextImpl.registerReceiver(ContextImpl.java:1299)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ContextImpl.registerReceiver(ContextImpl.java:1293)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:341)
06-20 23:20:15.460: E/ActivityThread(10269):    at com.pingm2c.WifiScanService.onStartCommand(WifiScanService.java:84)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2723)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ActivityThread.access$1900(ActivityThread.java:139)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.os.Looper.loop(Looper.java:156)
06-20 23:20:15.460: E/ActivityThread(10269):    at android.app.ActivityThread.main(ActivityThread.java:5005)
06-20 23:20:15.460: E/ActivityThread(10269):    at java.lang.reflect.Method.invokeNative(Native Method)
06-20 23:20:15.460: E/ActivityThread(10269):    at java.lang.reflect.Method.invoke(Method.java:511)
06-20 23:20:15.460: E/ActivityThread(10269):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-20 23:20:15.460: E/ActivityThread(10269):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-20 23:20:15.460: E/ActivityThread(10269):    at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案