Add OSM links to location updates
[fonbot.git] / src / ro / ieval / fonbot / Heavy.java
1 package ro.ieval.fonbot;
2
3 import static ro.ieval.fonbot.R.string.*;
4 import static ro.ieval.fonbot.Utils.toNonNull;
5
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.FileNotFoundException;
9 import java.io.IOException;
10 import java.lang.reflect.InvocationTargetException;
11 import java.lang.reflect.Method;
12 import java.net.InetSocketAddress;
13 import java.net.Socket;
14 import java.net.UnknownHostException;
15 import java.nio.channels.FileChannel;
16 import java.nio.channels.SocketChannel;
17 import java.util.ArrayList;
18 import java.util.Date;
19
20 import org.eclipse.jdt.annotation.Nullable;
21
22 import ro.ieval.fonbot.Utils.Command;
23 import ro.ieval.fonbot.Utils.MessageType;
24 import ro.ieval.fonbot.Utils.OngoingEvent;
25 import ro.ieval.fonbot.Utils.RingerMode;
26 import ro.ieval.fonbot.Utils.WipeType;
27 import android.annotation.SuppressLint;
28 import android.app.AlarmManager;
29 import android.app.NotificationManager;
30 import android.app.PendingIntent;
31 import android.app.admin.DevicePolicyManager;
32 import android.bluetooth.BluetoothAdapter;
33 import android.content.ActivityNotFoundException;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.database.Cursor;
38 import android.graphics.ImageFormat;
39 import android.hardware.Camera;
40 import android.hardware.Camera.PictureCallback;
41 import android.location.Location;
42 import android.location.LocationListener;
43 import android.location.LocationManager;
44 import android.location.LocationProvider;
45 import android.media.AudioManager;
46 import android.media.Ringtone;
47 import android.media.RingtoneManager;
48 import android.net.ConnectivityManager;
49 import android.net.Uri;
50 import android.net.wifi.WifiManager;
51 import android.os.AsyncTask;
52 import android.os.BatteryManager;
53 import android.os.Bundle;
54 import android.os.Handler;
55 import android.os.PowerManager;
56 import android.os.Vibrator;
57 import android.preference.PreferenceManager;
58 import android.provider.BaseColumns;
59 import android.provider.CallLog.Calls;
60 import android.provider.ContactsContract.CommonDataKinds;
61 import android.provider.ContactsContract.CommonDataKinds.BaseTypes;
62 import android.provider.ContactsContract.CommonDataKinds.Phone;
63 import android.provider.ContactsContract.Contacts;
64 import android.provider.ContactsContract.Data;
65 import android.provider.Settings.Secure;
66 import android.speech.tts.TextToSpeech;
67 import android.speech.tts.TextToSpeech.OnInitListener;
68 import android.support.v4.app.NotificationCompat;
69 import android.telephony.SmsManager;
70 import android.telephony.TelephonyManager;
71 import android.util.Log;
72 import android.view.SurfaceView;
73 import android.widget.Toast;
74
75 import com.android.internal.telephony.ITelephony;
76
77 /*
78 * Copyright © 2013 Marius Gavrilescu
79 *
80 * This file is part of FonBot.
81 *
82 * FonBot is free software: you can redistribute it and/or modify
83 * it under the terms of the GNU General Public License as published by
84 * the Free Software Foundation, either version 3 of the License, or
85 * (at your option) any later version.
86 *
87 * FonBot is distributed in the hope that it will be useful,
88 * but WITHOUT ANY WARRANTY; without even the implied warranty of
89 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
90 * GNU General Public License for more details.
91 *
92 * You should have received a copy of the GNU General Public License
93 * along with FonBot. If not, see <http://www.gnu.org/licenses/>.
94 */
95
96 /**
97 * Implementation of all FonBot commands. The methods of this class do not do argument checking.
98 *
99 * @author Marius Gavrilescu <marius@ieval.ro>
100 */
101 final class Heavy {
102 /**
103 * LocationListener that sends notifications to the user.
104 *
105 * @author Marius Gavrilescu <marius@ieval.ro>
106 */
107 private static final class FonBotLocationListener implements LocationListener {
108 /** Context instance */
109 private final Context context;
110 /** Destination address for notifications */
111 private final Address replyTo;
112
113 /**
114 * Construct a FonBotLocationListener.
115 *
116 * @param context Context instance
117 * @param replyTo the reply address
118 */
119 FonBotLocationListener(final Context context, final Address replyTo) {
120 this.context=context;
121 this.replyTo=replyTo;
122 }
123
124 @Override
125 public void onLocationChanged(@Nullable final Location loc) {
126 if(loc==null)
127 return;
128 final StringBuilder sb=new StringBuilder(toNonNull(context.getString(location)));
129 sb.append(": ");
130 sb.append(toNonNull(context.getString(latitude)));
131 sb.append(": ");
132 sb.append(loc.getLatitude());
133 sb.append(", ");
134 sb.append(toNonNull(context.getString(longitude)));
135 sb.append(": ");
136 sb.append(loc.getLongitude());
137
138 if(loc.hasAccuracy()){
139 sb.append(", ");
140 sb.append(toNonNull(context.getString(accuracy)));
141 sb.append(": ");
142 sb.append(loc.getAccuracy());
143 }
144
145 if(loc.hasAltitude()){
146 sb.append(", ");
147 sb.append(toNonNull(context.getString(altitude)));
148 sb.append(": ");
149 sb.append(loc.getAltitude());
150 }
151
152 if(loc.hasBearing()){
153 sb.append(", ");
154 sb.append(toNonNull(context.getString(bearing)));
155 sb.append(": ");
156 sb.append(loc.getBearing());
157 }
158
159 if(loc.hasSpeed()){
160 sb.append(", ");
161 sb.append(toNonNull(context.getString(speed)));
162 sb.append(": ");
163 sb.append(loc.getSpeed());
164 }
165
166 final Date locationDate=new Date(loc.getTime());
167 sb.append(" ");
168 sb.append(toNonNull(context.getString(at)));
169 sb.append(" ");
170 sb.append(locationDate.toString());
171 sb.append(". ");
172
173 sb.append("http://openstreetmap.org/?zoom=15&mlat=");
174 sb.append(loc.getLatitude());
175 sb.append("&mlon=");
176 sb.append(loc.getLongitude());
177 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), toNonNull(sb.toString()));
178 }
179
180 @Override
181 public void onProviderDisabled(@Nullable final String provider) {
182 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), location_provider_disabled, provider);
183 }
184
185 @Override
186 public void onProviderEnabled(@Nullable final String provider) {
187 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), location_provider_enabled, provider);
188 }
189
190 @Override
191 public void onStatusChanged(@Nullable final String provider, final int status, @Nullable final Bundle extras) {
192 final int state;
193 switch(status){
194 case LocationProvider.AVAILABLE:
195 state=location_provider_available;
196 break;
197 case LocationProvider.TEMPORARILY_UNAVAILABLE:
198 state=location_provider_temporary_unavailable;
199 break;
200 case LocationProvider.OUT_OF_SERVICE:
201 state=location_provider_out_of_service;
202 break;
203 default:
204 state=location_provider_unknown_state;
205 }
206 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), state, provider);
207 }
208 }
209 /**
210 * Currently active FonBotLocationListener
211 */
212 private static FonBotLocationListener locationListener = null;
213
214 /**
215 * AsyncTask that sends a byte[] to a server
216 *
217 * @author Marius Gavrilescu <marius@ieval.ro>
218 *
219 */
220 private static class SendDataAsyncTask extends AsyncTask<Void, Void, Void>{
221 /**
222 * Context instance used by this class
223 */
224 private final Context context;
225 /**
226 * Server hostname
227 */
228 private final String hostname;
229 /**
230 * Server port
231 */
232 private final int port;
233 /**
234 * Data to send
235 */
236 private final byte[] data;
237 /**
238 * Address for sending back errors and success messages
239 */
240 private final Address replyTo;
241
242 /**
243 * Constructs a SendDataAsyncTasks from its parameters
244 *
245 * @param context the context
246 * @param replyTo the reply Address
247 * @param hostname the server hostname
248 * @param port the server port
249 * @param data the data to send
250 */
251 public SendDataAsyncTask(final Context context,final Address replyTo, final String hostname, final int port, final byte[] data) {//NOPMD array is immutable
252 super();
253 this.context=context;
254 this.hostname=hostname;
255 this.port=port;
256 this.data=data;
257 this.replyTo=replyTo;
258 }
259
260 @Override
261 protected @Nullable Void doInBackground(@Nullable final Void... params) {
262 final Socket sock;
263 try {
264 sock = new Socket(hostname, port);
265 try {
266 sock.getOutputStream().write(data);
267 } catch (IOException e) {
268 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), error_writing_to_socket, e.getMessage());
269 return null;
270 }
271
272 try {
273 sock.close();
274 } catch (IOException e) {
275 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), cannot_close_socket, e.getMessage());
276 return null;
277 }
278 } catch (UnknownHostException e) {
279 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), unknown_host, hostname);
280 return null;
281 } catch (IOException e) {
282 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), cannot_connect_to_host_on_port, hostname, Integer.valueOf(port));
283 return null;
284 }
285 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), photo_sent);
286 return null;
287 }
288 }
289
290 /**
291 * PictureCallback that sends the picture to a server.
292 *
293 * @author Marius Gavrilescu <marius@ieval.ro>
294 */
295 private static final class FonBotPictureCallback implements PictureCallback{
296 /** Server hostname */
297 private final String hostname;
298 /** Server port */
299 private final int port;
300 /** Context instance */
301 private final Context context;
302 /** Reply address */
303 private final Address replyTo;
304
305 /**
306 * Construct a FonBotPictureCallback.
307 *
308 * @param context Context instance
309 * @param replyTo reply Address
310 * @param hostname server hostname
311 * @param port server port
312 */
313 FonBotPictureCallback(final Context context, final Address replyTo, final String hostname, final int port) {
314 this.hostname=hostname;
315 this.port=port;
316 this.context=context;
317 this.replyTo=replyTo;
318 }
319
320 @Override
321 @SuppressWarnings("hiding")
322 public void onPictureTaken(final @Nullable byte[] data, final @Nullable Camera camera) {
323 if(camera==null || data==null)
324 return;
325 camera.stopPreview();
326 stopCamera();
327 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), sending_photo);
328 new SendDataAsyncTask(toNonNull(context), toNonNull(replyTo), toNonNull(hostname), port, data).execute();
329 }
330 }
331
332 /**
333 * Runnable that takes a screen capture and stores it in a file.
334 */
335 private static final class ScreencapRunnable implements Runnable{
336 private final Context context;
337 private final Address replyTo;
338 private final String filename;
339
340 ScreencapRunnable(final Context context, final Address replyTo, final String filename){
341 this.context=context;
342 this.replyTo=replyTo;
343 this.filename=filename;
344 }
345
346 @Override
347 public void run(){
348 final int exitCode;
349 try {
350 exitCode=Runtime.getRuntime().exec(new String[]{
351 "su",
352 "-c",
353 "screencap -p \"" + filename + "\""
354 }).waitFor();
355 } catch (final Exception e){
356 e.printStackTrace();
357 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), screencap_failed);
358 return;
359 }
360
361 if(exitCode == 0 && new File(filename).exists())
362 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), screencap_successful);
363 else
364 Utils.sendMessage(toNonNull(context), toNonNull(replyTo), screencap_failed);
365 }
366 }
367
368 /**
369 * Get help for a particular command
370 *
371 * @param context Context instance
372 * @param replyTo reply Address
373 * @param command command to get help for
374 */
375 public static void help(final Context context, final Address replyTo, final Command command){//NOPMD method is a big switch statement. Nothing confusing.
376 switch(command){
377 case ANSWER:
378 Utils.sendMessage(context, replyTo, answer_help);
379 break;
380 case BATT:
381 Utils.sendMessage(context, replyTo, batt_help);
382 break;
383 case BLUETOOTH:
384 Utils.sendMessage(context, replyTo, bluetooth_help);
385 break;
386 case CALLLOG:
387 Utils.sendMessage(context, replyTo, calllog_help);
388 break;
389 case CONTACTS:
390 Utils.sendMessage(context, replyTo, contacts_help);
391 break;
392 case DATA:
393 Utils.sendMessage(context, replyTo, data_help);
394 break;
395 case DELNOTIFICATION:
396 Utils.sendMessage(context, replyTo, delnotification_help, Utils.join(", ", toNonNull(MessageType.values())));
397 break;
398 case DIAL:
399 Utils.sendMessage(context, replyTo, dial_help);
400 break;
401 case DIALOG:
402 Utils.sendMessage(context, replyTo, dialog_help);
403 break;
404 case DISABLE:
405 Utils.sendMessage(context, replyTo, disable_help, Utils.join(", ", toNonNull(Command.values())));
406 break;
407 case ECHO:
408 Utils.sendMessage(context, replyTo, echo_help);
409 break;
410 case ENABLE:
411 Utils.sendMessage(context, replyTo, enable_help, Utils.join(", ", toNonNull(Command.values())));
412 break;
413 case FLASH:
414 Utils.sendMessage(context, replyTo, flash_help);
415 break;
416 case GLOCATION:
417 Utils.sendMessage(context, replyTo, glocation_help);
418 break;
419 case GPS:
420 Utils.sendMessage(context, replyTo, gps_help);
421 break;
422 case HANGUP:
423 Utils.sendMessage(context, replyTo, hangup_help);
424 break;
425 case HELP:
426 Utils.sendMessage(context, replyTo, help_help, Utils.join(", ",toNonNull(Command.values())));
427 break;
428 case LAUNCH:
429 Utils.sendMessage(context, replyTo, launch_help);
430 break;
431 case LOCATION:
432 Utils.sendMessage(context, replyTo, location_help, Utils.join(", ",toNonNull(Utils.LocationProvider.values())));
433 break;
434 case LOCK:
435 Utils.sendMessage(context, replyTo, lock_help);
436 break;
437 case LS:
438 Utils.sendMessage(context, replyTo, ls_help);
439 break;
440 case NCFILE:
441 Utils.sendMessage(context, replyTo, ncfile_help);
442 break;
443 case NEXT:
444 Utils.sendMessage(context, replyTo, next_help);
445 break;
446 case NOLOCATION:
447 Utils.sendMessage(context, replyTo, nolocation_help);
448 break;
449 case PAUSE:
450 Utils.sendMessage(context, replyTo, pause_help);
451 break;
452 case PHOTO:
453 Utils.sendMessage(context, replyTo, photo_help);
454 break;
455 case PLAY:
456 Utils.sendMessage(context, replyTo, play_help);
457 break;
458 case POLL:
459 Utils.sendMessage(context, replyTo, poll_help);
460 break;
461 case PREV:
462 Utils.sendMessage(context, replyTo, prev_help);
463 break;
464 case RING:
465 Utils.sendMessage(context, replyTo, ring_help);
466 break;
467 case RINGER:
468 Utils.sendMessage(context, replyTo, ringer_help, Utils.join(", ", toNonNull(RingerMode.values())));
469 break;
470 case RM:
471 Utils.sendMessage(context, replyTo, rm_help);
472 break;
473 case SETNOTIFICATION:
474 Utils.sendMessage(context, replyTo, setnotification_help, Utils.join(", ", toNonNull(MessageType.values())));
475 break;
476 case SETPASSWORD:
477 Utils.sendMessage(context, replyTo, setpassword_help);
478 break;
479 case SMS:
480 Utils.sendMessage(context, replyTo, sms_help);
481 break;
482 case SMSLOG:
483 Utils.sendMessage(context, replyTo, smslog_help);
484 break;
485 case SPEAK:
486 Utils.sendMessage(context, replyTo, speak_help);
487 break;
488 case TOAST:
489 Utils.sendMessage(context, replyTo, toast_help);
490 break;
491 case VIBRATE:
492 Utils.sendMessage(context, replyTo, vibrate_help);
493 break;
494 case VIEW:
495 Utils.sendMessage(context, replyTo, view_help);
496 break;
497 case WIFI:
498 Utils.sendMessage(context, replyTo, wifi_help);
499 break;
500 case WIPE:
501 Utils.sendMessage(context, replyTo, wipe_help, Utils.WIPE_CONFIRM_STRING);
502 break;
503 case REBOOT:
504 Utils.sendMessage(context, replyTo, reboot_help);
505 break;
506 case NOTIFY:
507 Utils.sendMessage(context, replyTo, notify_help);
508 break;
509 case SCREENCAP:
510 Utils.sendMessage(context, replyTo, screencap_help);
511 break;
512 case TORCH:
513 Utils.sendMessage(context, replyTo, torch_help);
514 break;
515 }
516 }
517
518 /**
519 * Camera instance.
520 *
521 * @see #startCamera(Context, Address)
522 * @see #stopCamera()
523 */
524 private static Camera camera;
525 /**
526 * Ringtone used by the {@link Utils.Command#RING RING} command.
527 *
528 * @see #setupRingtone(Context)
529 */
530 private static Ringtone ringtone;
531 /**
532 * Saved ringer volume.
533 *
534 * @see #startAlarm(Context, Address)
535 * @see #stopAlarm(Context, Address)
536 */
537 private static int savedRingVolume;
538 /**
539 * Saved ringer mode.
540 *
541 * @see #startAlarm(Context, Address)
542 * @see #stopAlarm(Context, Address)
543 */
544 private static int savedRingerMode;
545
546 /** Private constructor */
547 private Heavy(){
548 //do nothing
549 }
550
551 /**
552 * Convert a phone number type to a string
553 *
554 * @param context Context instance
555 * @param type phone number type
556 * @param label name of a custom phone type
557 * @return the phone number type
558 */
559 private static @Nullable String phoneNumberType(final Context context, final int type, final @Nullable String label) {
560 switch(type){
561 case BaseTypes.TYPE_CUSTOM:
562 return label;
563 case Phone.TYPE_ASSISTANT:
564 return context.getString(phone_numer_type_assistant);
565 case Phone.TYPE_CALLBACK:
566 return context.getString(phone_number_type_callback);
567 case Phone.TYPE_CAR:
568 return context.getString(phone_number_type_car);
569 case Phone.TYPE_COMPANY_MAIN:
570 return context.getString(phone_number_type_company_main);
571 case Phone.TYPE_FAX_HOME:
572 return context.getString(phone_number_type_home_fax);
573 case Phone.TYPE_FAX_WORK:
574 return context.getString(phone_number_type_work_fax);
575 case Phone.TYPE_HOME:
576 return context.getString(phone_number_type_home);
577 case Phone.TYPE_ISDN:
578 return context.getString(phone_number_type_isdn);
579 case Phone.TYPE_MAIN:
580 return context.getString(phone_number_type_main);
581 case Phone.TYPE_MMS:
582 return context.getString(phone_number_type_mms);
583 case Phone.TYPE_MOBILE:
584 return context.getString(phone_number_type_mobile);
585 case Phone.TYPE_OTHER:
586 return context.getString(phone_number_type_other);
587 case Phone.TYPE_OTHER_FAX:
588 return context.getString(phone_number_type_other_fax);
589 case Phone.TYPE_PAGER:
590 return context.getString(phone_number_type_pager);
591 case Phone.TYPE_RADIO:
592 return context.getString(phone_number_type_radio);
593 case Phone.TYPE_TELEX:
594 return context.getString(phone_number_type_telex);
595 case Phone.TYPE_TTY_TDD:
596 return context.getString(phone_number_type_textphone);
597 case Phone.TYPE_WORK:
598 return context.getString(phone_number_type_work);
599 case Phone.TYPE_WORK_MOBILE:
600 return context.getString(phone_number_type_work_mobile);
601 case Phone.TYPE_WORK_PAGER:
602 return context.getString(phone_number_type_work_pager);
603 }
604
605 return context.getString(phone_number_type_unknown, Integer.valueOf(type));
606 }
607
608 /**
609 * Setup the ringtone used by the {@link Utils.Command#RING RING} command
610 *
611 * @param context Context
612 */
613 private static void setupRingtone(final Context context){
614 if(ringtone==null){//NOPMD not supposed to be thread-safe
615 final Uri alert=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
616 ringtone=RingtoneManager.getRingtone(context, alert);
617 }
618 }
619
620 /**
621 * Make the phone start ringing. Turns up the volume and sets the ringer mode to NORMAL
622 *
623 * @param context Context instance
624 * @param replyTo reply Address
625 */
626 private static void startAlarm(final Context context, final Address replyTo){
627 Utils.registerOngoing(context, toNonNull(OngoingEvent.RING));
628 final AudioManager man=(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
629 savedRingerMode=man.getRingerMode();
630 man.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
631 savedRingVolume=man.getStreamVolume(AudioManager.STREAM_RING);
632 man.setStreamVolume(AudioManager.STREAM_RING, man.getStreamMaxVolume(AudioManager.STREAM_RING), 0);
633 Utils.sendMessage(context, replyTo, ringing);
634 ringtone.play();
635 }
636
637 /**
638 * Get a camera instance.
639 *
640 * @param context Context instance
641 * @param replyTo reply Address
642 */
643 private static void startCamera(final Context context, final Address replyTo){
644 if(camera!=null)
645 return;
646 try{
647 camera=Camera.open();
648 } catch (Exception e){
649 Utils.sendMessage(context, replyTo, cannot_grab_camera);
650 }
651 }
652
653 /**
654 * Make the phone stop ringing. Restores the volume and ringer mode.
655 *
656 * @param context Context instance
657 * @param replyTo reply Address
658 */
659 private static void stopAlarm(final Context context, final Address replyTo){
660 Utils.unregisterOngoing(context, toNonNull(OngoingEvent.RING));
661 final AudioManager man=(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
662 Utils.sendMessage(context, replyTo, no_longer_ringing);
663 ringtone.stop();
664 man.setStreamVolume(AudioManager.STREAM_RING, savedRingVolume, 0);
665 man.setRingerMode(savedRingerMode);
666 }
667
668 /**
669 * Release the previously grabbed camera instance
670 *
671 * @see #startCamera(Context, Address)
672 */
673 private static void stopCamera(){
674 if(camera==null)
675 return;
676 camera.release();
677 camera=null;
678 }
679
680 /**
681 * Send battery status information to an Address
682 *
683 * @param context Context instance
684 * @param replyTo destination Address
685 *
686 * @see #describeBatteryLevel(Context, Address, MessageType)
687 */
688 public static void batt(final Context context, final Address replyTo){
689 describeBatteryLevel(context, replyTo, null);
690 }
691
692 /**
693 * Show the bluetooth radio status.
694 *
695 * @param context Context instance
696 * @param replyTo destination Address
697 */
698 public static void bluetooth(final Context context, final Address replyTo) {
699 final BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
700 if(adapter==null){
701 Utils.sendMessage(context, replyTo, no_bluetooth_adapter);
702 return;
703 }
704
705 if(adapter.isEnabled())
706 Utils.sendMessage(context, replyTo, bluetooth_on);
707 else
708 Utils.sendMessage(context, replyTo, bluetooth_off);
709 }
710
711 /**
712 * Set the bluetooth radio status.
713 *
714 * @param context Context instance
715 * @param replyTo destination Address
716 * @param on the requested radio status
717 */
718 public static void bluetooth(final Context context, final Address replyTo, final boolean on){
719 final BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
720 if(adapter==null){
721 Utils.sendMessage(context, replyTo, no_bluetooth_adapter);
722 return;
723 }
724
725 if(on) {
726 adapter.enable();
727 Utils.sendMessage(context, replyTo, enabling_bluetooth);
728 }
729 else {
730 adapter.disable();
731 Utils.sendMessage(context, replyTo, disabling_bluetooth);
732 }
733 }
734
735 /**
736 * Cancel an ongoing event.
737 *
738 * @param context Context instance
739 * @param event the event to cancel
740 */
741 public static void cancelOngoing(final Context context, final OngoingEvent event){
742 switch(event){
743 case LOCATION:
744 nolocation(context, toNonNull(Address.BLACKHOLE));
745 break;
746 case RING:
747 ring(context, toNonNull(Address.BLACKHOLE), false);
748 break;
749 }
750 }
751
752 /**
753 * Send the last calls to an Address.
754 *
755 * @param context Context instance
756 * @param replyTo destination Address
757 * @param numCalls how many calls to send
758 */
759 public static void calllog(final Context context, final Address replyTo, final int numCalls) {
760 final String[] fields = {
761 Calls.TYPE, Calls.NUMBER, Calls.CACHED_NAME, Calls.DURATION, Calls.DATE
762 };
763
764 final Cursor cursor = context.getContentResolver().query(
765 Calls.CONTENT_URI,
766 fields,
767 null,
768 null,
769 Calls.DATE + " DESC"
770 );
771
772 if (cursor.moveToFirst()) {
773 do {
774 final StringBuilder sb=new StringBuilder(50);//NOPMD different strings
775 final int type=cursor.getInt(0);
776 final String from=cursor.getString(1);
777
778 switch(type){
779 case Calls.INCOMING_TYPE:
780 sb.append(context.getString(incoming_call_from, from));
781 break;
782 case Calls.MISSED_TYPE:
783 sb.append(context.getString(missed_call_from, from));
784 break;
785 case Calls.OUTGOING_TYPE:
786 sb.append(context.getString(outgoing_call_to, from));
787 break;
788 }
789
790 if (cursor.getString(2) != null)
791 sb.append('(').append(cursor.getString(2)).append(") ");
792
793 sb.append(context.getString(duration_seconds_starting_at,
794 Long.valueOf(cursor.getLong(3)),
795 new Date(cursor.getLong(4))));
796
797 Utils.sendMessage(context, replyTo, toNonNull(sb.toString()));
798 } while (cursor.moveToNext() && cursor.getPosition() < numCalls);
799 }
800
801 cursor.close();
802 }
803
804 /**
805 * Search for contacts by name/nickname and send matching entries to an Address.
806 *
807 * @param context Context instance
808 * @param replyTo destination Address
809 * @param name name/nickname part to search for
810 */
811 @SuppressLint("StringFormatMatches")
812 public static void contacts(final Context context, final Address replyTo, final String name){
813 final Cursor cursor=context.getContentResolver().query(Uri.withAppendedPath(
814 Contacts.CONTENT_FILTER_URI, name),
815 new String[]{Contacts.DISPLAY_NAME, BaseColumns._ID, Contacts.LOOKUP_KEY},
816 null, null, Contacts.DISPLAY_NAME);
817
818 if(cursor.getCount()==0)
819 Utils.sendMessage(context, replyTo, no_matching_contacts_found);
820
821 while(cursor.moveToNext()){
822 final String[] fields = {
823 CommonDataKinds.Phone.NUMBER,
824 CommonDataKinds.Phone.TYPE,
825 CommonDataKinds.Phone.LABEL,
826 };
827
828 final Cursor inCursor=context.getContentResolver().query(Data.CONTENT_URI,
829 fields,
830 Data.CONTACT_ID+" = ? AND "+Data.MIMETYPE+ " = ?",
831 new String[]{Long.toString(cursor.getLong(1)), CommonDataKinds.Phone.CONTENT_ITEM_TYPE},
832 CommonDataKinds.Phone.LABEL);
833
834 while(inCursor.moveToNext())
835 Utils.sendMessage(context, replyTo, toNonNull(context.getString(contact_info,
836 cursor.getString(0),
837 inCursor.getString(0),
838 phoneNumberType(context, inCursor.getInt(1), inCursor.getString(2)))));
839
840 inCursor.close();
841 }
842
843 cursor.close();
844 }
845
846 /**
847 * Send battery status information to an Address or as a notification
848 *
849 * @param context Context instance
850 * @param replyTo Address to send the information to, if sending to a direct address. Null otherwise.
851 * @param type Notification type, if sending as a notification. Null otherwise.
852 */
853 public static void describeBatteryLevel(final Context context, final @Nullable Address replyTo, final @Nullable MessageType type) {
854 if(replyTo==null&&type==null)
855 return;
856 final Intent intent=context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
857 if(intent==null)
858 return;
859 final double level=intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
860 final int scale=intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
861 final int plugged=intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
862 final int status=intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
863 final int temp=intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
864 final int volt=intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
865
866 final StringBuilder sb=new StringBuilder(100);
867 sb.append(context.getString(battery_level, Double.valueOf(level*100/scale)));
868
869 switch(plugged){
870 case 0:
871 sb.append(context.getString(not_plugged_in));
872 break;
873 case BatteryManager.BATTERY_PLUGGED_AC:
874 sb.append(context.getString(plugged_in_ac));
875 break;
876 case BatteryManager.BATTERY_PLUGGED_USB:
877 sb.append(context.getString(plugged_in_usb));
878 break;
879 case BatteryManager.BATTERY_PLUGGED_WIRELESS:
880 sb.append(context.getString(plugged_in_wireless));
881 break;
882 }
883
884 switch(status){
885 case BatteryManager.BATTERY_STATUS_CHARGING:
886 sb.append(context.getString(status_charging));
887 break;
888 case BatteryManager.BATTERY_STATUS_DISCHARGING:
889 sb.append(context.getString(status_discharging));
890 break;
891 case BatteryManager.BATTERY_STATUS_FULL:
892 sb.append(context.getString(status_full));
893 break;
894 case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
895 sb.append(context.getString(status_not_charging));
896 break;
897 case BatteryManager.BATTERY_STATUS_UNKNOWN:
898 sb.append(context.getString(status_unknown));
899 break;
900 }
901
902 sb.append(context.getString(temperature, Integer.valueOf(temp)));
903
904 sb.append(context.getString(voltage, Integer.valueOf(volt)));
905 if(type==null)
906 Utils.sendMessage(context, toNonNull(replyTo), toNonNull(sb.toString()));
907 else
908 Utils.sendMessage(context, type, toNonNull(sb.toString()));
909 }
910
911 /**
912 * Dial a phone number.
913 *
914 * @param context Context instance
915 * @param replyTo reply Address
916 * @param nr phone number to dial
917 */
918 public static void dial(final Context context, final Address replyTo, final String nr){
919 final Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+nr));
920 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
921 final String name=Utils.callerId(context, nr);
922 if(name==null)
923 Utils.sendMessage(context, replyTo, dialing, nr);
924 else
925 Utils.sendMessage(context, replyTo, dialing, nr+" ("+name+")");
926 context.startActivity(intent);
927 }
928
929 /**
930 * Show a dialog with a message and a list of buttons.
931 *
932 * @param context Context instance
933 * @param replyTo reply Address
934 * @param message dialog message
935 * @param buttons dialog buttons
936 */
937 public static void dialog(final Context context, final Address replyTo, final String message, final String[] buttons){
938 final Intent intent=new Intent(context, DialogActivity.class);
939 intent.putExtra(DialogActivity.EXTRA_MESSAGE, message);
940 intent.putExtra(DialogActivity.EXTRA_BUTTONS, buttons);
941 intent.putExtra(DialogActivity.EXTRA_REPLYTO, replyTo.toString());
942 intent.addFlags(
943 Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|
944 Intent.FLAG_ACTIVITY_NEW_TASK|
945 Intent.FLAG_ACTIVITY_NO_USER_ACTION|
946 Intent.FLAG_FROM_BACKGROUND);
947 Utils.sendMessage(context, toNonNull(replyTo), showing_dialog);
948 context.startActivity(intent);
949 }
950
951 /**
952 * Turns the flashlight on or off.
953 *
954 * @param context Context instance
955 * @param replyTo reply Address
956 * @param on requested flashlight state
957 */
958 public static void flash(final Context context, final Address replyTo, final boolean on){
959 startCamera(context, replyTo);
960 if(camera==null)
961 return;
962 final Camera.Parameters parms=camera.getParameters();
963 if(on){
964 parms.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
965 camera.setParameters(parms);
966 } else {
967 parms.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
968 camera.setParameters(parms);
969 stopCamera();
970 }
971 }
972
973 /**
974 * Start sending location updates to an Address.
975 *
976 * @param context Context instance
977 * @param replyTo destination Address
978 * @param provider LocationProvider
979 * @param minTime minimum time between two consecutive updates (in ms)
980 * @param minDistance minimum distance between two consecutive updates (in meters)
981 *
982 * @see LocationManager#requestLocationUpdates(String, long, float, LocationListener)
983 */
984 public static void location(final Context context, final Address replyTo, final String provider,final long minTime,final float minDistance){
985 final LocationManager man=(LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
986 if(locationListener!=null)
987 nolocation(context, toNonNull(Address.BLACKHOLE));
988 Utils.registerOngoing(context, toNonNull(OngoingEvent.LOCATION));
989 locationListener=new FonBotLocationListener(context, replyTo);
990 man.removeUpdates(locationListener);
991 final Location lastKnownLocation=man.getLastKnownLocation(provider);
992 if(lastKnownLocation!=null){
993 Utils.sendMessage(context, replyTo, last_known_location);
994 locationListener.onLocationChanged(lastKnownLocation);
995 }
996 Utils.sendMessage(context, replyTo, listening_for_location_updates);
997 man.requestLocationUpdates(provider, minTime, minDistance, locationListener);
998 }
999
1000 /**
1001 * Lock the phone.
1002 *
1003 * @param context Context instance
1004 * @param replyTo reply Address
1005 */
1006 public static void lock(final Context context, final Address replyTo) {
1007 final DevicePolicyManager dpm=(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1008 dpm.lockNow();
1009 Utils.sendMessage(context, replyTo, device_locked);
1010 }
1011
1012 /**
1013 * Send a command to a running instance of the music player
1014 *
1015 * @param context Context instance
1016 * @param replyTo reply Address
1017 * @param command command to send
1018 */
1019 public static void musicPlayerCommand(final Context context, final Address replyTo, final String command) {
1020 final Intent intent=new Intent("com.android.music.musicservicecommand");
1021 intent.putExtra("command", command);
1022 context.sendBroadcast(intent);
1023 Utils.sendMessage(context, replyTo, command_sent);
1024 }
1025
1026 /**
1027 * Send a file to a server.
1028 *
1029 * @param context Context instance
1030 * @param replyTo reply Address
1031 * @param filename file to send
1032 * @param hostname server hostname
1033 * @param port server port
1034 */
1035 public static void ncfile(final Context context, final Address replyTo, final String filename,final String hostname,final int port){
1036 new AsyncTask<Void, Void, Void>() {
1037 @Override
1038 protected @Nullable Void doInBackground(@Nullable final Void... params) {
1039 final FileChannel in;
1040 try{
1041 in=new FileInputStream(filename).getChannel();
1042 } catch (final FileNotFoundException e){
1043 Utils.sendMessage(context, replyTo, file_not_found, filename);
1044 return null;
1045 }
1046 final SocketChannel sock;
1047 try{
1048 sock = SocketChannel.open(new InetSocketAddress(hostname, port));
1049 } catch (final IOException e){
1050 Utils.sendMessage(context, replyTo, toNonNull(context.getString(
1051 cannot_connect_to_host_on_port, hostname, Integer.valueOf(port))));
1052 try {
1053 in.close();
1054 } catch (IOException ex) {
1055 //ignored
1056 }
1057 return null;
1058 }
1059
1060 try{
1061 in.transferTo(0, in.size(), sock);
1062 } catch (final IOException e){
1063 Utils.sendMessage(context, replyTo, toNonNull(context.getString(
1064 io_error, e.getMessage())));
1065 } finally {
1066 try{
1067 in.close();
1068 } catch (IOException e){
1069 //ignored
1070 }
1071 try{
1072 sock.close();
1073 } catch(IOException e){
1074 //ignored
1075 }
1076 }
1077 return null;
1078 }
1079
1080 @Override
1081 protected void onPostExecute(@Nullable final Void result) {
1082 Utils.sendMessage(context, replyTo, file_sent);
1083 }
1084 }.execute();
1085 }
1086
1087 /**
1088 * Stop sending location updates.
1089 *
1090 * @param context Context instance
1091 * @param replyTo reply Address
1092 */
1093 public static void nolocation(final Context context, final Address replyTo){
1094 Utils.unregisterOngoing(context, toNonNull(OngoingEvent.LOCATION));
1095 final LocationManager man=(LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
1096 man.removeUpdates(locationListener);
1097 locationListener=null;
1098 Utils.sendMessage(context, replyTo, no_longer_listening_for_location_updates);
1099 }
1100
1101 /**
1102 * Take a photo and send it to a server.
1103 *
1104 * @param context Context instance
1105 * @param replyTo reply Address
1106 * @param hostname server hostname
1107 * @param port server port
1108 */
1109 public static void photo(final Context context, final Address replyTo, final String hostname, final int port){
1110 startCamera(context, replyTo);
1111 if(camera==null)
1112 return;
1113 final Camera.Parameters parms=camera.getParameters();
1114 parms.setJpegQuality(70);
1115 parms.setPictureFormat(ImageFormat.JPEG);
1116 camera.setParameters(parms);
1117
1118 final SurfaceView fakeView=new SurfaceView(context);
1119 try {
1120 camera.setPreviewDisplay(fakeView.getHolder());
1121 } catch (IOException e) {
1122 Utils.sendMessage(context, replyTo, error_setting_preview_display);
1123 return;
1124 }
1125 camera.startPreview();
1126 final Handler handler=new Handler();
1127
1128 new Thread(new Runnable() {
1129 @Override
1130 public void run() {
1131 try {
1132 Thread.sleep(2000);
1133 } catch (InterruptedException e) {
1134 //ignored
1135 }
1136
1137 handler.post(new Runnable() {
1138 @Override
1139 public void run() {
1140 camera.takePicture(null, null, new FonBotPictureCallback(context, replyTo, hostname, port));
1141 }
1142 });
1143 }
1144 }).start();
1145 }
1146
1147 /**
1148 * Send a directory listing to an Address
1149 *
1150 * @param context Context instance
1151 * @param replyTo destination Address
1152 * @param directory directory to list
1153 */
1154 public static void ls(final Context context, final Address replyTo, final String directory) {
1155 final File[] files=new File(directory).listFiles();
1156 if(files==null){
1157 Utils.sendMessage(context, replyTo, string_is_not_a_directory, directory);
1158 return;
1159 }
1160
1161 final StringBuilder sb=new StringBuilder(context.getString(files_in_directory,directory));
1162 for(final File file : files){
1163 sb.append(file.getName());
1164 if(file.isDirectory())
1165 sb.append('/');
1166 sb.append(" ");
1167 }
1168
1169 Utils.sendMessage(context, replyTo, toNonNull(sb.toString()));
1170 }
1171
1172 /**
1173 * Make the phone start ringing if it is not ringing or stop ringing if it is.
1174 *
1175 * @param context Context instance
1176 * @param replyTo reply Address
1177 */
1178 public static void ring(final Context context, final Address replyTo){
1179 setupRingtone(context);
1180 if(ringtone==null){
1181 Utils.sendMessage(context, replyTo, no_ringtone_found);
1182 return;
1183 }
1184 if(ringtone.isPlaying())
1185 stopAlarm(context, replyTo);
1186 else
1187 startAlarm(context, replyTo);
1188 }
1189
1190 /**
1191 * Make the phone start/stop ringing.
1192 *
1193 * @param context Context instance
1194 * @param replyTo reply Address
1195 * @param on true if the phone should start ringing, false otherwise
1196 */
1197 public static void ring(final Context context, final Address replyTo, final boolean on){
1198 setupRingtone(context);
1199 if(ringtone==null){
1200 Utils.sendMessage(context, replyTo, no_ringtone_found);
1201 return;
1202 }
1203 if(on&&!ringtone.isPlaying())
1204 startAlarm(context, replyTo);
1205 else if(ringtone.isPlaying()&&!on)
1206 stopAlarm(context, replyTo);
1207 }
1208
1209 /**
1210 * Send the current ringer mode to an Address
1211 *
1212 * @param context Context instance
1213 * @param replyTo destination Address
1214 */
1215 public static void ringer(final Context context, final Address replyTo){
1216 final AudioManager man=(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1217 switch(man.getRingerMode()){
1218 case AudioManager.RINGER_MODE_NORMAL:
1219 Utils.sendMessage(context, replyTo, ringer_mode_normal);
1220 break;
1221 case AudioManager.RINGER_MODE_VIBRATE:
1222 Utils.sendMessage(context, replyTo, ringer_mode_vibrate);
1223 break;
1224 case AudioManager.RINGER_MODE_SILENT:
1225 Utils.sendMessage(context, replyTo, ringer_mode_silent);
1226 break;
1227 default:
1228 Utils.sendMessage(context, replyTo, unknown_ringer_mode);
1229 }
1230 }
1231
1232 /**
1233 * Set the ringer mode.
1234 *
1235 * @param context Context instance
1236 * @param replyTo reply Address
1237 * @param ringerMode requested ringer mode
1238 *
1239 * @see Utils.RingerMode
1240 */
1241 public static void ringer(final Context context, final Address replyTo, final int ringerMode){
1242 final AudioManager man=(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1243 man.setRingerMode(ringerMode);
1244 ringer(context, replyTo);
1245 }
1246
1247 /**
1248 * Remove a file or empty directory.
1249 *
1250 * @param context Context instance
1251 * @param replyTo reply Address
1252 * @param filename file/empty directory to delete
1253 */
1254 public static void rm(final Context context, final Address replyTo, final String filename){
1255 if(new File(filename).delete())
1256 Utils.sendMessage(context, replyTo, file_deleted);
1257 else
1258 Utils.sendMessage(context, replyTo, error_while_deleting_file);
1259 }
1260
1261 /**
1262 * Clear the keyguard password.
1263 *
1264 * @param context Context instance
1265 * @param replyTo reply Address
1266 * @throws SecurityException if FonBot does not have device administration permissions
1267 */
1268 public static void setPassword(final Context context, final Address replyTo) throws SecurityException{
1269 final DevicePolicyManager dpm=(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1270
1271 dpm.resetPassword("", 0);
1272 Utils.sendMessage(context, replyTo, password_cleared);
1273 }
1274
1275 /**
1276 * Change the keyguard password.
1277 *
1278 * @param context Context instance
1279 * @param replyTo reply Address
1280 * @param password new password
1281 * @throws SecurityException if FonBot does not have device administration permissions
1282 */
1283 public static void setPassword(final Context context, final Address replyTo, final String password) throws SecurityException{
1284 final DevicePolicyManager dpm=(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1285
1286 dpm.resetPassword(password, 0);
1287 Utils.sendMessage(context, replyTo, password_set);
1288 }
1289
1290 /**
1291 * Send a text message.
1292 *
1293 * @param context Context instance
1294 * @param replyTo reply Address
1295 * @param destination destination phone number
1296 * @param text text message contents
1297 */
1298 public static void sms(final Context context, final Address replyTo, final String destination, final String text){
1299 final SmsManager manager=SmsManager.getDefault();
1300 final ArrayList<String> messages=manager.divideMessage(text);
1301 if(messages.size() > 1)
1302 Utils.sendMessage(context, replyTo, message_was_split_into_parts, Integer.valueOf(messages.size()));
1303
1304 final ArrayList<PendingIntent> sents=new ArrayList<PendingIntent>(messages.size());
1305 final ArrayList<PendingIntent> delivereds=new ArrayList<PendingIntent>(messages.size());
1306
1307 final String name=Utils.callerId(context, destination);
1308 final String fullDestination;
1309 if(name==null)
1310 fullDestination=destination;
1311 else
1312 fullDestination=destination+" ("+name+")";
1313
1314 for(int i=0;i<messages.size();i++){
1315 final Intent sent=new Intent(context,SmsStatusReceiver.class);
1316 sent.putExtra(SmsStatusReceiver.EXTRA_DESTINATION, fullDestination);
1317 sent.putExtra(SmsStatusReceiver.EXTRA_PART, i+1);
1318 sent.putExtra(SmsStatusReceiver.EXTRA_TOTAL, messages.size());
1319 sent.putExtra(SmsStatusReceiver.EXTRA_REPLY_TO, replyTo.toString());
1320 sent.setAction(SmsStatusReceiver.SENT_ACTION+i);//actions must be unique
1321 sents.add(PendingIntent.getBroadcast(context, 0, sent, PendingIntent.FLAG_UPDATE_CURRENT));
1322
1323 final Intent delivered=new Intent(context, SmsStatusReceiver.class);
1324 delivered.putExtra(SmsStatusReceiver.EXTRA_DESTINATION, fullDestination);
1325 delivered.putExtra(SmsStatusReceiver.EXTRA_PART, i+1);
1326 delivered.putExtra(SmsStatusReceiver.EXTRA_TOTAL, messages.size());
1327 delivered.putExtra(SmsStatusReceiver.EXTRA_REPLY_TO, replyTo.toString());
1328 delivered.setAction(SmsStatusReceiver.DELIVERED_ACTION+i);//actions must be unique
1329 delivereds.add(PendingIntent.getBroadcast(context, 0, delivered, PendingIntent.FLAG_UPDATE_CURRENT));
1330 }
1331
1332 Log.d(Heavy.class.getName(), "Sending sms to "+destination);
1333 manager.sendMultipartTextMessage(destination, null, messages, sents, delivereds);
1334 }
1335
1336 /**
1337 * Send the last SMSes to an Address.
1338 *
1339 * @param context Context instance
1340 * @param replyTo destination Address
1341 * @param numSms how many SMSes to send
1342 */
1343 public static void smslog(final Context context, final Address replyTo, final int numSms) {
1344 final String[] fields = {"type","address", "body", "date"};
1345
1346 final Cursor cursor = context.getContentResolver().query (
1347 Uri.parse("content://sms"),
1348 fields,
1349 null,
1350 null,
1351 "date DESC"
1352 );
1353
1354 if (cursor.moveToFirst()) {
1355 do {
1356 final String fromNumber=cursor.getString(1);
1357 final String from;
1358 final String name=Utils.callerId(context, Utils.toNonNull(fromNumber));
1359 if(name==null)
1360 from=fromNumber;
1361 else
1362 from=fromNumber+" ("+name+')';
1363 final String message=cursor.getString(2).replace("\n", "\n ");
1364 final Date date=new Date(cursor.getLong(3));
1365
1366 if(cursor.getInt(0)==1)
1367 Utils.sendMessage(context, replyTo, incoming_message, from, message, date);
1368 else
1369 Utils.sendMessage(context, replyTo, outgoing_message, from, message, date);
1370 } while (cursor.moveToNext() && cursor.getPosition() < numSms);
1371 }
1372
1373 cursor.close();
1374 }
1375
1376 /** TTS instance, only used by {@link #speak(Context, Address, String)} */
1377 private static TextToSpeech tts;
1378
1379 /**
1380 * Speak a String using the text-to-speech engine.
1381 *
1382 * @param context Context instance
1383 * @param replyTo reply Address
1384 * @param text text to speak
1385 */
1386 public static void speak(final Context context, final Address replyTo, final String text){
1387 tts=new TextToSpeech(context, new OnInitListener() {
1388 @Override
1389 public void onInit(final int status) {
1390 if(status==TextToSpeech.SUCCESS){
1391 Utils.sendMessage(context, replyTo, speaking);
1392 tts.speak(text, TextToSpeech.QUEUE_ADD, null);
1393 } else
1394 Utils.sendMessage(context, replyTo, tts_engine_not_available);
1395 }
1396 });
1397 }
1398
1399 /**
1400 * Show a toast notification with the default duration.
1401 *
1402 * @param context Context instance
1403 * @param replyTo reply Address
1404 * @param text toast text
1405 */
1406 public static void toast(final Context context, final Address replyTo, final String text){
1407 toast(context, replyTo, text, Toast.LENGTH_SHORT);
1408 }
1409
1410 /**
1411 * Show a toast notification.
1412 *
1413 * @param context Context instance
1414 * @param replyTo reply Address
1415 * @param text toast text
1416 * @param duration toast duration
1417 */
1418 public static void toast(final Context context, final Address replyTo, final String text, final int duration){
1419 Toast.makeText(context,text,duration).show();
1420 Utils.sendMessage(context, replyTo, toast_shown);
1421 }
1422
1423 /**
1424 * Make the phone vibrate for a number of milliseconds.
1425 *
1426 * @param context Context instance
1427 * @param replyTo reply Address
1428 * @param ms vibrate duration, in milliseconds
1429 */
1430 public static void vibrate(final Context context, final Address replyTo, final long ms){
1431 final Vibrator v=(Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
1432 Utils.sendMessage(context, replyTo, vibrating);
1433 v.vibrate(ms);
1434 }
1435
1436 /**
1437 * View an URI in an appropriate activity.
1438 *
1439 * @param context Context instance
1440 * @param replyTo reply Address
1441 * @param uri URI to view
1442 */
1443 public static void view(final Context context, final Address replyTo, final Uri uri) {
1444 try{
1445 final Intent intent=new Intent(Intent.ACTION_VIEW);
1446 intent.setData(uri);
1447 intent.setFlags(Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_ACTIVITY_NEW_TASK);
1448 context.startActivity(intent);
1449 Utils.sendMessage(context, replyTo, url_opened);
1450 } catch(ActivityNotFoundException e){
1451 Utils.sendMessage(context, replyTo, no_activity_found_for_this_url);
1452 } catch(Exception e){
1453 Utils.sendMessage(context, replyTo, invalid_url);
1454 }
1455 }
1456
1457 /**
1458 * Get the current WiFi state.
1459 *
1460 * @param context Context instance
1461 * @param replyTo reply Address
1462 */
1463 public static void wifi(final Context context, final Address replyTo){
1464 final WifiManager man=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
1465 if(man.isWifiEnabled())
1466 Utils.sendMessage(context, replyTo, wifi_on);
1467 else
1468 Utils.sendMessage(context, replyTo, wifi_off);
1469 }
1470
1471 /**
1472 * Set the WiFi state.
1473 *
1474 * @param context Context instance
1475 * @param replyTo reply Address
1476 * @param on the requested WiFi state
1477 */
1478 public static void wifi(final Context context, final Address replyTo, final boolean on){
1479 final WifiManager man=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
1480 man.setWifiEnabled(on);
1481 if(on)
1482 Utils.sendMessage(context, replyTo, enabling_wifi);
1483 else
1484 Utils.sendMessage(context, replyTo, disabling_wifi);
1485 }
1486
1487 /**
1488 * Factory reset the phone, optionally deleting the SD card too.
1489 *
1490 * @param context Context instance
1491 * @param type {@link Utils.WipeType} instance
1492 * @throws SecurityException if FonBot does not have device administration permissions
1493 */
1494 @SuppressLint("InlinedApi")
1495 public static void wipe(final Context context, final WipeType type) throws SecurityException{
1496 final DevicePolicyManager dpm=(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1497
1498 switch(type){
1499 case DATA:
1500 dpm.wipeData(0);
1501 break;
1502 case FULL:
1503 dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
1504 break;
1505 }
1506 }
1507
1508 /**
1509 * Disable a Command. The command cannot be used until enabled again with the {@link Utils.Command#ENABLE ENABLE} command.
1510 *
1511 * @param context Context instance
1512 * @param replyTo reply Address
1513 * @param command Command to disable
1514 */
1515 public static void disable(final Context context, final Address replyTo, final Command command){
1516 PreferenceManager.getDefaultSharedPreferences(context).edit()
1517 .putBoolean(command+"disabled", true).commit();
1518 Utils.sendMessage(context, replyTo, command_disabled, command);
1519 }
1520
1521 /**
1522 * Re-enable a disabled Command.
1523 *
1524 * @param context Context instance
1525 * @param replyTo reply Address
1526 * @param command Command to re-enable
1527 */
1528 public static void enable(final Context context, final Address replyTo, final Command command){
1529 PreferenceManager.getDefaultSharedPreferences(context).edit()
1530 .remove(command+"disabled").commit();
1531 Utils.sendMessage(context, replyTo, command_enabled, command);
1532
1533 }
1534
1535 /**
1536 * Check whether a Command is disabled.
1537 *
1538 * @param context Context instance
1539 * @param command Command to check
1540 * @return true if the Command is disabled, false otherwise
1541 */
1542 public static boolean isCommandDisabled(final Context context, final Command command){
1543 return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(command+"disabled", false);
1544 }
1545
1546 /**
1547 * Poll the server for pending commands.
1548 *
1549 * @param context Context instance
1550 * @param replyTo reply Address
1551 */
1552 public static void poll(final Context context, final Address replyTo) {
1553 Utils.sendMessage(context, replyTo, polling_server);
1554 context.startService(new Intent(context, FonBotMainService.class));
1555 }
1556
1557 /**
1558 * Get an instance of {@link ITelephony}
1559 *
1560 * @param context Context instance
1561 * @return an instance of {@link ITelephony}
1562 * @throws NoSuchMethodException thrown by reflection
1563 * @throws IllegalArgumentException thrown by reflection
1564 * @throws IllegalAccessException thrown by reflection
1565 * @throws InvocationTargetException thrown by reflection
1566 */
1567 private static ITelephony getITelephony(final Context context) throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
1568 final TelephonyManager man=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1569 final Method m=TelephonyManager.class.getDeclaredMethod("getITelephony");
1570 m.setAccessible(true);
1571 return toNonNull((ITelephony) m.invoke(man));
1572 }
1573
1574 /**
1575 * Hang up the phone.
1576 *
1577 * @param context Context instance
1578 * @param replyTo reply Address
1579 */
1580 public static void hangup(final Context context, final Address replyTo){
1581 try{
1582 getITelephony(context).endCall();
1583 } catch(Exception e){
1584 Utils.sendMessage(context, replyTo, exception_while_hanging_up_call,
1585 e.getClass().getName(), e.getMessage());
1586 }
1587 }
1588
1589 /**
1590 * Answer the phone if it is ringing.
1591 *
1592 * @param context Context instance
1593 * @param replyTo reply Address
1594 */
1595 public static void answer(final Context context, final Address replyTo){
1596 try{
1597 getITelephony(context).answerRingingCall();
1598 } catch(Exception e){
1599 Utils.sendMessage(context, replyTo, exception_while_answering_call,
1600 e.getClass().getName(), e.getMessage());
1601 }
1602 }
1603
1604 /**
1605 * Launch a package.
1606 *
1607 * @param context Context instance
1608 * @param replyTo reply Address
1609 * @param pkg name of the package to launch
1610 */
1611 public static void launch(final Context context, final Address replyTo, final String pkg){
1612 final Intent intent=context.getPackageManager().getLaunchIntentForPackage(pkg);
1613 if(intent==null){
1614 Utils.sendMessage(context, replyTo, no_such_package);
1615 return;
1616 }
1617 context.startActivity(intent);
1618 Utils.sendMessage(context, replyTo, app_launched);
1619 }
1620
1621 /**
1622 * Get the mobile data enabled status.
1623 *
1624 * @param context Context instance
1625 * @param replyTo reply Address
1626 */
1627 public static void data(final Context context, final Address replyTo){
1628 try{
1629 final ConnectivityManager man=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1630 final Method m=ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
1631 m.setAccessible(true);
1632 if(((Boolean)m.invoke(man)).booleanValue())
1633 Utils.sendMessage(context, replyTo, data_on);
1634 else
1635 Utils.sendMessage(context, replyTo, data_off);
1636 } catch(Exception e){
1637 Utils.sendMessage(context, replyTo, exception_while_determining_data_state,
1638 e.getClass().getName(), e.getMessage());
1639 }
1640 }
1641
1642 /**
1643 * Set the mobile data enabled status.
1644 *
1645 * @param context Context instance
1646 * @param replyTo reply Address
1647 * @param enable whether to enable mobile data
1648 */
1649 public static void data(final Context context, final Address replyTo, final boolean enable) {
1650 try{
1651 if(enable){
1652 getITelephony(context).enableDataConnectivity();
1653 Utils.sendMessage(context, replyTo, enabling_data);
1654 } else {
1655 getITelephony(context).disableDataConnectivity();
1656 Utils.sendMessage(context, replyTo, disabling_data);
1657 }
1658 } catch(Exception e){
1659 Utils.sendMessage(context, replyTo, exception_while_getting_itelephony,
1660 e.getClass().getName(), e.getMessage());
1661 }
1662 }
1663
1664 /**
1665 * Get the GPS status.
1666 *
1667 * @param context Context instance
1668 * @param replyTo reply Address
1669 */
1670 public static void gps(final Context context, final Address replyTo){
1671 if(Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER))
1672 Utils.sendMessage(context, replyTo, gps_on);
1673 else
1674 Utils.sendMessage(context, replyTo, gps_off);
1675 }
1676
1677 /**
1678 * Set the GPS status.
1679 *
1680 * @param context Context instance
1681 * @param replyTo reply Address
1682 * @param enabled requested GPS status
1683 */
1684 public static void gps(final Context context, final Address replyTo, final boolean enabled) {
1685 Secure.setLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER, enabled);
1686 if(enabled)
1687 Utils.sendMessage(context, replyTo, enabling_gps);
1688 else
1689 Utils.sendMessage(context, replyTo, disabling_gps);
1690 }
1691
1692 /**
1693 * Get the Google location (aka network location) state.
1694 *
1695 * @param context Context instance
1696 * @param replyTo reply Address
1697 */
1698 public static void glocation(final Context context, final Address replyTo){
1699 if(Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.NETWORK_PROVIDER))
1700 Utils.sendMessage(context, replyTo, network_location_on);
1701 else
1702 Utils.sendMessage(context, replyTo, network_location_off);
1703 }
1704
1705 /**
1706 * Set the Google location (aka network location) state.
1707 *
1708 * @param context Context instance
1709 * @param replyTo reply Address
1710 * @param enabled requested Google location state
1711 */
1712 public static void glocation(final Context context, final Address replyTo, final boolean enabled) {
1713 Secure.setLocationProviderEnabled(context.getContentResolver(), LocationManager.NETWORK_PROVIDER, enabled);
1714 if(enabled)
1715 Utils.sendMessage(context, replyTo, enabling_network_location);
1716 else
1717 Utils.sendMessage(context, replyTo, disabling_network_location);
1718 }
1719
1720 /**
1721 * Reboot the phone.
1722 *
1723 * @param context Context instance
1724 * @param replyTo reply Address
1725 * @param reason reboot reason
1726 *
1727 * @see PowerManager#reboot(String)
1728 */
1729 public static void reboot(final Context context, final Address replyTo, final @Nullable String reason) {
1730 final PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
1731 Utils.sendMessage(context, replyTo, rebooting);
1732 pm.reboot(reason);
1733 }
1734
1735 /**
1736 * Cancel a notification.
1737 *
1738 * @param context Context instance
1739 * @param replyTo reply Address
1740 * @param id notification ID
1741 */
1742 public static void notify(final Context context, final Address replyTo, final int id) {
1743 final NotificationManager man=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
1744 man.cancel(id);
1745 Utils.sendMessage(context, replyTo, notification_canceled);
1746 }
1747
1748 /**
1749 * Show a notification.
1750 *
1751 * @param context Context instance
1752 * @param replyTo reply Address
1753 * @param id notification ID
1754 * @param title notificationO title
1755 * @param text notification text
1756 */
1757 public static void notify(final Context context, final Address replyTo, final int id, final String title, final String text) {
1758 final NotificationManager man=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
1759 man.notify(id, new NotificationCompat.Builder(context).
1760 setContentTitle(title).
1761 setContentText(text).
1762 setSmallIcon(android.R.drawable.stat_notify_sync_noanim).
1763 build());
1764 Utils.sendMessage(context, replyTo, notification_shown);
1765 }
1766
1767 /**
1768 * Take a screen capture. Uses the screencap utility and requires root.
1769 *
1770 * @param context Context instance
1771 * @param replyTo reply Address
1772 * @param filename capture file location
1773 */
1774 public static void screencap(final Context context, final Address replyTo, final String filename){
1775 new Thread(new ScreencapRunnable(context, replyTo, filename)).start();
1776 }
1777
1778 /**
1779 * Toggle the torch state using the Torch (net.cactii.torch2) app.
1780 *
1781 * @param context Context instance
1782 * @param replyTo reply Address
1783 */
1784 public static void torch(final Context context, final Address replyTo){
1785 context.sendBroadcast(new Intent("net.cactii.flash2.TOGGLE_FLASHLIGHT"));
1786 Utils.sendMessage(context, replyTo, toggling_torch_state);
1787 }
1788 }
This page took 0.076306 seconds and 4 git commands to generate.