public void onClick(Viewv) (stopService(newIntent(ServiceDemo.ACTION)1),bindBtn.setOnClickListener(new View.OnClickListenerOpublic void onClick(Viewv) bindService(newIntent(ServiceDemo.ACTION)conn,BIND AUTO CREATE);33);unbindBtn.setOnClickListener(newView.OnClickListenerOpublic void onClick(Viewv) unbindService(conn);13),3@Overrideprotected void onDestroyOsuper.onDestroyO;10运行程序在Android实验箱上运行程序,观察和记录实验结果单击"BINDSERVICE"按钮,启动绑定服务,“AndroidStudiolAndroidMonitorllogcat"中运行结果如下图所示。其中:回调方法onCreateO在服务创建时调用,回调方法onBindO在服务绑定时调用。19
19 public void onClick(View v) { stopService(new Intent(ServiceDemo.ACTION)); } }); bindBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { bindService(new Intent(ServiceDemo.ACTION), conn, BIND_AUTO_CREATE); } }); unbindBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { unbindService(conn); } }); } @Override protected void onDestroy() { super.onDestroy(); }; } 10 运行程序 在 Android 实验箱上运行程序,观察和记录实验结果 单击“BIND SERVICE”按钮,启动绑定服务,“Android Studio|Android Monitor|logcat”中运行 结果如下图所示。其中:回调方法 onCreate()在服务创建时调用,回调方法 onBind()在服务 绑定时调用
A1032helloservicenalogcatVerboseMfOVR:27:035 1194-1194/con.exanpte,hellossServicecene anernatne6-11CSRSrVTPSAndroid Montor生RunTOOoWEventLeg再次单击"BINDSERVICE"按钮,再次绑定服务,“AndroidStudioAndroidMonitorlogcat"中将无新的输出,因为服务已经绑定。单击"UNBINDSERVICE"按钮,取消绑定服务,“AndroidStudioAndroidMonitorlogcat"中运行结果如下图所示。其中:回调方法onUnbindO在取消服务绑定时调用,回调方法onDestroyO在服务销毁时调用。-e.helloserviceBoxLabw5-Sx-001ttia loocatMonitorsRegexShoworlareedannleatingMessagesAndraidMontorh4RunETODnEventLog国Gradle11修改ServiceDemo类(ServiceDemo.java)中onStartO方法的代码如下,在其中创建子线程,并如下图所示。@Overridepublic void onStart(Intent intent, int startld) I/Log.v(TAG, "ServiceDemo onStart");new Thread(new RunnableO (@Overridepublic void runOLog.v(TAG,"ServiceDemoonStart-NewThread");1).start(),20
20 再次单击“BIND SERVICE”按钮,再次绑定服务,“Android Studio|Android Monitor|logcat”中 将无新的输出,因为服务已经绑定。 单击“UNBIND SERVICE”按钮,取消绑定服务,“Android Studio|Android Monitor|logcat”中运 行结果如下图所示。其中:回调方法 onUnbind()在取消服务绑定时调用,回调方法 onDestroy() 在服务销毁时调用。 11 修改 ServiceDemo 类(ServiceDemo.java)中 onStart()方法的代码如下,在其中创建子线 程,并如下图所示。 @Override public void onStart(Intent intent, int startId) { //Log.v(TAG, "ServiceDemo onStart"); new Thread(new Runnable() { @Override public void run() { Log.v(TAG, "ServiceDemo onStart - New Thread"); } }).start(); }
12运行程序在Android实验箱上运行程序,观察和记录实验结果单击“STARTSERVICE"按钮,启动非绑定服务,“AndroidStudiolAndroidMonitorlogcat"中运行结果如下图所示。其中:可以观察到新线程的输出结果。DOBov5.Snn16n国.com.example.helloservicelooVerbo.RegeReecmoonCreatOcon.exateni-0015:27:54:230 304xanple-hellasericaW/CeiceDeso onStartNevThreaoAndraid MonitarR单击“STOPSERVICE"按钮,停止非绑定服务。3.4Android广播与通知1使用AndroidStudio创建项目应用程序名:HelloBroadcast(加学号作为后缀,后续操作凡是涉及HelloBroadcast都加后缀,不再赞述)。公司域名:com.example(默认)。包名:com.example.hellobroadcast(默认,自动加上学号后缀)。应用程序存放位置:学号目录。Minimum SDK:API15:Android4.0.3(IceCreamSandwich)。活动:EmptyActivity。活动名:MainActivity(默认)。布局名:activity_main(默认)。项目视图:project。如下图所示。2修改activity_main.xml文件双击AndroidStudio左侧app/src/main/res/layout/activity_main.xml文件,修改后的代码如下,并如下图所示。<?xml version="1.0" encoding-"utf-8"?>21
21 12 运行程序 在 Android 实验箱上运行程序,观察和记录实验结果 单击“START SERVICE”按钮,启动非绑定服务,“Android Studio|Android Monitor|logcat”中运 行结果如下图所示。其中:可以观察到新线程的输出结果。 单击“STOP SERVICE”按钮,停止非绑定服务。 3.4 Android 广播与通知 1 使用 Android Studio 创建项目 应用程序名:HelloBroadcast(加学号作为后缀,后续操作凡是涉及 HelloBroadcast 都加后缀, 不再赘述)。 公司域名:com.example(默认)。 包名:com.example.hellobroadcast(默认,自动加上学号后缀)。 应用程序存放位置:学号目录。 Minimum SDK: API 15: Android4.0.3 (IceCreamSandwich)。 活动:Empty Activity。 活动名:MainActivity(默认)。 布局名:activity_main(默认)。 项目视图:project。 如下图所示。 2 修改 activity_main.xml 文件 双击 Android Studio 左侧 app/src/main/res/layout/activity_main.xml 文件,修改后的代码如下, 并如下图所示。 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns: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"><TextViewandroid:layout_width="wrap_content"android:layout height-"wrap contentandroid:layout _alignParentLefl-"true'android:layout centerVertical-"true"android:textSize="30sp"android:text="广播已注册,每隔1分钟发送通知,退出程序则注销广播"/></RelativeLayout>车3修改MainActivity.java文件双击AndroidStudio左侧app/src/main/java/com.example.hellobroadcast/MainActivity.java文件,修改后的代码如下,并如下图所示。packagecom.example.hellobroadcast,import android.app.Notification:importandroid.app.NotificationManagerimportandroid.content.BroadcastReceiver,import android.content.Context;import android.content.Intentimport android.content.IntentFilter,import android.support.v7.app.AppCompatActivity,import android.os.Bundle;import android.widget.Toast,publicclass MainActivityextendsAppCompatActivity22
22 <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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:textSize="30sp" android:text="广播已注册,每隔 1 分钟发送通知,退出程序则注销广播" /> </RelativeLayout> 3 修改 MainActivity.java 文件 双击Android Studio左侧app/src/main/java/com.example.hellobroadcast/MainActivity.java文件, 修改后的代码如下,并如下图所示。 package com.example.hellobroadcast; import android.app.Notification; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity {
private MyReceiver myReceiver,@Overrideprotected void onCreate(Bundle savedlnstanceState)super.onCreate(savedlnstanceState);setContentView(R.layout.activity_main);myReceiver=newMyReceiverO;1@Overrideprotected void onResumeO tII TODO Auto-generated method stubsuper.onResume);//IntentFilterfilter=newIntentFilter(Intent.ACTION_TIME_TICK);registerReceiver(myReceiver, filter);Toast.makeText(this,”广播在方法中注册”已onResumeToast.LENGTH_LONG).showO;3@Overrideprotected void onPauseOII TODO Auto-generated method stubsuper.onPause(),unregisterReceiver(myReceiver);Toast.makeText(this,"广播已在onPause方法中注销",Toast.LENGTH_LONG).show),1privateclassMyReceiverextendsBroadcastReceiver@Overridepublic void onReceive(Context context, Intent intent) I/TODOAuto-generated method stub1INotificationManager(NotificationManager)nm=context.getSystemService(NOTIFICATION_SERVICE);/INotification.Builderbuilder=newNotification.Builder(context),Ilbuilder.setAutoCancel(false).setContentTitle("This is ContentTitle").setContentText("this is Content Text").setContentlnfo("this is Content Info").setSmallcon(R.mipmap.ic_launcher).setWhen(System.currentTimeMillisO);lNotification notification =builder.getNotificationO;Ilnm.notify(o, notification);23
23 private MyReceiver myReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myReceiver = new MyReceiver(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK); registerReceiver(myReceiver, filter); Toast.makeText(this, " 广 播 已 在 onResume 方法中注册 ", Toast.LENGTH_LONG).show(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); unregisterReceiver(myReceiver); Toast.makeText(this, "广播已在 onPause 方法中注销", Toast.LENGTH_LONG).show(); } private class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub // NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); // Notification.Builder builder = new Notification.Builder(context); // builder.setAutoCancel(false) .setContentTitle("This is Content Title") .setContentText("this is Content Text") .setContentInfo("this is Content Info") .setSmallIcon(R.mipmap.ic_launcher) .setWhen(System.currentTimeMillis()); // Notification notification = builder.getNotification(); // nm.notify(0, notification);