Pavle_nis

AlarmManager

Feb 1st, 2017
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. AlarmReceiver.class
  2.  
  3. public class AlarmReceiver extends BroadcastReceiver
  4. {
  5.     private static int conn_length = -1;
  6.     @Override
  7.     public void onReceive(Context context,Intent intent)
  8.     {
  9.         File directory = new File("/sys/bus/usb/devices");
  10.         File[] contents = directory.listFiles();
  11.  
  12.         if(contents.length == conn_length){
  13.             return;
  14.         }
  15.         else{
  16.             conn_length = contents.length;
  17.         }
  18.  
  19.         if(conn_length == 0)
  20.         {
  21.  
  22.             Toast.makeText(context,"otg not connected",Toast.LENGTH_SHORT).show();
  23.         }
  24.         else
  25.         {
  26.             Toast.makeText(context,"otg connected",Toast.LENGTH_SHORT).show();
  27.         }
  28.     }
  29. }
  30.  
  31.  
  32.  
  33. MainActivity.class
  34.  
  35. public class MainActivity extends AppCompatActivity
  36. {
  37.     private Process suProcess;
  38.     private PendingIntent pendingIntent;
  39.  
  40.     @Override
  41.     protected void onCreate(Bundle savedInstanceState)
  42.     {
  43.         super.onCreate(savedInstanceState);
  44.         setContentView(R.layout.activity_main);
  45.  
  46.         getRoot();
  47.  
  48.         Handler handler = new Handler();
  49.         handler.post(alarmUpdater);
  50.     }
  51.  
  52.     public Runnable alarmUpdater= new Runnable() {
  53.         @Override
  54.         public void run() {
  55.             startAlarm();
  56.         }
  57.     };
  58.  
  59.     private void getRoot()
  60.     {
  61.         try
  62.         {
  63.             suProcess = Runtime.getRuntime().exec("su");
  64.         }
  65.         catch (IOException e)
  66.         {
  67.  
  68.         }
  69.     }
  70.  
  71.     private void startAlarm()
  72.     {
  73.         Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
  74.         PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
  75.  
  76.         AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  77.         int interval = 1000;
  78.         manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment