Antholife
Antholife

Reputation: 21

Broadcast receiver continue after application leave

I have a problem I can not solve, the broadcast receiver of my application continues to run when I leave my application. I have to forcibly stop the application manually, whereas I are closed; Thank you for your help. Here is my manifest, and my receiver:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.locateit.antholife.locateit">

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />



<application
    android:allowBackup="true"
    android:icon="@mipmap/locate"
    android:label="@string/app_nameprincipal"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true"
        android:xlargeScreens="true" />

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Main2Activity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".Changelog"
        android:label="@string/title_activity_changelog"
        android:theme="@style/AppTheme.NoActionBar" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyBfmF3WWxsPhufZR5keiDNRy-33hJI1rvM" />

    <activity
        android:name=".lequipe"
        android:label="@string/nomequipe" />
    <activity
        android:name=".Setting"
        android:label="@string/title_activity_setting" />
    <activity android:name=".MDPinterne"
              android:label="@string/title_activity_mdpsecure" />
    <activity android:name=".Bluetooth"
              android:label="@string/title_activity_bluetooth" />

    <receiver android:name=".MyReceiver">
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

    <activity android:name=".Smsconnection"
        android:label="@string/title_activity_gsm" >

    </activity>
</application>

and myreceiver :

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

public int lock = 0;

@Override
public void onReceive(Context context, Intent intent) {


    Bundle extra = intent.getExtras();
    if (extra != null) {
        Object[] pdus = (Object[]) extra.get("pdus");
        final SmsMessage[] messages = new SmsMessage[pdus.length];
        for (int i = 0; i < pdus.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        }
        if (messages.length > -1) {
            for (int i = 0; i < messages.length; i++) {
                String messageBody = messages[i].getMessageBody();
                String phoneNumber = messages[i].getDisplayOriginatingAddress();
                Toast.makeText(context, "Expéditeur:" + "\n" + phoneNumber, Toast.LENGTH_LONG).show();
                Toast.makeText(context, "Message : " + "\n" + messageBody, Toast.LENGTH_LONG).show();

                if (messageBody.equals("CS")) {

                    lock = 1;
                    SharedPreferences sharedPreferences = context.getSharedPreferences("appSharedPreferences", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("lockphone", phoneNumber);
                    editor.putInt("locksecurity", lock);
                    editor.commit();
                    Toast.makeText(context, "Association réussie !", Toast.LENGTH_LONG).show();
                    Toast.makeText(context, "L'option Connexion GSM est maintenant désactivée.", Toast.LENGTH_LONG).show();

                }
             /**   else {
                    Toast.makeText(context, "Echec de l'association !", Toast.LENGTH_LONG).show();
                    Toast.makeText(context, "Merci de renseigner un numéro correct", Toast.LENGTH_LONG).show();

                } **/
            }
        }
    }
  }



 }

Upvotes: 1

Views: 351

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006594

You have MyReceiver registered in the manifest. Therefore, it is set up to receive broadcasts all the time.

If you want to only receive broadcasts some of the time, either:

  • Use registerReceiver() and unregisterReceiver() on some Context, eliminating your <receiver> element from the manifest, or

  • Use PackageManager and setComponentEnabledSetting() to enable or disable the <receiver> as appropriate

As an example of the former, this sample app has a fragment that registers for ACTION_BATTERY_CHANGED in onResume() and unregisters in onPause():

/***
  Copyright (c) 2008-2014 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.battmon;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BatteryFragment extends Fragment {
  private ProgressBar bar=null;
  private ImageView status=null;
  private TextView level=null;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent,
                           Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.batt, parent, false);

    bar=(ProgressBar)result.findViewById(R.id.bar);
    status=(ImageView)result.findViewById(R.id.status);
    level=(TextView)result.findViewById(R.id.level);

    return(result);
  }

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

    IntentFilter f=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

    getActivity().registerReceiver(onBattery, f);
  }

  @Override
  public void onPause() {
    getActivity().unregisterReceiver(onBattery);

    super.onPause();
  }

  BroadcastReceiver onBattery=new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
      int pct=
          100 * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 1)
              / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);

      bar.setProgress(pct);
      level.setText(String.valueOf(pct));

      switch (intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
          status.setImageResource(R.drawable.charging);
          break;

        case BatteryManager.BATTERY_STATUS_FULL:
          int plugged=
              intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

          if (plugged == BatteryManager.BATTERY_PLUGGED_AC
              || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
            status.setImageResource(R.drawable.full);
          }
          else {
            status.setImageResource(R.drawable.unplugged);
          }
          break;

        default:
          status.setImageResource(R.drawable.unplugged);
          break;
      }
    }
  };
}

As a result, it will only receive that broadcast while the fragment is in the foreground from an input standpoint.

Upvotes: 2

anAmaka
anAmaka

Reputation: 418

check this and register/unregister at right place.

Upvotes: 1

Related Questions