Android One of the four components :service:

Service There are five life cycles :onCreat,onStartCommand, onBind,onUnbind, onDestroy

There are mainly two ways of binding and unbound

 The prime minister is here Activity There are four Button, For testing both bound and unbound , Press down Button Play music , Stop the music , Unbound with StopService stop it , The binding method uses Bind Service start-up , For unbinding unbindService stop it .
 Unbound :Intent intent=new Intent(MainActivity.this,MyService.class);
start Service(intent);/stopSercice(intent)
 from Activity start-up service Mainly use the above code ,
 
 binding :Intentintent=newIntent(MainActivity.this,MyService.class);
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
serviceConnection by :
private ServiceConnection serviceConnection=new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name,
                                   IBinder service) {
     myService=((MyService.MyBinder)service).getService();
    }     @Override
    public void onServiceDisconnected(ComponentName name) {     }
};
 The binding method is fixed 
 stay Service You can also use function callbacks to perform certain operations 
 Function callbacks generally have four steps :
1. Define an excuse , Define a method in an excuse 
2. Activity In order to realize this excuse , And the method in the excuse 
3.Service In the definition of public static void setMusicStop(Context context){
    stopImg = (StopImg) context;
}
4. stay Activity You can call Service The method in .
 Function callbacks are generally divided into these four steps .
 Function callbacks are not only used for Activity And Service in , It can also be used for Activity And Activity in .
 Function callbacks are commonly used in music players .
 
 
Broadcast: radio broadcast 
 The registration method is not static 、 Dynamic two ways 
 Static is manually registered in the manifest file 
<receiver
    android:name=".Broadcast.MySMS"
    android:enabled="true"
    android:exported="true"
>
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>
 Among them android:name="android.provider.Telephony.SMS_RECEIVED"
 Name defined for yourself 
 
 Dynamic registration :
// Dynamic registration broadcast 
IntentFilter intent Filter=new IntentFilter();
intentFilter.addAction("android.jredu.action.WEN");
registerReceiver(new MyactiveBroad(),intentFilter);
 
 
 
public class MyactiveBroad extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        String arg2 = intent.getStringExtra("arg2");
        Log.d("=========== Accept ======",arg2);
    }
}
 After the radio registration is completed , And the next inheritance BroadcastReceiver Methods , Used to receive broadcast content , Where do you want to receive the radio , Where to register for broadcasting .
 
 Write a broadcast test program to illustrate : Use what I said before Service
 
 First , Build a Activity1, Set the two Button,
 A test static registration , One for jump test dynamic registration .
 Build another one Service, Static registration ,
 
 
 stay Service In manifest file , Join in 
<receiver
    android:name=".Broadcast.MyReceiver"
    android:enabled="true"
    android:exported="true"
>
    <intent-filter>
        <action android:name="android.jredu.broadcast.ZHANG" />
    </intent-filter>
</receiver>
 This statically registers a broadcast , Broadcast name by 
<action android:name="android.jredu.broadcast.ZHANG" />
 Build another one Activity2, Test dynamic sending .
 
 
 for Activity1 The content of 
public class BroadcastActivity extends AppCompatActivity {
    private Button bt1,bt2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);
        bt1= (Button) findViewById(R.id.bt1);
        bt2= (Button) findViewById(R.id.bt2);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("arg"," Hello ");
                intent.setAction("android.jredu.broadcast.ZHANG");
                sendBroadcast(intent);
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getBaseContext(),BroadActivity.class);
                startActivity(intent);
            }
        });
        // Dynamic registration broadcast
       
IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("android.jredu.action.WEN");
        registerReceiver(new MyactiveBroad(),intentFilter);     }
    public class MyactiveBroad extends BroadcastReceiver{         @Override
        public void onReceive(Context context, Intent intent) {
            String arg2 = intent.getStringExtra("arg2");
            Log.d("=========== Accept ======",arg2);
        }
    }
}
 
 for Activity2 The content of : There is one of them. Button, Press send broadcast 
public class BroadActivity extends AppCompatActivity {
    private Button bt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broad);
        bt1= (Button) findViewById(R.id.bt1);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("arg2","42870");
                intent.setAction("android.jredu.action.WEN");
                sendBroadcast(intent);
            }
        });
    }
}

Android Of the four components service And Broadcast More articles about

  1. Android Of the four components Service

    Android Of the four components Service Android The concept of support services , Services are components that run in the background , No user interface ,Android Services can have a lifecycle independent of activities .Android Supports two types of services : The local service : ...

  2. 【Android Development diary 】 Introduction to ( 5、 ... and )——Android Of the four components Service

    I'm busy with driving school test these days , I can't even touch the computer , It's finally over today ~~Service As Android The service component of , Silently serve the whole program in the background , The auxiliary application communicates with other components or system services in the system . It goes with Activity Of ...

  3. Android Growth Diary -Android Of the four components Service Component learning

    1. What is? Service? Service yes Android Among the four major components, there are Activity The most similar component , They all represent executable programs ,Service And Activity The difference is that :Service Always running in the background , it ...

  4. Android One of the four components Service Introduce -android Learning journey ( Twelve )

    Basic concepts : service yes android One of the four components , Running time-consuming operations in the background , It doesn't provide a user interface . Other components such as acticity Can pass startService Start the component , It can also be done through bindService ...

  5. Android One of the four components -- Service Detailed explanation

    I believe most of my friends are right Service This term is not strange , you 're right , An experienced Android If the programmer even Service Never heard of anything , That's too bad .Service As Android One of the four components , In every application ...

  6. Android Four components :Service

    Preface Service As Android One of the four components , Very widely used This article will introduce the concept of Service Give a full introduction ( Basic knowledge . Life cycle . Usage and application scenarios ) Catalog Catalog 1. Basic knowledge of Definition : service , Belong to Androi ...

  7. Android Of the four components Service My humble opinion

    Service yes Android One of the four components , It can run in the background without displaying the interface . Another function is through AIDL To achieve interprocess communication . Service Mode of starting Service There are two ways to start ,startSe ...

  8. Android Of the four components Service

    --- Resume content start --- 1,Service Life cycle of

  9. To talk about Android Of the four components Service piece

    Service brief introduction Service yes Android One of the four components in the system , It's a long life cycle , No visual interface , A service program running in the background .Service Must be in AndroidManifest.xml In a statement ...

Random recommendation

  1. Don't use return false prevent event Default behavior

    When we click on a a When labeling , If this label is href It points to another address , The browser will jump to this address by default . In the page , Sometimes we need to trigger click events , But I don't want to trigger the default behavior , We need to stop event The default behavior of . routine ...

  2. Hello, AnnsShadow!

    Hello! It's been almost a year since I found this magical garden , It's been a year since I had a bumpy learning experience , Think , For so long , It's time to take notes and be a sharer . From the beginning, I only dare to see Blog, So far, I want to express my feelings and thoughts , It's a kind of growth ...

  3. The first gui program by Qt

    #include<QApplication> #include<QPushButton> int main(int argc, char **argv) {     QAppl ...

  4. console, And define events for yourself

    console.log This command outputs the log in the browser console , Used to debug programs Follow alert similar But not like alert That would interrupt the program .

  5. ubuntu Under the supervisor start-up express The problem of failure

    ubuntu Next apt-get install nodejs The next startup command is nodejs, And different from windows Under the node So I am supervisor start-up express There was a problem The tips are as follows : / ...

  6. haproxy Configuration file analysis of

    function --> Provide high availability / Load balancing / be based on tcp and http Agent for application ; Support virtual host , It is especially suitable for heavy load web Site . Profile parsing --> # The configuration file --> Turn on /proc/net/ipv4 ...

  7. springMVC3 Study ( Four )-- Access static files such as js,jpg,css

    Suppose your DispatcherServlet Intercept is *.do such URL. There is no access to static resources Suppose your DispatcherServlet Intercepted "/" All requests , At the same time ...

  8. django---- utilize Form Whether the two password inputs are the same ( Local hook and global hook )

    from django import forms # Import form module from django.core.exceptions import ValidationError class RegisterF ...

  9. linux Users and groups

    1. The user belongs to the user group . 2. User and user group profiles 1) User group profile /etc/group First column : The group name of the user group Second column : Set the password ( The real password is stored in gshadow in ) The third column : User groups ID, The user group is ...

  10. Redis note ( 6、 ... and ):Java Use in Redis

    Java Program usage Redis Add dependency package Maven Dependent manner <dependency> <groupId>redis.clients</groupId> <ar ...