Android Development Service applies to broadcast receiver tutorials

Source: Internet
Author: User
Tags xmlns

What is a service: a long running background with no interface components,

Android is an application scenario:
Weather forecast: The logic of the backend connection server to get the latest weather information every once in a while
Stock Display: Background of the logic of the connection server, every time to get the latest stock information
MP3 Player: Play music in the background for a long time.

New Thread () {}.start (); The child thread has no interface and is also long-running in the background.

The Android system process management is based on certain rules:

1. The process does not stop once the application is turned on and is normally closed (emptying the task stack). aspect of the next quick Launch.

A problem with low memory.

2.Android system has a set of memory cleaning mechanism. Recycle the memory of the system according to priority.



Process is divided into 5 priority levels: (from high to low)



1.Foreground process foreground process users are playing the application corresponding processes


2.Visible process visual processes users can still see the interface of this process.


The 3.Service Process Service processes application has a service component running in the background.


4.Background Process Daemon applications are running and minimized with no services (activity OnStop)


5.Empty process empty processes do not have any running activity, the task stack is empty


Long-running background components, do not open child threads in activity.

It should be creating a service that opens a child thread within the service.



Purpose of the service:

1. Long-term background operation.

2. Increase the priority of the process, the system is not easy to reclaim the process, even if the recovery, sufficient memory, the process to recreate.

Case scenario: Use a button to open the service and print the service startup status on the console. The program interface is as follows:


The 2 Android listing file is as follows:

<?xml version= "1.0" encoding= "Utf-8"?>

<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"

Package= "Com.itheima.testservice"

Android:versioncode= "1"

Android:versionname= "1.0" >



<uses-sdk

Android:minsdkversion= "8"

Android:targetsdkversion= "/>"



<application

Android:allowbackup= "true"

android:icon= "@drawable/ic_launcher"

Android:label= "@string/app_name"

Android:theme= "@style/apptheme" >

<activity

Android:name= "Com.itheima.testservice.MainActivity"

Android:label= "@string/app_name" >

<intent-filter>

<action android:name= "Android.intent.action.MAIN"/>



<category android:name= "Android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

<service android:name= "Com.itheima.testservice.MyService" ></service>

</application>



</manifest>

3 layout files are as follows:

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"

Xmlns:tools= "Http://schemas.android.com/tools"

Android:layout_width= "Match_parent"

android:layout_height= "Match_parent"

Tools:context= ". Mainactivity ">


<button

android:onclick= "click"

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

Android:layout_centerhorizontal= "true"

Android:layout_centervertical= "true"

android:text= "Open service"/>

</RelativeLayout>

The code for the 4 mainactivity is as follows:

Package com.itheima.testservice;

Import android.app.Activity;

Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;

public class Mainactivity extends activity {

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

}

public void Click (View view) {

Intent Intent = new Intent (this,myservice.class);

StartService (Intent);

}

}

The code for the 5 MyService is as follows:

Package com.itheima.testservice;

Import Android.app.Service;

Import android.content.Intent;

Import Android.os.IBinder;


public class MyService extends Service {

@Override

Public IBinder Onbind (Intent Intent) {

return null;

}


OnCreate ondestory onstart onstop onresume onpause

@Override

public void OnCreate () {

SYSTEM.OUT.PRINTLN ("service created");

Super.oncreate ();

}



@Override

public int Onstartcommand (Intent Intent, int flags, int startid) {

SYSTEM.OUT.PRINTLN ("server");

Return Super.onstartcommand (Intent, flags, Startid);

}



@Override

public void OnDestroy () {

SYSTEM.OUT.PRINTLN ("server destroyed");

Super.ondestroy ();

}

}




6. Note on the recipient


Four components:

Activity
Content provider Provider
Broadcast receiver broadcast recipient
Service services


Radio: Send a broadcast
Radio: Accept the Radio


Broadcasts under the Android system:

Low battery charge.
Battery charge complete.
Message's coming.
Program Safety Loading and unloading
SD Card Uninstall Installation

1. Write a class to inherit the broadcast recipient
2. Configure the action of interest in the manifest file
3. Once the broadcast event occurs, the OnReceive method of the broadcast recipient is executed




Android invokes service method via broadcast receiver

Android invokes the service method through the broadcast receiver and registers the broadcast receiver with code (the only component in 4 large components that can use code declarations (activity Receiver provider service))

Service

Package Com.pas.callmethod;

Import Android.app.Service;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import Android.os.IBinder;
Import Android.widget.Toast;

public class MyService extends Service
{

Private Myreciver receiver;

@Override
public void OnCreate ()
{
Registering a broadcast receiver by code
Receiver=new Myreciver ();
Intentfilter filter=new Intentfilter ();
Filter.addaction ("Com.pas.call");
Registerreceiver (receiver, filter);
Super.oncreate ();
}

@Override
public void OnDestroy ()
{
Unregisterreceiver (receiver);
Receiver=null;
Super.ondestroy ();
}
@Override
Public IBinder Onbind (Intent arg0)
{
return null;
}

private void Method_inservice ()
{
Toast.maketext (Getapplicationcontext (), "My service method ...", Toast.length_short). Show ();
}

Private class Myreciver extends Broadcastreceiver
{

@Override
public void OnReceive (context arg0, Intent arg1)
{
SYSTEM.OUT.PRINTLN ("internal receiver");
Method_inservice ();
}

}
}


Mainac:

Package Com.pas.callmethod;

Import Android.os.Bundle;
Import android.app.Activity;
Import android.content.Intent;
Import Android.view.Menu;
Import Android.view.View;

public class Mainactivity extends activity
{

@Override
protected void OnCreate (Bundle savedinstancestate)
{
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Intent intent=new Intent (this,myservice.class);
StartService (Intent);
}

@Override
public boolean Oncreateoptionsmenu (Menu menu)
{
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}

public void Call (View v)
{
Send a custom broadcast
Intent intent=new Intent ();
Intent.setaction ("Com.pas.call");
Sendbroadcast (Intent);
}
}

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.