还剩27页未读,继续阅读
本资源只提供10页预览,全部文档请下载后查看!喜欢就下载吧,查找使用更方便
文本内容:
目录
一、复习重点、字符、数组资源的定义
1、与适配器的使用2Spinner、清单文件关于活动、服务、广播、内容提供者的配置,3intent-filter的配置,如设置为启动的Activity、服务,和如如何定义的子4Service IntentServer,IntentServer类、通知的编程
5、广播的编程6
二、[Spinner]package com.gdlgxy.componentsdemo;import androidx.appcompat.app.AppCompatActivity;if player!=nullplayer.startf;}/***You should not overridethis methodfor yourIntentService.Instead,*override{@link#onHandlelntent},which the system callswhen the IntentService*receives astart request.**@param intent*@param flags*@param startId*@see Service#onStartCommand*/@Overridepublic intonStartCommand@Nullable Intent intent,int flags,int{〃该方法不是一定要重写,在这里重写是为了理解回调方startld法的回调顺序调用Log.dFLAG,onStartCommand;调用顺序、调用构造方法return START_NOT_STICKY;/*:1调用、调用ServiceDemo2onCreatef3onStartCommand*/」与上相同*///return START_REDELIVER NTENT;/*与上相同*///return START_STICKY;/*//return super.onStartCommandintent,flags,startld;/*调用顺序、调用构造方法、调用1lntentServiceDemo2onCreate、调用、调用、调用3onStartCommand4onStart5onHandlelntent、调用6onDestroy*/}©Override{〃该方public voidonStart@Nullable Intentintent,int startId法不是一定要重写,在这里重写是为了理解回调方法的回调顺序super.onStartintent,startld;调用Log.dFLAG,onStart;/***Unless youprovide bindingfor yourservice,you dontneed toimplementthis*method,because the default implementationreturnsnull.**@param intent*@see Service#onBind*/@Nullable@Override{〃该方法不是一定要重public IBinderonBindlntent intent写,在这里重写是为了理解回调方法的回调顺序调用Log.dFLAG,onBindf;return super.onBindintent;}与U![Service Notification]package com.gdlgxy.servicedemo;import android.app.Notification;import android.app.Notificationchannel;import android.app.NotificationManager;import android.app.Pendingintent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.media.MediaPlayer;import android.os.AsyncTask;import android.os.Binder;import android.os.Build;import android.os.lBinder;import android.util.Log;import androidx.annotation.Nullable;import androidx.core.app.NotificationManagerCompat;{〃绑定服务在服务端做好public classServiceDemo extendsService个步骤4private finalString FLAG=abc;MediaPlayer player;〃定义一个实例绑private LocalBindermLocalBinder;Binder定服务第步,定义实例2Binderprivate NotificationManager manager;private Notification.Builder builder;更新进度的线程private ThreadProgressThread;//{〃该方法不一定要定义,构造方法第一个public ServiceDemo被调用super;Log.dFLAG,”调用构造方法ServiceDemon;/***Called bythe systemwhenthe service isfirst created.Do notcallthis methoddirectly.*/©Override{〃该方法在服务仓建时仅被调用一次,public voidonCreate U在调用构造方法之后调用该方法super.onCreate;调用”;Log.dFLAG,onCreatemanager=NotificationManagergetSystemServiceNOTIFICATION_SERVICE;;//初始化实例,mLocalBinder=new LocalBinder Binder绑定服务第步,初始化实例3Binderif player==nullplayer=MediaPlayer.creategetApplicationContext,R.raw.chengdu_zaolei;***@param intent*@param startId*@deprecated Implement{@link#onStartCommandlntent,int,int}instead.*/@Overridepublic voidonStartflntent intent,int startId{super.onStartintent,startld;调用Log.dFLAG,onStart;/***Called whennew clientshave connectedto theservice,after ithad*previously beennotified thatall haddisconnected inits*{@link#onllnbind}.This willonly becalled if theimplementation*of{@link#onllnbind}was overriddento returntrue.**@param intentThe Intentthat wasused tobind tothisservice,as givento{@link Context#bindServiceContext.bindService}.Note thatanyextras thatwere includedwith*the Intentat thatpoint willemnot/embe seenhere.*/@Overridepublic voidonRebindflntent intent{super.onRebindintent;调用Log.dFLAGJ onRebindf;/***Called bythe systemto notifya Servicethat it is nolongerused andis beingremoved.The*service shouldclean upany resourcesit holdsthreads,registered*receivers,etc atthis point.Upon return,there willbe nomorecalls*in tothis Serviceobject and itiseffectively dead.Do notcallthis methoddirectly.*/©Override停止服务或服务注销时调用,注意public voidonDestroy{//如果该方法没有调用,哪怕是结束播放,服务依然没MediaPlayer有停止super.onDestroy;调用Log.dFLAG,onDestroy;{〃如果将这段代码注释掉,则服务停止,if player!=null但继续播放MediaPlayer〃这种情况下结束播放,听player.stop;MediaPlayer不到声音if!ProgressThread.islnterrupted{ProgressThread.interrupt;}}/***Called bythe systemevery timea clientexplicitly startstheservice bycalling*{@link Context#startService},providing thearguments itsuppliedand a*unique integertoken representingthe start request.Donot callthis methoddirectly.**pFor backwardscompatibility,thedefaultimplementationcalls*{@link#onStart}and returnseither{@link#START_STICKY}*or{@link#START_STICKY_COMPATIBILITY}.**p class=,,caution,,Note thatthesystemcalls thisonyour*services main thread.A servicesmainthreadis thesame*thread whereUI operationstake placefor Activitiesrunning inthe*same process.You shouldalways avoidstalling themain*threads eventloop.When doinglong-runningoperations,*network calls,or heavydisk I/O,you shouldkick offanew*thread,or use{@link AsyncTask}./p**{@「@param intentThe Intentsupplied tonk Context#startService},*as given.This maybe nullif theserviceis beingrestarted after*its processhas goneaway,andithadpreviously returnedanythingexcept{@link#START_STICKY_COMPATIBILITY}.*@param flagsAdditional dataabout thisstartrequest.*@param startId Aunique integerrepresenting thisspecificrequest to*start.Use with{@link#stopSelfResultint}.*@return Thereturn valueindicates whatsemantics thesystemshould*use forthe servicescurrent startedstate.It maybe oneof the*constants associatedwith the{@link#START_CONTINUATION_MASK}bits.*@see#stopSelfResultint*/@Override{〃public intonStartCommandlntent intent,int flags,int startId该方法可以被多次调用调用1;Log.dFLAG,onStartCommandif player!=nullplayer.start;调用顺序、调用构造方//return START_NOT_STICKY;/*:1法、调用、调用ServiceDemo2onCreate3onStartCommand,import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.ViewManager;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.RadioButton;import android.widget.Spinner;import android.widget.Toast;public classSecondActivity extendsAppCompatActivity{Spinner spinnerl;Button stepback_btn,next_btn;RadioButton radioButtonl,radioButton2;private Bundleselectstring;@Overrideprotected voidonCreateBundle savedI nstanceState{super.onCreatesavedlnstanceState;setContentViewR.layout.activity_second;selectstring=new Bundle;注意没有调用*/onStart」与上相同*///return START_REDELIVER NTENT;/*与上相同*///return START_STICKY;/*调用return super.onStartCommandintent,flags,startld;/*顺序、调用构造方法、调用、调用:1ServiceDemo2onCreate3调用onStartCommand4onStartf*/}/***Return thecommunication channelto theservice.May returnnullif*clients cannot bind to theservice.The returned*{©link IBinder}is usuallyfor acomplex interface*that hasbeen ahref=,,{@docRoot}guide/components/aidl.htmr,described using*aidl/a.**pxemNote thatunlike otherapplication components,callson tothe*IBinder interfacereturned heremay nothappen on the mainthread*of theprocess/em.More informationabout themainthread canbe foundin*ahref=n{@docRoot}guide/topics/fundamentals/processes-and-threads.htmrProcesses and*Threads/a./p**@param intentThe Intentthat wasused tobind tothisservice,*as givento{@link Context#bindService*Context.bindService}.Note thatanyextras thatwere includedwith*the Intentat thatpoint willemnot/embe seenhere.*@return Returnan IBinderthrough whichclients cancall ontothe*service.*/@Nullable@Override{〃绑定时调用public IBinderonBindlntent intent调用Log.dFLAGJ onBindO;if player!=nullplayer.startf;〃返回实例,绑定服务第步,从return mLocalBinder;Binder4返回实例如果返回则无法绑定onBirid Bindernull}/***Called whenall clientshave disconnectedfrom aparticularinterface*published bytheservice.The defaultimplementation doesnothingand*returns false.**@param intentThe Intentthat wasused tobindtothisservice,*as givento{@link Context#bindService*Context.bindService}.Note thatanyextras thatwere includedwith*the Intentat thatpoint willemnot/embe seenhere.*@return Returntrue ifyou wouldlike tohave theserviced*{@link#onRebind}method latercalled whennew clientsbindto it.@Override{〃解绑定时调用public booleanonllnbindlntent intent调用Log.dFLAG,onUnbind;{〃如果将这段代码注释掉,则服务停止,if player!=null但继续播放MediaPlayer〃这种情况下结束播放,听player.stop;MediaPlayer不到声音}manager.cancelAII;if!ProgressThread.islnterrupted11ProgressThread.isAlive{ProgressThread.interrupt;}return super.onUnbindintent;}{〃绑定服务第步,自public classLocalBinder extendsBinder1定义扩展类在该类中创建实例,当然Binder,Binder,BinderBinder应该实现某些操作{〃为客户端提供public ServiceDemogetService方法,检索的当前实例getService ServiceDemo〃返回当前的return ServiceDemo.this;ServiceDemo实例}}public voidSendNotificationContext context,String channelld,intnotificationlD{if Build.VERSION.SDKJNT=Build.VERSION_CODES.O{Notificationchannel channel=newNotificationChannelfchannelld,simple,NotificationManagerCompat.lMPORTANCE_DEFAULT;manager.createNotificationChannelchannel;Intent notificationintent=new lntentthis,MainActivity.class;Pendingintent pendingintent=Pendingintent.getActivitythis,0,notificationintent,0;builder=new Notification.Builderfcontext,channelld;音乐播放builder.setContentTitle.setContentTextgetResources.getResourceEntryNameR.raw.chengdu_zaolei+,,JH.setSmalllconR.mipmap.icJauncher.setPriorityNotification.PRIORITY_LOW.setContentlntentpendinglntent.setOnlyAlertOncetrue.setProgressplayer.getDuration,player.getCurrentPosition,false;manager.notifyfnotificationlD,builder.build;final intID=notificationlD;ProgressThread=new ThreadnewRunnable{©Overridepublic voidrun{while!ProgressThread.isAlivef11player.getCurrentPosition=player.getDuration{try秒刷新进Thread.sleep5000;//5度builder.setProgressplayer.getDuration,player.getCurrentPosition,〃更新进度false.setSoundnull,null;manager.notifyID,〃更新通知消息builder.build;}catch InterruptedExceptione{manager.cancelID;stopSelfID;}};P rogressThread.start;}
五、【BroadcastReceiver]public classBroadcastReceiverDemo extendsBroadcastReceiver{private finalString TAG=abc;@Overridepublic voidonReceiveContext context,Intentintent{StringBuilder sb=new StringBuilder;sb.appendHAction:”+intent.getAction+“\n;sb.appendnURI:11intent.toUrilntent.URIJNTENT_SCHEME.toString+\n;通过本消息特别说明,我接收到了隐匿广播sb.append了!;“+\n“String log=sb.toString;Log.dTAG,log;Toast.makeTextcontext,log,Toast.LENGTH_LONG.show;}radioButtonl=RadioButtonfindViewByldR.id.radioButton1;radioButton2=RadioButtonfindViewByldR.id.radioButton2;radioButtonl.setOnClickListenernew View.OnClickListener{@Override publicvoid onClickView v{onRadioButtonClickv;};radioButton
2.setOnClickListenernew View.OnClickListener{@Override public voidonClickView v{onRadioButtonClickv;};spinnerl=SpinnerfindViewByldR.id.spinnerl;ArrayAdaptermArrayAdapter=ArrayAdapter.createFromResourcethis,R.array.stringJist,android.R.layout.simple_spinner_dropdown_item;spinnerl.setAdaptermArrayAdapter;spinnerl.setOnltemSelectedListenernewAdapterView.OnltemSelectedListener{@Overridepublic voidonltemSelectedAdapterView parent,View view,int position,long id{selectstring.putString,,college,,,parent.getltemAtPositionposition.toString;©Overridepublic voidonNothingSelectedAdapterViewparent{};stepback_btn=ButtonfindViewByldR.id.buttonl;next_btn=ButtonfindViewByldRjd.button2;stepback_btn.setOnClickListenernewView.OnClickListenerf{@Overridepublic voidonClickView v{Intent mintent=newlntentSecondActivity.this,MainActivity.class;sta rtActivitym Intent;};next_btn.setOnClickListenernew View.OnClickListener{@Overridepublic voidonClickViewv{您的基本信息为String info=for Stringvalue:selectString.keySet{info+=selectstring.getvalue+}Toast.makeTextSecondActivity.this,info.substringO,info.Iength-1+,
6000.show;Intent mintent=newlntentSecondActivity.this,ThirdActivity.class;startActivitymlntent;};protected voidonRadioButtonClickView view{selectstring.putString,,sex,,,RadioButtonview.getText.toString;}
三、[intentservice]package com.gdlgxy.servicedemo;import android.app.IntentService;import android.app.Service;import android.content.Context;import android.content.Intent;import android.media.Media Player;import android.os.lBinder;import android.util.Log;import androidx.annotation.Nullable;public classIntentServiceDemo extendsIntentService{private finalStringFLAG=,,abc;MediaPlayer player;^Override{〃该方法不是一定要重写,在这里重写public voidonCreate是为了理解回调方法的回调顺序,在调用构造方法之后调用该方法super.onCreate;调用Log.dFLAG,onCreatef;if player==nullplayer=MediaPlayer.creategetApplicationContext,R.raw.chengdu_zaolei;}/***Creates anIntentService.Invoked byyour subclasssconstructor.**@param nameUsed toname theworker thread,importantonly fordebugging.*/{〃该方法一定要定义,构造方法第public IntentServiceDemo一个被调用superlntentServiceDemo;调用构造方法;Log.dFLAG,”IntentServiceDemo}©Override{〃该方法不是一定要重写,在这里重publicvoidonDestroy写是为了理解回调方法的回调顺序super.onDestroyf;调用Log.dFLAG,onDestroy;〃{〃如果将这段代码注释掉,则服务启动、执if player!=null行,完毕停止,但继续播放MediaPlayer〃这种情况下结束播放,//player.stop;MediaPlayer听不到声音//player.release;//}/***This methodis invokedontheworker threadwith arequestto process.*Only oneIntent isprocessed ata time,but theprocessinghappens ona*worker threadthat runsindependently fromotherapplication logic.*So,if thiscode takesa longtime,it willhold upotherrequests to*the sameIntentService,but itwill nothold upanythingelse.*When allrequests havebeen handled,the IntentServicestopsitself,*so youshouldnotcall{@link#stopSelf}.**@param intentThe valuepassed to{@link*Context#startServicelntent}.*This maybe nulliftheservice isbeingrestarted after*its processhas goneaway;see*{@link Service#onStartCommand}*for details.*/@Override{〃该方protected voidonHandlelntent@Nullable Intentintent法一定要定义调用Log.dFLAG”onHandlelntentO;。
个人认证
优秀文档
获得点赞 0