-1

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!

4

1 回答 1

1

您不需要启动/停止广播接收器。它不是您的后台运行服务。您只需要为您的应用程序注册或取消注册它。一旦注册,它总是打开。

当某些特定事件发生时,系统会通知(广播)所有已注册的应用程序有关该事件的信息。所有注册的应用程序都将其作为Intent. 此外,您可以发送自己的广播。

有关更多信息,请参阅此

简单示例:

在我的清单中,我包含了一个权限和一个接收者

<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>

现在,我的接收器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();

    }

}

在这里,当我安装这个应用程序时,我正在通过清单注册一个 Broadcastreceiver。每次来电/结束时都会出现 Toast。

于 2013-07-28T17:39:28.047 回答