Advertisement
Guest User

Untitled

a guest
May 20th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.00 KB | None | 0 0
  1. package com.raserbaden.gamlaBettan;
  2.  
  3. import android.util.Log;
  4. import android.app.Activity;
  5. import android.content.Context;
  6. import android.content.SharedPreferences;
  7. import android.os.Bundle;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.view.Display;
  11. import android.view.KeyEvent;
  12. import android.view.Menu;
  13. import android.view.MenuItem;
  14. import android.view.View;
  15. import android.view.Window;
  16. import android.view.WindowManager;
  17. import android.widget.Button;
  18. import android.widget.EditText;
  19. import android.widget.TextView;
  20.  
  21.  
  22.  
  23.  
  24. //This is the activity what I have set in my AndroidManifest.xml file to be the initial activity.
  25. //(name not important, can be anything, no relation to 'main' convention used in C)
  26. public class Main extends Activity {
  27.    
  28.     //ID in log output.
  29.     private static final String TAG = "Main";
  30.    
  31.     //Some randomly chosen ID used in message passing.
  32.     //(in this case, the message that a new timer tick has occurred)
  33.     static final int NEWINTERVAL = 0x1337;
  34.    
  35.     //Some useful variables.
  36.     int activeView = 0;
  37.     boolean isPortrait = true;
  38.     String user = "";
  39.     String password = "";
  40.    
  41.     //Option Menu item id:s.
  42.     final int MAIN_ITEM_ID = 0;
  43.     final int SETTINGS_ITEM_ID = 1;
  44.        
  45.     //A reference to a Display objects (useful later on).
  46.     Display display;
  47.    
  48.     //A reference to view I have defined (mostly) in code.
  49.     MainView mainView;
  50.     TextView userTextView;
  51.     TextView passwordTextView;
  52.    
  53.     //In my SettingsView view.
  54.     EditText userText;
  55.     EditText passwordText;
  56.    
  57.     //Reference to a thread used to hold timer.
  58.     Thread tickerThread;
  59.    
  60.    
  61.    
  62.     //Main constructor (empty).
  63.     public Main(){}
  64.    
  65.    
  66.     //Called by system when activity created (initially or e.g. after a screen rotation).
  67.     //(called before saved instance is restored!)
  68.     @Override
  69.     public void onCreate(Bundle savedInstanceState) {
  70.         super.onCreate(savedInstanceState);
  71.         Log.d(TAG,"Created.");
  72.        
  73.         //Remove status and title bars in landscape mode.
  74.         Window win = getWindow();
  75.         if(win.getWindowManager().getDefaultDisplay().getHeight() < win.getWindowManager().getDefaultDisplay().getWidth()){
  76.             //No Statusbar.
  77.             win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  78.             //No Titlebar.
  79.             requestWindowFeature(Window.FEATURE_NO_TITLE);
  80.             requestWindowFeature(Window.FEATURE_PROGRESS);  
  81.         }
  82.                
  83.         //Retrieve saved data from (persistent) storage in a preferences file.
  84.         //(file is private to this activity and has default name = activity name)
  85.         restoreData();
  86.        
  87.         //Get screen orientation.
  88.         display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
  89.         if(display.getHeight() > display.getWidth()) isPortrait = true; else isPortrait = false;
  90.        
  91.         //Create my mainView.
  92.         mainView = new MainView(this);
  93.  
  94.         //Create thread and put the ticker object in it.
  95.         tickerThread = new Thread(new Ticker());
  96.         tickerThread.start();//will cause the run() method to be called
  97.        
  98.     }  
  99.    
  100.    
  101.     //Called after the activity has been stopped, just prior to it being started again.
  102.     //Always followed by onStart().
  103.     @Override
  104.     public void onRestart() {
  105.         super.onRestart();
  106.         Log.d(TAG,"Restarted.");
  107.     }
  108.    
  109.          
  110.     //Called just before the activity becomes visible to the user.
  111.     //Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
  112.     @Override
  113.     public void onStart() {
  114.         super.onStart();
  115.         Log.d(TAG,"Started.");
  116.     }
  117.  
  118.    
  119.     //Called just before the activity starts interacting with the user.
  120.     //At this point the activity is at the top of the activity stack, with user input going to it.
  121.     //Always followed by onPause().
  122.     @Override
  123.     public void onResume() {
  124.         super.onResume();
  125.         Log.d(TAG,"Resumed.");
  126.        
  127.         if(activeView==MAIN_ITEM_ID) {
  128.             setContentView(mainView);
  129.             //configMainView();
  130.         }
  131.         if(activeView==SETTINGS_ITEM_ID){
  132.             setContentView(R.layout.settings);
  133.             configSettingsView();
  134.         }
  135.     }
  136.  
  137.    
  138.     //Called when the system is about to start resuming another activity.
  139.     //This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on.
  140.     //It should do whatever it does very quickly, because the next activity will not be resumed until it returns.
  141.     //Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.
  142.     @Override
  143.     public void onPause() {
  144.         super.onPause();
  145.         Log.d(TAG,"Paused.");
  146.     }
  147.          
  148.    
  149.     //Called when the activity is no longer visible to the user.
  150.     //This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.
  151.     //Followed either by onRestart() if the activity is coming back to interact with the user, or by onDestroy() if this activity is going away.
  152.     @Override
  153.     public void onStop() {
  154.         super.onStop();
  155.         //Save data to (persistent) storage in a preferences file.
  156.         //(file is private to this activity and has default name = activity name)
  157.         saveData();
  158.         Log.d(TAG,"Stopped.");
  159.     }  
  160.  
  161.    
  162.     //Called before the activity is destroyed.
  163.     //This is the final call that the activity will receive.
  164.     //It could be called either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space.
  165.     //You can distinguish between these two scenarios with the isFinishing() method.
  166.     @Override
  167.     public void onDestroy() {
  168.        
  169.         // Hjalmar: varför körs onDestory först?
  170.         super.onDestroy();
  171.         Log.d(TAG,"Destroyed.");
  172.        
  173.         //Declare ticker thread as interrupted, it will soon exit (hopefully).
  174.         //(might need to check truly exited by calling tickerThread.isAlive() and if so, wait and kill again)
  175.         tickerThread.interrupt();
  176.        
  177.     }
  178.    
  179.  
  180.    
  181.     //Called by system depending on GUI happenings.
  182.     //(use only for GUI state, not for persistent data)
  183.     //(if not present, system will restore GUI state itself, which might not be desirable)
  184.     @Override
  185.     public void onSaveInstanceState(Bundle savedInstanceState){
  186.         super.onSaveInstanceState(savedInstanceState);
  187.     }
  188.    
  189.    
  190.     //Called by system depending on GUI happenings.
  191.     //(use only for GUI state, not for persistent data)
  192.     //(if not present, system will restore GUI state itself, which might not be desirable)
  193.     @Override
  194.     public void onRestoreInstanceState(Bundle savedInstanceState){
  195.         super.onRestoreInstanceState(savedInstanceState);
  196.     }
  197.  
  198.    
  199.    
  200.    
  201.     //Save whatever data you want persistently saved (in the preferences file).
  202.     //(file is private to this activity and has default name = activity name)
  203.     void saveData(){
  204.        
  205.         SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
  206.        
  207.         SharedPreferences.Editor e = settings.edit();
  208.         e.putString("User", user);
  209.         e.putString("Password", password);
  210.         e.commit();
  211.        
  212.         Log.d(TAG,"Saved.");
  213.     }
  214.    
  215.  
  216.     //Restore from data saved (in the preferences file).
  217.     //(file is private to this activity and has default name = activity name)
  218.     void restoreData(){
  219.  
  220.         SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
  221.  
  222.         user = settings.getString("User", "Elisabeth");
  223.         password = settings.getString("Password", "password");
  224.  
  225.         Log.d(TAG,"Restored.");
  226.     }
  227.    
  228.    
  229.    
  230.     //Creates Options Menu items, called first time menu accessed.
  231.     @Override
  232.     public boolean onCreateOptionsMenu(Menu menu){
  233.         super.onCreateOptionsMenu(menu);
  234.         Log.d(TAG,"Options Menu set.");
  235.         menu.add(0, SETTINGS_ITEM_ID, 0, "Settings").setIcon(R.drawable.settings);
  236.         return true;
  237.     }
  238.    
  239.    
  240.    
  241.     //Menu handler, called when an Options Menu item is accessed.
  242.     @Override
  243.     public boolean onOptionsItemSelected(MenuItem item){
  244.         activeView = item.getItemId();
  245.         switch (item.getItemId()){
  246.        
  247.         case MAIN_ITEM_ID:
  248.             Log.d(TAG,"Start accessed.");
  249.             setContentView(mainView);
  250.             configMainView();
  251.             break;//return true;
  252.            
  253.         case SETTINGS_ITEM_ID:
  254.             //Log.d(TAG,"Settings accessed.");
  255.             setContentView(R.layout.settings);
  256.             configSettingsView();
  257.             break;//return true;
  258.            
  259.         }
  260.         return false;
  261.     }
  262.    
  263.    
  264.     //Called right before the menu is shown, every time it is shown (not just first time menu accessed).
  265.     //You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
  266.     @Override
  267.     public boolean onPrepareOptionsMenu(Menu menu) {
  268.         return super.onPrepareOptionsMenu(menu);
  269.     }
  270.  
  271.     void configMainView() {
  272.        
  273.         Log.d(TAG, "configMainView");
  274.         userTextView = (TextView) mainView.findViewById(R.id.userTextView);
  275.         userTextView.setText(user);
  276.        
  277.         passwordTextView = (TextView) mainView.findViewById(R.id.passwordTextView);
  278.         passwordTextView.setText(password);
  279.     }
  280.    
  281.    
  282.     //Called when restoring a Settings view (no separate code for that view).
  283.     void configSettingsView(){
  284.        
  285.         userText = (EditText) findViewById(R.id.user);
  286.         userText.setText(user);
  287.         passwordText = (EditText) findViewById(R.id.password);
  288.         passwordText.setText(password);
  289.        
  290.         Button cancel = (Button) findViewById(R.id.cancel);
  291.         cancel.setOnClickListener(new View.OnClickListener(){
  292.             public void onClick(View v) {
  293.                 activeView = MAIN_ITEM_ID;
  294.                 setContentView(mainView);
  295.             }
  296.         });
  297.        
  298.         Button ok = (Button) findViewById(R.id.ok);
  299.         ok.setOnClickListener(new View.OnClickListener(){
  300.             public void onClick(View v) {
  301.                 user = userText.getText().toString();
  302.                 password = passwordText.getText().toString();
  303.                 saveData();
  304.                 activeView = MAIN_ITEM_ID;
  305.                 setContentView(mainView);
  306.             }
  307.         });
  308.     }
  309.        
  310.  
  311.     //Keyboard handler
  312.     //Called when a key was pressed (and not handled by any of the views inside of the activity).
  313.     @Override
  314.     public boolean onKeyDown(int keyCode, KeyEvent event){
  315.         if(keyCode==KeyEvent.KEYCODE_BACK){
  316.             if(activeView!= MAIN_ITEM_ID){
  317.                 setContentView(mainView);
  318.                 activeView = MAIN_ITEM_ID;
  319.                 return true;
  320.             }else{
  321.                 return super.onKeyDown(keyCode, event);
  322.             }
  323.         }
  324.         return super.onKeyDown(keyCode, event);
  325.     }
  326.    
  327.    
  328.    
  329.     //Handler for clock tick events.
  330.     //(automatically connected to class it resides in!)
  331.     Handler handler = new Handler(){
  332.  
  333.         @Override
  334.         public void handleMessage(Message msg) {
  335.             super.handleMessage(msg);
  336.  
  337.             switch (msg.what) {
  338.             case NEWINTERVAL:
  339.            
  340.                 //Update time.
  341.                
  342.                 /*   now do lots of very serious and important work here ...  :-)   */
  343.                 //Log.d(TAG, "Timer tick handled.");
  344.            
  345.                 //View updated.
  346.                 mainView.invalidate();
  347.                 break;//End (only) case
  348.                
  349.             }//End switch
  350.         }//End handleMessage method
  351.     }; //End Handler anonymous class
  352.  
  353.    
  354.    
  355.  
  356.     //Clock ticker (runs  in it's own thread).
  357.     //(thread runs until run() method exits, in this case loops endlessly until 'interrupted' flag set to true)
  358.     class Ticker implements Runnable {
  359.        // Hjalmar tog bort
  360.         //@Override
  361.         public void run() {
  362.             while(!Thread.currentThread().isInterrupted()){
  363.                  Message m = new Message();
  364.                  m.what = NEWINTERVAL;
  365.                  handler.sendMessage(m);
  366.                  try {
  367.                       Thread.sleep(1000);
  368.                  } catch (InterruptedException e) {
  369.                       Thread.currentThread().interrupt();
  370.                  }
  371.                 // Log.d(TAG, "Tick.");
  372.             }
  373.             Log.d(TAG, "Ticker thread interrupted and now exits.");
  374.         }
  375.     }
  376.  
  377.  
  378. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement