Search code examples
androidbroadcastreceiver

how can i run broadcastreceiver without stoping?


I want to run broadcastreceiver without stoping and i dont know how.

I do not know if there is service runs all the time...

Thnaks!


Solution

  • You don't need to start/stop a BroadcastReceiver. Its not your background running service. All you need is to register or unregister it for your application. Once registered, its always ON.

    When some specific event occur, system notifies(broadcast) all registered applications about the event. all registered apps receives this as an Intent. Also, you can send your own broadcast.

    for more, see this

    Simple Example:

    in my manifest, I'm including a permission and a receiver

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.receivercall"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".Main">
            <intent-filter >
                <action android:name="android.intent.action.PHONE_STATE"/>
            </intent-filter>
        </receiver>
        <activity android:name=".TelServices">
            <intent-filter >
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
    
            </intent-filter>
        </activity>
    </application>
    

    Now, my receiver, Main.java

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.TelephonyManager;
    import android.widget.Toast;
    
    
    
       public class Main extends BroadcastReceiver {
        String number,state;   
        @Override
        public void onReceive(Context context, Intent intent) {
    
             state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    
            if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                number=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
    
                Toast.makeText(context, "Call from : "+number, Toast.LENGTH_LONG).show();
            }
            else if(state.equals(TelephonyManager.EXTRA_STATE_IDLE))
                Toast.makeText(context, "Call ended", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, intent.getAction(), Toast.LENGTH_LONG).show();
    
        }
    
    }
    

    Here, when I install this app, I'm registering a Broadcastreceiver through manifest. And the Toast will appear every time a call comes/ends.