Android Radio & Services

Source: Internet
Author: User

Broadcastreceiver
    • Broadcast recipient, one of the four Android components
    • To receive broadcast intent, the broadcast intent is sent by calling Sendbroadcast/sendorderbroadcast, usually a broadcast intent can be received by multiple broadcast receivers subscribed to this intent.
Broadcasting
    • Android system broadcasts information via broadcast, only need to register the broadcast recipient
    • The Android system can generate a lot of events during operation, and when these events occur, the system wants to notify other apps that they know about the event, so the broadcast will be issued.
    • such as: Boot, power change, send and receive text messages, call, screen switch.
Define broadcast receivers
    • Must be configured in the manifest file
    • What broadcasts are received through <intent-filter> settings
    • The broadcast contains a intent, and when the broadcast is made, the system traverses
    • If the broadcast receiver is stopped manually by the user, it will never start again. Know that the next time the user starts the process manually, the broadcast recipient will not take effect.
Broadcast classified unordered broadcasts:
    • All broadcast receivers that match the intent in the broadcast receive this broadcast and receive the order
    • Out-of-order broadcasts can not be intercepted and will be error-blocked.
    • Unordered broadcasts use the Sendbroadcast method to send
Orderly broadcast:
    • All broadcast receivers that match the intent in the broadcast will receive this broadcast, but should follow the priority of the broadcast recipient
    • Ordered broadcasts can be intercepted, and high-priority receivers can intercept low-priority
    • Priority value range for broadcast receivers-1000 (lowest) ~1000 (highest)
    • Under the same priority, the order in which they are received depends on the order in which they are declared in the manifest file, and the first declared receiver receives the broadcast before declaring it.
    • Shuffle broadcast using the Sendorderedbroadcast method to send, using the Abortbroadcast method to intercept
    • The priority of the broadcast recipient is set by setting the "Android:property" property under the <intent-filter> tab when the recipient is declared in the manifest file.
Registering a broadcast recipient has two ways of registering statically
    • Add the following configuration to the manifest file

      <!-- 配置广播接收者 --><receiver android:name="com.istarry.ipbohao.IpCallReceiver" >    <intent-filter>        <!-- 指定接收那个广播 -->        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />        <!-- <data android:scheme=" " /> -->    </intent-filter></receiver>
Dynamic registration: Registering in Java code
public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        IntentFilter intentFilter = new IntentFilter("android.intent.action.MEDIA_UNMOUNTED");        intentFilter.addDataScheme("file");        registerReceiver(new IpCallReceiver(), intentFilter);    }}
Attention:
    • The broadcast recipient priority of the Java code registration is higher than the manifest file, but the current broadcast recipient's claim period is associated with the activity, the activity is destroyed, and the broadcast receiver ceases to function.
    • A broadcast receiver registered through a manifest file is registered with the system once it is run on the system, but it can also be received to the broadcast in the future without running the broadcast receiver.
    • When you receive a broadcast, be careful to add the appropriate permissions in the manifest file.
IP Dialer
  • Demand:

    • Listen to the user to make a call, add 17951 before the user dials the phone number
  • 1. Interception of Broadcasts

            <!-- 指定接收(拦截)那个广播 -->        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />           
  • 2. Required Permissions

    <uses-permission android:name= "Android.permission.PROCESSoutgoingCALLS"/>

  • 3. Create a class ipcallreceiver inherit Broadcastreceiver

    public class IpCallReceiver extends BroadcastReceiver {    //当收到广播时,此方法调用    @Override    public void onReceive(Context arg0, Intent arg1) {        //添加17951线路        //1.拿到用户拨打的号码        //广播会发送一个Intent,携带数据        String number = getResultData();        //在号码前加上17951,并返回数据        setResultData("17951"+number);    }}
  • 4. Register the broadcast recipient in the manifest file

       <application    …… >    …………    <!-- 配置广播接收者 -->        <receiver android:name="com.istarry.ipbohao.IpCallReceiver" >         <!-- android:priority="1000"代表着给当前接收者设置优先级,优先级越高就越先接收到广播,取值-1000~1000 -->            <intent-filter android:priority="1000">            <!-- 指定接收那个广播 -->            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />            <!-- <data android:scheme=" " /> -->          </intent-filter>        </receiver>    …………
Service
    • Service is a long-life-cycle component in Android, and it does not have any user interface, it is an activity with no interface.
    • The service runs in the background for a long time, performing some operations that are not related to the interface. For example: NetEase news Service, every minute to the service to see if there is the latest news.
    • The service and thread are somewhat similar, but using thread is unsafe and not rigorous.
    • The service, like any other component, is running in the main thread, so you can't use it to do good things.
Process types in Android in Android

The process priority is high-to-low, in turn:

    • 1. Foreground process Foreground (has an activity process that is interacting with the user, that is, the Onresume () method is called)
    • 2. Visible process can be seen, but cannot be interacted with. (Has an activity that is not in the foreground but is still visible, that is, the OnPause () method is called)
    • 3. Service Process Services processes (running a service process started through the Starservice () method)
    • 4. Background Process Daemon (the OnStop method of the activity is called)
    • 5. Empty process (when the program exits, the process is not destroyed, but it becomes an empty process). Processes that do not have any component activity (there is no service or activity in the process)
Recycle mechanism of process

Android

Phone Recorder phone Status

Telephonymanager, setting Phonestatelistener listening status

    • Free
    • Bell
    • Off-hook status (answer)

Permissions

<uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.RECORD_AUDIO" />

Configuration manifest file

<service android:name="com.istarry.luyinji.LuyinjiService" />

Create a class Luyinjiservice inherit service

  public class Luyinjiservice extends Service {@Override public ibinder onbind (Intent Intent) {//    TODO auto-generated method stub return null;        } @Override public void OnCreate () {//TODO auto-generated Method Stub super.oncreate ();        Get phone Manager Telephonymanager TM = (Telephonymanager) getsystemservice (Telephony_service);    Set listen//Parameter 2: Set listener to listen to only what data Tm.listen (new MyListener (), phonestatelistener.listen_call_state);    } private Mediarecorder Recorder; Class MyListener extends Phonestatelistener {//Call this method when the phone state changes @Override public void Oncallstatechange d (int state, String incomingnumber) {//TODO auto-generated Method stub super.oncallstatechanged (St            Ate, Incomingnumber); Switch (state) {case TELEPHONYMANAGER.CALL_STATE_IDLE:SYSTEM.OUT.PRINTLN ("idle");  
                if (recorder! = NULL) {//Stop recording recorder.stop ();                    Release the resource Recorder.release ();                Recorder = null;            } break;                Case TelephonyManager.CALL_STATE_RINGING:System.out.println ("Bell");                    if (recorder = = null) {recorder = new mediarecorder ();                    Set the recording source Recorder.setaudiosource (MediaRecorder.AudioSource.MIC);                    Set the recording format 3gp format Recorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP);                    Set the recording file save location Recorder.setoutputfile ("sdcard/voice.3gp");                    Set audio encoding (one format may have multiple encoding methods) Recorder.setaudioencoder (MediaRecorder.AudioEncoder.AMR_NB);                    try {//Ready to record Recorder.prepare () at any time; } CAtch (Exception e) {e.printstacktrace ();            }} break;                Case TelephonyManager.CALL_STATE_OFFHOOK:System.out.println ("Off-hook");                if (recorder! = null) {Recorder.start ();            } break; }}} @Override public int onstartcommand (Intent Intent, int flags, int startid) {//TODO Auto-gen    erated Method Stub return Super.onstartcommand (Intent, flags, Startid); }}

Android Radio & Services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.