Saturday, March 12, 2011

Create background service.

The following code uses buttons to call the service. you can start the service any way you want.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ButtonStart = new Button(this);
    ButtonStop = new Button(this);

    ButtonStart.setOnClickListener(this);
    ButtonStart.setId(1000);
    ButtonStart.setText("Start Service");
    
    ButtonStop.setOnClickListener(this);
    ButtonStop.setId(2000);
    ButtonStop.setText("Stop Service");

    
    LinearLayout OverView = new LinearLayout(this);
 OverView.setOrientation( LinearLayout.VERTICAL );
 OverView.setScrollContainer(true); 
 
 
 OverView.addView( ButtonStart );
 OverView.addView( ButtonStop);

 setContentView(OverView);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case 1000:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, myService.class));
      break;
    case 2000:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, myService.class));
      break;
    }
  }


You might want to set a service running in the background. The following code setup a notification in the background and check some numbers every seconds. If the number match a criteria, notification will be updated.
public void onCreate() {
  // The following define the notification bar area layout
  //Intent intent = new Intent(this, MainActivity.class);
  notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
  notification = new Notification();
  notification.icon = R.drawable.icon;
  notification.defaults = Notification.DEFAULT_SOUND;
  notification.tickerText = "Bu.......";
  notification.flags |= Notification.FLAG_AUTO_CANCEL;

  Intent notifyIntent = new Intent(getBaseContext(), ServiceDemo.class);
  PendingIntent PendTntent = PendingIntent.getActivity(this, 0, notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
  notification.setLatestEventInfo(this,"Title","Check the latest update",PendTntent);


  //notification = new Notification(R.drawable.icon,"test",null,"title",null);
  //PendingIntent contentIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
  
  
  // The following is something will run every 1 s.
  
         new Thread(new Runnable(){  
             int myCounter = (int) (msec%4000);
             @Override 
             public void run() {  
                 while (bThreadRunning) {  
                     try {  
                         Thread.sleep(1000);  
                     } catch (InterruptedException e) {  
                     }  
                     myCounter = (int) (msec%4000);
                     Log.i(TAG, "myservice running " + (msec+=1000) + "ms.");  
                     Log.i(TAG, "Your number is  " + (msec%4000) + " **");  

               if (myCounter == 0 ) {
                //notification.icon = R.drawable.icon;
                //notification.tickerText = "Bu.......";
                //notification.when = System.currentTimeMillis(); //通知产生的时间,会在通知信息里显示
                //notification.defaults = Notification.DEFAULT_SOUND;
                notification.tickerText = String.valueOf( msec );
                        Log.i(TAG, "Playing sound");  
                  notificationManager.notify(0, notification);

              }
               
                 }  
             }  
         }).start();  
         
     }  

Service onCreate running in the background all the time, if you want the service do something once when it starts, you can use the following code.
public void onStart(Intent intent, int startid) {
  Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
  Log.d(TAG, "onStart");
 }

Notification

Three things needed for a notification on the top.
1. a notification manager manage everything.
2. a notification itself has the icon, sounds, and ticker.
3. a Intent that is going to run when an user click the notification.

notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
  notification = new Notification();
  notification.icon = R.drawable.icon;
  notification.defaults = Notification.DEFAULT_SOUND;
  notification.tickerText = "Bu.......";
  notification.flags |= Notification.FLAG_AUTO_CANCEL;

  Intent notifyIntent = new Intent(getBaseContext(), ServiceDemo.class);
  PendingIntent PendTntent = PendingIntent.getActivity(this, 0, notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
  notification.setLatestEventInfo(this,"Title","Check the latest update",PendTntent);

Once you have everything ready, you can use the following code to trigger the notification.
notificationManager.notify(0, notification); 

Sunday, December 26, 2010

Running Android Develop on Win 7 64-bit

I just updated my OS to win 7 64-bit. I can use all 6 GB of RAM. But the Android Development really gave me trouble. The Eclipse 64-bit might be a good idea but it requires Java-64. Java-64 might conflict with other 32-bit application. In the end, I have to use Java-32 and Eclipse 32.

After Eclipse is installed, you need go to Help->Update Software. That will install the Android Plugin for Eclipse. Once the plugin is installed, you can install Android SDK and point the Android SDK directory in Eclipse.

Since there are many things to download in the Android SDK and I am tired of downloading, I decided to use the old Android SDK directory.

After the Android SDK is pointed to the right directory, you can start developing. Using virtual machine is no problem. If you want to use the real devices, you have to install ADB driver. The driver will recognize your device through USB cable. Common drivers are installed in the Androids SDK usb_driver directory.

For LG Ally, there is an LG driver you need to install. Once you have that installed, everything will be fine.

Friday, December 3, 2010

How to post rating

myRating = new RatingBar(this);  //Create a rating bar.
myRating_Label = new TextView(this);  //Create a label;
  
myRatingView = new LinearLayout(this);  //Create a LinearLayout
myRatingView.setOrientation( LinearLayout.VERTICAL );

myRatingView.addView(myRating_Label);  //Add the label to the View
myRatingView.addView(myRating);  //Add rating bar to the View
  
alert = new AlertDialog.Builder(this).create(); //Create a AlertDialog

alert.setView(myRatingView);  //Add the Rating View to the alert

  // Add a button to the Alert
alert.setButton("Submit", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
    String value = "Thanks for your rating " + String.valueOf(User_Rating);
    Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();

   }
});

Create menu

When the Menu button is press on the phone, you can show up a menu to let user do something

public boolean onKeyDown(int keyCode, KeyEvent event){
    if(keyCode == KeyEvent.KEYCODE_MENU) {
         AlertDialog.Builder dialogBuilder = 
             new AlertDialog.Builder(this)
             .setMessage("Dialog Message")
             .setTitle("The Title");
         dialogBuilder.create().show();
         return true;
         }
     return super.onKeyDown(keyCode, event);
}

Thursday, November 18, 2010

Fetch data from html

    public void Fetch_Data(){
     line = "";
        try {
      // Perform action on click
      //Log.w("Fetchhhhhhhhhhhhh","You are going to fetch tip data");
      String tempStr = ""; 
      // Initiate the url connection
      URL url = new URL(The_URL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      while ( (tempStr= rd.readLine()) != null) {
       line = line + tempStr;
       }
      rd = null;
      conn.disconnect();
      }
     catch (Exception e) {
      Log.w("===========",e);

     }
    }

How to use Spinner

private List Game_Mode_List
  for (int i=0;i < Game_Mode.length ;i++) {
   // Populate the Game_Mode List
   Game_Mode_List.add(Game_Mode[i]);
  }
   // Put the Game_Mode_List to an Addapter and set addapter tpye
  ArrayAdapter Game_Mode_Addapter = new ArrayAdapter(
    this, android.R.layout.simple_spinner_dropdown_item, Game_Mode_List);
  Game_Mode_Addapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );
  
    // Create Spinner and attach the addapter to it.
  Spinner Game_Mode_Spinner = new Spinner(this);
  Game_Mode_Spinner.setAdapter(Game_Mode_Addapter);
    // The listener will listen the change. arg2 is the item selected
  Game_Mode_Spinner.setOnItemSelectedListener(
       new AdapterView.OnItemSelectedListener() {
     @Override
     public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
      myGameMode = String.valueOf(arg2);
     }
     @Override
     public void onNothingSelected(AdapterView arg0) {
      myGameMode = "1";
     }
       }
   );