Learn android from scratch (BroadCast. 45 .)

Source: Internet
Author: User

Learn android from scratch (BroadCast. 45 .)

Similar to Service, there is also one of the four main components running in the background in android, which is broadCcast, but he does not need to consider whether there are accepted objects, just consider sending.

We can use either of the following methods to use BroadCast:

1. Configure broadCcast in the configuration file.

Second, bind broadCcast to the class file.


Next we will explain it separately.

     
  
 

Broadcasting


Package com. example. broadcast; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. widget. toast; public class BroadCastUtil extends BroadcastReceiver {public void BroadcastReceiver () {System. out. println ("** a broadcast event is created");} @ Overridepublic void onReceive (Context context, Intent intent) {// TODO Auto-generated method stubToast. makeText (context, "broadcast started", 2 ). show ();}}
Main File
Package com. example. broadcast; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private Button button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button1); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // sets to filter Intent intent = new Intent (Intent. ACTION_EDIT); // enable broadcast MainActivity. this. sendBroadcast (intent );}});}}


Add configuration under application Node

             
           
 





Use registerReceiver (BroadcastReceiver, IntentFilter) to bind a filter.

Others do not need to be changed. Only change is required.

The master file is OK. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> package com. example. broadcast; import android. app. activity; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private Button button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button1); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // sets to filter Intent intent = new Intent ("com. example. broadcast "); IntentFilter filter = new IntentFilter (" com. example. broadcast "); BroadCastUtil broadCastUtil = new BroadCastUtil (); MainActivity. this. registerReceiver (broadCastUtil, filter); // enable broadcast MainActivity. this. sendBroadcast (intent );}});}}
In this way, no configuration information is required in the configuration file.

Start Service with broadcast

Service

package com.example.broadecast2;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubSystem.out.println("** SERVICE onCreate");super.onCreate();}@Overridepublic void onDestroy() {// TODO Auto-generated method stubSystem.out.println("** SERVICE onDestroy");super.onDestroy();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubSystem.out.println("** SERVICE onStartCommand");return Service.START_CONTINUATION_MASK;}}
BroadCask

package com.example.broadecast2;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyBroadeCast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent1) {context.startService(new Intent(context,MyService.class)) ;}}

Main

Package com. example. broadecast2; import android. OS. bundle; import android. app. activity; import android. app. pendingIntent; import android. content. intent; import android. view. menu; // use broadcast to start the public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Intent intent = new Intent ("com. example. broadecast2.DEMO "); MainActivity. this. sendBroadcast (intent );}}




Use broadcast for alarm control

     
      
      
      
  
 
Dialog Box
Package com. example. broadcast3; import java. text. simpleDateFormat; import java. util. date; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. OS. bundle; public class AlertMessage extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState); new AlertDialog. builder (this ). setIcon (R. drawable. b9 ). setTitle ("alarm time "). setMessage ("current time:" + new SimpleDateFormat ("MM dd, yyyy, HH, mm, ss seconds "). format (new Date ())). setNegativeButton ("cancel", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// TODO Auto-generated method stubAlertMessage. this. finish ();}}). create (). show ();}}

Broadcasting

package com.example.broadcast3;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyBroadCast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubIntent it = new Intent(context, AlertMessage.class);it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(it);}}
Main

Package com. example. broadcast3; import java. util. calendar; import android. OS. bundle; import android. r. integer; import android. app. activity; import android. app. alarmManager; import android. app. pendingIntent; import android. content. context; import android. content. intent; import android. view. menu; import android. view. view; import android. widget. button; import android. widget. textView; import android. widget. timePick Er; import android. widget. timePicker. onTimeChangedListener; import android. widget. toast; public class MainActivity extends Activity {private Button set, delete; private TextView info; private TimePicker time; private int hour; private int minute; private Calendar calendar = Calendar ar. getInstance (); private AlarmManager alarm; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (sav EdInstanceState); setContentView (R. layout. activity_main); set = (Button) this. findViewById (R. id. button1); delete = (Button) this. findViewById (R. id. button2); info = (TextView) this. findViewById (R. id. textView1); time = (TimePicker) this. findViewById (R. id. timePicker1); time. setIs24HourView (true); this. alarm = (AlarmManager) super. getSystemService (Context. ALARM_SERVICE); time. setOnTimeChangedListener (new OnTimeCh AngedListener () {@ Overridepublic void onTimeChanged (TimePicker view, int hourOfDay, int minute) {// TODO Auto-generated method stubMainActivity. this. hour = hourOfDay; MainActivity. this. minute = minute; MainActivity. this. calendar. setTimeInMillis (System. currentTimeMillis (); MainActivity. this. calendar. set (Calendar. HOUR_OF_DAY, hourOfDay); MainActivity. this. calendar. set (Calendar. MINUTE, minute); MainActivi Ty. this. calendar. set (Calendar. SECOND, 0); MainActivity. this. calendar. set (Calendar. MILLISECOND, 0) ;}}); set. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubIntent intent = new Intent (MainActivity. this, AlertMessage. class); intent. setAction ("com. example. broadcast3 "); PendingIntent sender = PendingIntent. getActivity (MainActivity. this, 0, intent, PendingIntent. FLAG_UPDATE_CURRENT); MainActivity. this. alarm. set (AlarmManager. RTC_WAKEUP, MainActivity. this. calendar. getTimeInMillis (), sender); MainActivity.this.info. setText ("when the alarm is triggered:" + MainActivity. this. hour + "hour" + MainActivity. this. minute + "points. "); Toast. makeText (MainActivity. this," the alarm is set successfully! ", Toast. LENGTH_LONG ). show () ;}}); delete. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubif (MainActivity. this. alarm! = Null) {Intent intent = new Intent (MainActivity. this, MyBroadCast. class); intent. setAction ("org. lxh. action. setalarm "); PendingIntent sender = PendingIntent. getBroadcast (MainActivity. this, 0, intent, PendingIntent. FLAG_UPDATE_CURRENT); MainActivity. this. alarm. cancel (sender); // cancel MainActivity.this.info. setText ("no alarm is set currently. "); Toast. makeText (MainActivity. this," the alarm is deleted successfully! ", Toast. LENGTH_LONG). show ();}}});}}



Next prediction: basic android plotting


Related Article

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.