Service..,.,....
Chapter 09 GUI,. ( ) Thread AsyncTask... Toasts non modal,....,,.,.. Alarms.,,.,( ).,,,.,,.
397,,.,,.... ( ).. (, ).,.. MP3..,,. startservice.,. Service., 9 1 onbind oncreate. import android.app.service; import android.content.intent;
Chapter 09 import android.os.ibinder; public class MyService extends Service { public void oncreate() { // TODO:. public IBinder onbind(intent intent) { // TODO:. return null; onstartcommand. startservice,.. onstartcommand 2.0 onstart. onstartcommand onstart, stopservice stopself. 9 1 onstartcommand... public int onstartcommand(intent intent, int flags, int startid) { // TODO:. return Service.START_STICKY;., onstartcommand GUI. onstartcommand
399, ( ). onstartcommand, Service. START_STICKY. 2.0 onstart. onstartcommand., onstartcommand null. (startservice stopservice ).. START_NOT_STICKY. stopself., pending start calls. startservice, onstartcommand., network polling.. START_REDELIVER_INTENT.., stopself. onstartcommand,.
Chapter 09 stopservice stopself.. onstart onstart onstartcommand START_STICKY onstartcommand. startservice. START_STICKY null, START_ REDELIVER_INTENT. flag. 9 2. START_FLAG_REDELIVERY. stopself. START_FLAG_RETRY. START_STICKY. public int onstartcommand(intent intent, int flags, int startid) { if ((flags & START_FLAG_RETRY) == 0) { // TODO:. else { // TODO:. return Service.START_STICKY;
401. application <service>. requires-permission. service. <service android:enabled="true" android:name=".myservice"/> stopself. stopself. startservice, startid stopself. stopself(startid);... startservice.,., startservice SecurityException. onstart. 9 3.
Chapter 09 //. Intent myintent = new Intent(MyService.ORDER_PIZZA); myintent.putextra("topping", "Margherita"); startservice(myintent); //. startservice(new Intent(this, MyService.class)); MyService ORDER_PIZZA ORDER_PIZZA stopservice. 9 4, startservice. ComponentName service = startservice(new Intent(this, BaseballWatch.class)); //. stopservice(new Intent(this, service.getclass())); //. try { Class serviceclass = Class.forName(service.getClassName()); stopservice(new Intent(this, serviceclass)); catch (ClassNotFoundException e) { startservice onstartcommand. startservice. startservice stopservice. 5 6, 7, 8..
403 1. Service EarthquakeService. package com.paad.earthquake; import android.app.service; import android.content.intent; import android.os.ibinder; import java.util.timer; import java.util.timertask; public class EarthquakeService extends Service { public void oncreate() { // TODO:, GUI. public IBinder onbind(intent intent) { return null; 2. application service. <service android:enabled="true" android:name=".earthquakeservice"/> 3. Earthquake refreshearthquakes addnewquake Earthquake Service. addquaketoarray loadquakesfromprovider ( Earthquake ). EarthquakeService earthquakes.
Chapter 09 private void addnewquake(quake _quake) { ContentResolver cr = getcontentresolver(); // // where. String w = EarthquakeProvider.KEY_DATE + " = " + _quake.getdate().gettime(); //. Cursor c = cr.query(earthquakeprovider.content_uri, null, w, null, null); if (c.getcount()==0){ ContentValues values = new ContentValues(); values.put(earthquakeprovider.key_date, _quake.getdate().gettime()); values.put(earthquakeprovider.key_details, _quake.getdetails()); double lat = _quake.getlocation().getlatitude(); double lng = _quake.getlocation().getlongitude(); values.put(earthquakeprovider.key_location_lat, lat); values.put(earthquakeprovider.key_location_lng, lng); values.put(earthquakeprovider.key_link, _quake.getlink()); values.put(earthquakeprovider.key_magnitude, _quake.getmagnitude()); cr.insert(earthquakeprovider.content_uri, values); c.close(); private void refreshearthquakes() { // XML. URL url; try { String quakefeed = getstring(r.string.quake_feed); url = new URL(quakeFeed); URLConnection connection; connection = url.openconnection(); HttpURLConnection httpconnection = (HttpURLConnection)connection; int responsecode = httpconnection.getresponsecode(); if (responsecode == HttpURLConnection.HTTP_OK) { InputStream in = httpconnection.getinputstream();
405 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newdocumentbuilder(); //. Document dom = db.parse(in); Element docele = dom.getdocumentelement(); //. NodeList nl = docele.getelementsbytagname("entry"); if (nl!= null && nl.getlength() > 0) { for (int i = 0 ; i < nl.getlength(); i++) { Element entry = (Element)nl.item(i); Element title; title = (Element)entry.getElementsByTagName("title").item(0); Element g = (Element)entry.getElementsByTagName("georss:point").item(0); Element when = (Element)entry.getElementsByTagName("updated").item(0); Element link = (Element)entry.getElementsByTagName("link").item(0); String details = title.getfirstchild().getnodevalue(); String hostname = "http://earthquake.usgs.gov"; String linkstring = hostname + link.getattribute("href"); String point = g.getfirstchild().getnodevalue(); String dt = when.getfirstchild().getnodevalue(); SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); Date qdate = new GregorianCalendar(0,0,0).getTime(); try { qdate = sdf.parse(dt); catch (ParseException e) { e.printstacktrace(); String[] location = point.split(" "); Location l = new Location("parsed"); l.setlatitude(double.parsedouble(location[0])); l.setlongitude(double.parsedouble(location[1])); String magnitudestring = details.split(" ")[1];
Chapter 09 int end = magnitudestring.length()-1; double magnitude = Double.parseDouble(magnitudeString.substring(0, end)); details = details.split(",")[1].trim(); Quake quake = new Quake(qdate, details, l, magnitude, linkstring); //. addnewquake(quake); catch (MalformedURLException e) { e.printstacktrace(); catch (IOException e) { e.printstacktrace(); catch (ParserConfigurationException e) { e.printstacktrace(); catch (SAXException e) { e.printstacktrace(); finally { 4. Earthquake refreshearthquakes. EarthquakeService. private void refreshearthquakes() { startservice(new Intent(this, EarthquakeService.class)); 5. EarthquakeService. onstartcommand oncreate. onstartcommand START_STICKY..,..
407 6 Shared Preferences. private Timer updatetimer; private int minimummagnitude = 0; private boolean autoupdate = false; private int updatefreq = 0; public int onstartcommand(intent intent, int flags, int startid) { // Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); autoupdate = prefs.getboolean(preferences.pref_auto_update, false); minimummagnitude = Integer.parseInt(prefs.getString(Preferences.PREF_MIN_MAG, "0")); updatefreq = Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0")); updatetimer.cancel(); if(autoupdate) { updatetimer = new Timer("earthquakeUpdates"); updatetimer.scheduleatfixedrate(new TimerTask() { public void run() { refreshearthquakes();, 0, updatefreq*60*1000); import import android.content.sharedpreferences; import android.content.res.resources; import android.preference.preferencemanager;
Chapter 09 refreshearthquakes(); ; return Service.START_STICKY; public void oncreate() { updatetimer = new Timer("earthquakeUpdates"); 6. EarthquakeService. Earthquake EarthquakeMap. EarthquakeService.. 6.1. addnewquake announcenewquake. public static final String NEW_EARTHQUAKE_FOUND = "New_Earthquake_Found"; private void addnewquake(quake _quake) { ContentResolver cr = getcontentresolver(); // // where. String w = EarthquakeProvider.KEY_DATE + " = " + _quake.getdate().gettime(); //. if (cr.query(earthquakeprovider.content_uri,
409 null, w, null, null).getcount()==0){ ContentValues values = new ContentValues(); values.put(earthquakeprovider.key_date, _quake.getdate().gettime()); values.put(earthquakeprovider.key_details, _quake.getdetails()); double lat = _quake.getlocation().getlatitude(); double lng = _quake.getlocation().getlongitude(); values.put(earthquakeprovider.key_location_lat, lat); values.put(earthquakeprovider.key_location_lng, lng); values.put(earthquakeprovider.key_link, _quake.getlink()); values.put(earthquakeprovider.key_magnitude, _quake.getmagnitude()); cr.insert(earthquakeprovider.content_uri, values); announcenewquake(_quake); private void announcenewquake(quake quake) { 6.2. announcenewquake. private void announcenewquake(quake quake) { Intent intent = new Intent(NEW_EARTHQUAKE_FOUND); intent.putextra("date", quake.getdate().gettime()); intent.putextra("details", quake.getdetails()); intent.putextra("longitude", quake.getlocation().getlongitude()); intent.putextra("latitude", quake.getlocation().getlatitude()); intent.putextra("magnitude", quake.getmagnitude()); sendbroadcast(intent); 7. EarthquakeService. Earthquake announcenewquake. 7.1. Earthquake BroadcastReceiver Earthquake Receiver. onreceive
Chapter 09 loadquakesfromprovider earthquakes. public class EarthquakeReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { loadquakesfromprovider(); 7.2. onresume 7.1. onpause, onresume. EarthquakeReceiver receiver; public void onresume() { IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); loadquakesfromprovider(); super.onresume(); public void onpause() { unregisterreceiver(receiver); super.onpause(); import import android.content.broadcastreceiver; import import android.content.intentfilter;
411 7.3. EarthquakeMap, requery MapView. EarthquakeReceiver receiver; public void onresume() { earthquakecursor.requery(); IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); super.onresume(); public void onpause() { earthquakecursor.deactivate(); super.onpause(); public class EarthquakeReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { earthquakecursor.requery(); MapView earthquakemap = (MapView)findViewById(R.id.map_view); earthquakemap.invalidate(); Earthquake. Earthquake. import import android.content.broadcastreceiver; import android.content.intentfilter;
Chapter 09, GUI. Force Close....,.... 9 5 onbind. private final IBinder binder = new MyBinder(); public IBinder onbind(intent intent) { return binder; public class MyBinder extends Binder { MyService getservice() { return MyService.this; ServiceConnection., 9 6 ServiceConnection
413 onserviceconnected onservicedisconnected. //. private MyService servicebinder; //. private ServiceConnection mconnection = new ServiceConnection() { public void onserviceconnected(componentname classname, IBinder service) { //. servicebinder = ((MyService.MyBinder)service).getService(); ; public void onservicedisconnected(componentname classname) { //. servicebinder = null; bindservice. ServiceConnection. 9 6. public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); //. Intent bindintent = new Intent(MyActivity.this, MyService.class); bindservice(bindintent, mconnection, Context.BIND_AUTO_CREATE);, onserviceconnected (servicebinder) public.,.
Chapter 09,. AIDL. AIDL. AIDL OS. AIDL 15. 3.,,.,... startforeground. (, ).. startforeground 9 7 ongoing Notification ( )..
415 int NOTIFICATION_ID = 1; Intent intent = new Intent(this, MyActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 1, intent, 0)); Notification notification = new Notification(R.drawable.icon, " ", System.currentTimeMillis()); notification.setlatesteventinfo(this, " ", " ", pi); notification.flags = notification.flags Notification.FLAG_ONGOING_EVENT; startforeground(notification_id, notification); 9 7 setlatesteventinfo..,., 9 8 stopforeground.. //. stopforeground(true); setforeground
Chapter 09.. AsyncTask, GUI. Thread Handler GUI UI.. 2. ( ) 5 onreceive 10..,,,. AsyncTask. AsyncTask GUI. UI. AsyncTask,,. AsyncTask, UI.
417 9 9 AsyncTask. AsyncTask execute,,. AsyncTask<[ ], [ ], [ ]>,, Void. private class MyAsyncTask extends AsyncTask<String, Integer, Integer> { protected void onprogressupdate(integer... progress) { // [... UI... ] protected void onpostexecute(integer... result) { // [... UI... ] protected Integer doinbackground(string... parameter) { int myprogress = 0; // [..., myprogress... ] publishprogress(myprogress); // [...... ] // onpostexecute. return result; 9 9 AsyncTask.
Chapter 09 doinbackground AsyncTask.. UI. publishprogress onprogressupdate UI. onpostexecute UI. onprogressupdate UI. doinbackground publishprogress. GUI. UI. onpostexecute. doinbackground UI. GUI. UI., 9 10 execute. execute AsyncTask. new MyAsyncTask().execute("inputString1", "inputstring2"); AsyncTask execute AsyncTask execute
419 EarthquakeService XML AsyncTask. 1. EarthquakeLookupTask AsyncTask. Void, Quake. doinbackground, onprogressupdate, onpostexecute. public class EarthquakeLookupTask extends AsyncTask<Void, Quake, Void> { protected Void doinbackground(void... params) { return null; protected void onprogressupdate(quake... values) { super.onprogressupdate(values); protected void onpostexecute(void result) { super.onpostexecute(result); 2. refreshearthquakes doinbackground. publishprogress. publishprogress Quake. null. protected Void doinbackground(void... params) { [... XML... ] //. addnewquake(quake); publishprogress(quake); import import android.os.asynctask;
Chapter 09 [...... ] return null; 3. refreshearthquakes. Earthquake LookupTask... EarthquakeLookupTask lastlookup = null; private void refreshearthquakes() { if (lastlookup == null lastlookup.getstatus().equals(asynctask.status.finished)) { lastlookup = new EarthquakeLookupTask(); lastlookup.execute((void[])null); AsyncTask.. UI GUI. Handler java.lang.thread. 9 11. // GUI. private void mainprocessing() { //.
421 Thread thread = new Thread(null, dobackgroundthreadprocessing, "Background"); thread.start(); // Runnable. private Runnable dobackgroundthreadprocessing = new Runnable() { public void run() { backgroundthreadprocessing(); ; //. private void backgroundthreadprocessing() { [...... ] GUI (GUI). GUI. GUI. runonuithread. runonuithread UI. runonuithread(new Runnable() { public void run() { // TODO:. ); ( ) Handler Handler.
Chapter 09 Handler post. 9 13 GUI. //. private Handler handler = new Handler(); private void mainprocessing() { Thread thread = new Thread(null, dobackgroundthreadprocessing, "Background"); thread.start(); private Runnable dobackgroundthreadprocessing = new Runnable() { public void run() { backgroundthreadprocessing(); ; //. private void backgroundthreadprocessing() { [...... ] handler.post(doupdategui); // GUI Runnable. private Runnable doupdategui = new Runnable() { public void run() { updategui(); ; private void updategui() { [... GUI... ] Handler postdelayed GUI, postattime.
423.,..,. Toast static maketext. maketext,, (LENGTH_SHORT LENGTH_LONG). 9 14 show. Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, msg, duration); toast.show(); 9 1 9 14. 2..
Chapter 09,.. 9 15 setgravity. Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, msg, duration); int offsetx = 0; int offsety = 0; toast.setgravity(gravity.bottom, offsetx, offsety); toast.show();. setview ( ). transient message window mechanism., 9 16 4 CompassView TextView. Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, msg, duration); toast.setgravity(gravity.top, 0, 0); LinearLayout ll = new LinearLayout(context); ll.setorientation(linearlayout.vertical); TextView mytextview = new TextView(context);
425 CompassView cv = new CompassView(context); mytextview.settext(msg); int lheight = LinearLayout.LayoutParams.FILL_PARENT; int lwidth = LinearLayout.LayoutParams.WRAP_CONTENT; ll.addview(cv, new LinearLayout.LayoutParams(lHeight, lwidth)); ll.addview(mytextview, new LinearLayout.LayoutParams(lHeight, lwidth)); ll.setpadding(40, 50, 0, 50); toast.setview(ll); toast.show(); 9 2.
Chapter 09 GUI GUI. cross thread exception. 9 17 GUI. private void mainprocessing() { Thread thread = new Thread(null, dobackgroundthreadprocessing, "Background"); thread.start(); private Runnable dobackgroundthreadprocessing = new Runnable() { public void run() { backgroundthreadprocessing(); ; private void backgroundthreadprocessing() { handler.post(doupdategui); // GUI Runnable. private Runnable doupdategui = new Runnable() { public void run() { Context context = getapplicationcontext(); String msg = "!"; int duration = Toast.LENGTH_SHORT; Toast.makeText(context, msg, duration).show(); ;
427..... LED.. audible alerts..,,,. ( ).
Chapter 09...,....,,., 9 3.. 9 18 getsystemservice. String svcname = Context.NOTIFICATION_SERVICE;
429 NotificationManager notificationmanager; notificationmanager = (NotificationManager)getSystemService(svcName);,,.. 1. 2. 3.. Notification LED,,. 9 19 Notification, ticker text. //. int icon = R.drawable.icon; //. String tickertext = " "; //. long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickertext, when);. Notification number,
Chapter 09. 1,. notification.number++; Notification. number 0-1.. 1.. setlatest EventInfo. 2. UI. UI contentview. setlatesteventinfo. 9 4,,,.. PendingIntent.. 9 20 setlatesteventinfo. Context context = getapplicationcontext(); //.
431 String expandedtext = " "; // String expandedtitle = " "; //. Intent intent = new Intent(this, MyActivity.class); PendingIntent launchintent = PendingIntent.getActivity(context, 0, intent, 0); notification.setlatesteventinfo(context, expandedtitle, expandedtext, launchintent); ( SMS ). ( ) setlatesteventinfo,... 9 5 9 21, 9 22, 9 23. 9 21,,. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dp" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/status_icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignparentleft="true" />
Chapter 09 <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingleft="10px" android:layout_torightof="@id/status_icon"> <TextView android:id="@+id/status_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:textcolor="#000" android:textsize="14sp" android:textstyle="bold" /> <ProgressBar android:id="@+id/status_progress" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/status_text" android:progressdrawable="@android:drawable/progress_horizontal" android:indeterminate="false" android:indeterminateonly="false" /> </RelativeLayout> </RelativeLayout> RemoteView contentview. contentintent. 9 22 ongoing Notification. Notification notification = new Notification(R.drawable.icon, " ", System.currentTimeMillis()); notification.flags = notification.flags Notification.FLAG_ONGOING_EVENT; notification.contentview = new RemoteViews(this.getPackageName(), R.layout.my_status_window_layout); Intent intent = new Intent(this, MyActivity.class); PendingIntent pendingintent = PendingIntent.getActivity(this, 0, intent, 0); notification.contentintent = pendingintent;
433 contentview contentintent, 9 23 set*. 9 23 9 21. notification.contentview.setimageviewresource(r.id.status_icon, R.drawable.icon); notification.contentview.settextviewtext(r.id.status_text, " :"); notification.contentview.setprogressbar(r.id.status_progress, 100, 50, false);.. 9 24 ID NotificationManager notify. int notificationref = 1; notificationmanager.notify(notificationref, notification);, ID NotificationManager notify. notify Notification. ID Notification
Chapter 09. ID. ID NotificationManager cancel. notificationmanager.cancel(notificationref);,. EarthquakeService.,. Earthquake. 1. EarthquakeService Notification. Notification. private Notification newearthquakenotification; public static final int NOTIFICATION_ID = 1; 2. oncreate Notification. public void oncreate() { updatetimer = new Timer("earthquakeUpdates"); int icon = R.drawable.icon; String tickertext = " "; long when = System.currentTimeMillis(); newearthquakenotification= new Notification(icon, import import android.app.notification;
435 tickertext, when); 3. EarthquakeLookupTask. onprogressupdate. setlatesteventinfo.. protected void onprogressupdate(quake... values) { String svcname = Context.NOTIFICATION_SERVICE; NotificationManager notificationmanager = (NotificationManager)getSystemService(svcName); Context context = getapplicationcontext(); String expandedtext = values[0].getdate().tostring(); String expandedtitle = "M:" + values[0].getmagnitude() + " " + values[0].getdetails(); Intent startactivityintent = new Intent(EarthquakeService.this, Earthquake.class); PendingIntent launchintent = PendingIntent.getActivity(context, 0, startactivityintent, 0); newearthquakenotification.setlatesteventinfo(context, expandedtitle, expandedtext, launchintent); newearthquakenotification.when = java.lang.system.currenttimemillis(); notificationmanager.notify(notification_id, newearthquakenotification); Toast.makeText(context, expandedtitle, Toast.LENGTH_SHORT).show(); import import android.app.notificationmanager; import android.app.pendingintent; import android.widget.toast;
Chapter 09 4. Earthquake EarthquakeMap.. 4.1. Earthquake. oncreate. NotificationManager notificationmanager; public void oncreate(bundle savedinstancestate) { [... oncreate... ] String svcname = Context.NOTIFICATION_SERVICE; notificationmanager = (NotificationManager)getSystemService(svcName); 4.2. EarthquakeReceiver onreceive.., onreceive. onreceive. public void onreceive(context context, Intent intent) { loadquakesfromprovider(); notificationmanager.cancel(earthquakeservice.notification_id); 4.3. onresume. public void onresume() { notificationmanager.cancel(earthquakeservice.notification_id); import import android.app.notificationmanager;
437 IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); super.onresume(); 4.4. Earthquake EarthquakeMap. NotificationManager notificationmanager; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.earthquake_map); ContentResolver cr = getcontentresolver(); earthquakecursor = cr.query(earthquakeprovider.content_uri, null, null, null, null); MapView earthquakemap = (MapView)findViewById(R.id.map_view); earthquakemap.getoverlays().add(new EarthquakeOverlay(earthquakeCursor)); String svcname = Context.NOTIFICATION_SERVICE; notificationmanager = (NotificationManager)getSystemService(svcName); public void onresume() { notificationmanager.cancel(earthquakeservice.notification_id); earthquakecursor.requery(); IntentFilter filter; filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUND); receiver = new EarthquakeReceiver(); registerreceiver(receiver, filter); import import android.app.notificationmanager;
Chapter 09 super.onresume(); public class EarthquakeReceiver extends BroadcastReceiver { public void onreceive(context context, Intent intent) { notificationmanager.cancel(earthquakeservice.notification_id); earthquakecursor.requery(); MapView earthquakemap = (MapView)findViewById(R.id.map_view); earthquakemap.invalidate();.,,....,,. Notification defaults. Notification.DEFAULT_LIGHTS Notification.DEFAULT_SOUND
439 Notification.DEFAULT_VIBRATE Notification. notification.defaults = Notification.DEFAULT_SOUND Notification.DEFAULT_VIBRATE; Notification.DEFAULT_ALL.... URI sound. notification.sound = ringuri;. 11. announcenewquake, 6. if (quake.getmagnitude() > 6) { Uri ringuri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); newearthquakenotification.sound = ringuri; vibration pattern,
Chapter 09.. long Notification vibrate.... uses-permission. <uses-permission android:name="android.permission.vibrate"/>. 1, 5. long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 ; notification.vibrate = vibrate;. announcenewquake.. exponential scale. 1 1. 10, 20. Richter scale 3 7 200 4. double vibratelength = 100*Math.exp(0.53*quake.getMagnitude()); long[] vibrate = new long[] {100, 100, (long)vibratelength ; newearthquakenotification.vibrate = vibrate;
441 Notification LED. ledargb LED, ledoffms ledonms LED. ledonms 1, ledoffms 0 LED, 0 LED. LED Notification flags FLAG_SHOW_ LIGHTS. LED. notification.ledargb = Color.RED; notification.ledoffms = 0; notification.ledonms = 1; notification.flags = notification.flags Notification.FLAG_SHOW_LIGHTS;., LED. LED,. int color; if (quake.getmagnitude() < 5.4) color = Color.GREEN; else if (quake.getmagnitude() < 6) color = Color.YELLOW; else color = Color.RED;
Chapter 09 newearthquakenotification.ledargb = color; newearthquakenotification.ledoffms = (int)vibratelength; newearthquakenotification.ledonms = (int)vibratelength; newearthquakenotification.flags = newearthquakenotification.flags Notification.FLAG_SHOW_LIGHTS; Notification FLAG_ONGOING_EVENT ongoing notifications, FLAG_INSISTENT insistent notifications... notification.flags = notification.flags Notification.FLAG_ONGOING_EVENT; 9 6. (,, ).
443.. notification.flags = notification.flags Notification.FLAG_INSISTENT;....,,..,.,,. Handler,..
Chapter 09 AlarmManager. AlarmManager getsystemservice. AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); one shot Alarm set,,. (, ).. set. RTC_WAKEUP. RTC. ELAPSED_REALTIME... ELAPSED_REALTIME_WAKEUP. 9 25. int alarmtype = AlarmManager.ELAPSED_REALTIME_WAKEUP; long timeorlengthofwait = 10000; String ALARM_ACTION = "ALARM_ACTION"; Intent intenttofire = new Intent(ALARM_ACTION); PendingIntent pendingintent = PendingIntent.getBroadcast(this, 0, intenttofire, 0); alarms.set(alarmtype, timeorlengthofwait, pendingintent); RTC ELAPSED_REALTIME
445.. cancel. alarms.cancel(pendingintent); 9 26.,. 30,. AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); String MY_RTC_ALARM = "MY_RTC_ALARM"; String ALARM_ACTION = "MY_ELAPSED_ALARM"; PendingIntent rtcintent = PendingIntent.getBroadcast(this, 0, new Intent(MY_RTC_ALARM), 1); PendingIntent elapsedintent = PendingIntent.getBroadcast(this, 0, new Intent(ALARM_ACTION), 1); // 5. Date t = new Date(); t.settime(java.lang.system.currenttimemillis() + 60*1000*5); alarms.set(alarmmanager.rtc_wakeup, t.gettime(), rtcintent); // 30. alarms.set(alarmmanager.elapsed_realtime, 30*60*1000, elapsedintent); //. alarms.cancel(rtcintent);
Chapter 09.,.. 9 27 setrepeating setinexactrepeating.,,. setrepeating.. setinexactrepeating. AlarmManager. INTERVAL_FIFTEEN_MINUTES INTERVAL_HALF_HOUR INTERVAL_HOUR INTERVAL_HALF_DAY INTERVAL_DAY inexact repeating alarms... //,. alarms.setrepeating(alarmmanager.elapsed_realtime_wakeup,
447 60*60*1000, 60*60*1000, elapsedintent); //. alarms.setinexactrepeating(alarmmanager.elapsed_realtime_wakeup, 60*60*1000, AlarmManager.INTERVAL_DAY, elapsedintent);.. 1. BroadcastReceiver EarthquakeAlarmReceiver. package com.paad.earthquake; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; public class EarthquakeAlarmReceiver extends BroadcastReceiver { 2. onreceive EarthquakeService. public void onreceive(context context, Intent intent) { Intent startintent = new Intent(context, EarthquakeService.class); context.startservice(startintent);
Chapter 09 3. public static. public static final String ACTION_REFRESH_EARTHQUAKE_ALARM = "com.paad.earthquake.action_refresh_earthquake_alarm"; 4. EarthquakeAlarmReceiver, 3 <intent-filter>. <receiver android:name=".earthquakealarmreceiver"> <intent-filter> <action android:name="com.paad.earthquake.action_refresh_earthquake_alarm" /> </intent-filter> </receiver> 5. EarthquakeService oncreate AlarmManager, PendingIntent. timertask. AlarmManager alarms; PendingIntent alarmintent; public void oncreate() { int icon = R.drawable.icon; String tickertext = "New Earthquake Detected"; long when = System.currentTimeMillis(); newearthquakenotification = new Notification(icon, tickertext, when); alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); String ALARM_ACTION; ALARM_ACTION = EarthquakeAlarmReceiver.ACTION_REFRESH_EARTHQUAKE_ALARM; Intent intenttofire = new Intent(ALARM_ACTION); import import android.app.alarmmanager;
449 alarmintent = PendingIntent.getBroadcast(this, 0, intenttofire, 0); 6. onstartcommand.. Service.START_STICKY Service.START_NOT_STICKY. 7... public int onstartcommand(intent intent, int flags, int startid) { //. Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int minmagindex = prefs.getint(preferences.pref_min_mag, 0); if (minmagindex < 0) minmagindex = 0; int freqindex = prefs.getint(preferences.pref_update_freq, 0); if (freqindex < 0) freqindex = 0; boolean autoupdate = prefs.getboolean(preferences.pref_auto_update, false); Resources r = getresources(); int[] minmagvalues = r.getintarray(r.array.magnitude); int[] freqvalues = r.getintarray(r.array.update_freq_values); minimummagnitude = minmagvalues[minmagindex]; int updatefreq = freqvalues[freqindex]; import import android.os.systemclock;
Chapter 09 if (autoupdate) { int alarmtype = AlarmManager.ELAPSED_REALTIME_WAKEUP; long timetorefresh = SystemClock.elapsedRealtime() + updatefreq*60*1000; alarms.setrepeating(alarmtype, timetorefresh, updatefreq*60*1000, alarmintent); else alarms.cancel(alarmintent); refreshearthquakes(); ; return Service.START_NOT_STICKY; 7. EarthquakeLookupTask onpostexecute stopself. protected void onpostexecute(void result) { stopself(); 8. updatetimer TimerTask dorefresh....... LED.
451... AsyncTask GUI 10..,.