Tuesday, 1 October 2013

How to stop service at particular time on Android?

This might be an old question but I came across this issue myself today and figured a way to do it: You can use a new service which stops your service, and start that service in the desired time on a daily basis using alarm manager, like this:
Define the service which will stop your service:
package com.youractivity;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


public class MyServiceTerminator extends Service {

  @Override
public int onStartCommand(Intent intent, int flags, int startId) {
      return Service.START_NOT_STICKY;
  }


public void onCreate()
  {
     Intent service = new Intent(this, MyService.class);
    stopService(service);   //stop MyService
    stopSelf();     //stop MyServiceTerminator so that it doesn't keep running uselessly
  }

  @Override
  public IBinder onBind(Intent intent) {
  //TODO for communication return IBinder implementation
    return null;
  }
} 
add the following code after the one you posted, and run the method inside your activity:
private void stopRecurringAlarm(Context context) {
    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getTimeZone("GMT+3"));
    updateTime.set(Calendar.HOUR_OF_DAY, 18);
    updateTime.set(Calendar.MINUTE, 0);
    Intent intent = new Intent(this, MyServiceTerminator.class);
    PendingIntent pintent = PendingIntent.getService(context, 1, intent,    PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.setRepeating(AlarmManager.RTC_WAKEUP,updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);
}
this way the service will be scheduled to start as you posted above, and scheduled to stop at 6 as shown in the code I posted.

Monday, 30 September 2013

How to use alarmmanager 2 times every day?

You can use an interval of AlarmManager.INTERVAL_DAY / 2 :

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 35);
 calendar.set(Calendar.SECOND, 0); 
 
 AlarmManager am = (AlarmManager)getApplicationContext().getSystemService  (Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
 PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,      PendingIntent.FLAG_UPDATE_CURRENT);
 am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),        AlarmManager.INTERVAL_DAY / 2, pi);


but if the time of the day in which you fire your alarm matters you can use two calendar objects :
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 12); //midday
cal1.set(Calendar.MINUTE, 00);
cal1.set(Calendar.SECOND, 00); 
 
 
 Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, 18);//8pm for example
cal2.set(Calendar.MINUTE, 00);
cal2.set(Calendar.SECOND, 00);
and set your alarm manager :
am.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),cal2.getTimeInMillis(), pi);

Wednesday, 17 July 2013

android video player from SD card

package com.example.videoplaysdcard;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {
    VideoView videoView_player;
    private static final String TAG="com.example.videoplaysdcard.MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUIElements();
        playVideoFile("/mnt/sdcard/backups/p.mp4");
    }



    private void initUIElements() {
        videoView_player = (VideoView) findViewById(R.id.videoView_player);
    }
   
    private void playVideoFile(String sdCardPath) {
        try{
        MediaController mc = new MediaController(this);
        mc.setAnchorView(videoView_player);
        mc.setMediaPlayer(videoView_player);
        videoView_player.setMediaController(mc);
        videoView_player.setVideoPath(sdCardPath);
        videoView_player.requestFocus();
        videoView_player.start();
        }catch(Exception e){
            Log.e(TAG,e.toString());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Monday, 8 July 2013

Android radio buttons example

In Android, you can use “android.widget.RadioButton” class to render radio button, and those radio buttons are usually grouped by android.widget.RadioGroup. If RadioButtons are in group, when one RadioButton within a group is selected, all others are automatically deselected.
In this tutorial, we show you how to use XML to create two radio buttons, and grouped in a radio group. When button is clicked, display which radio button is selected.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Custom String

Open “res/values/strings.xml” file, add some custom string for radio button.
File : res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MyAndroidAppActivity!</string>
    <string name="app_name">MyAndroidApp</string>
    <string name="radio_male">Male</string>
    <string name="radio_female">Female</string>
    <string name="btn_display">Display</string>
</resources>

2. RadioButton

Open “res/layout/main.xml” file, add “RadioGroup“, “RadioButton” and a button, inside the LinearLayout.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <RadioGroup
        android:id="@+id/radioSex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
 
        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />
 
        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />
 
    </RadioGroup>
 
    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_display" />
 
</LinearLayout>
Radio button selected by default.
To make a radio button is selected by default, put android:checked="true" within the RadioButton element. In this case, radio option “Male” is selected by default.

3. Code Code

Inside activity “onCreate()” method, attach a click listener on button.
File : MyAndroidAppActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
 
public class MyAndroidAppActivity extends Activity {
 
  private RadioGroup radioSexGroup;
  private RadioButton radioSexButton;
  private Button btnDisplay;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 
 addListenerOnButton();
 
  }
 
  public void addListenerOnButton() {
 
 radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
 btnDisplay = (Button) findViewById(R.id.btnDisplay);
 
 btnDisplay.setOnClickListener(new OnClickListener() {
 
  @Override
  public void onClick(View v) {
 
          // get selected radio button from radioGroup
   int selectedId = radioSexGroup.getCheckedRadioButtonId();
 
   // find the radiobutton by returned id
          radioSexButton = (RadioButton) findViewById(selectedId);
 
   Toast.makeText(MyAndroidAppActivity.this,
    radioSexButton.getText(), Toast.LENGTH_SHORT).show();
 
  }
 
 });
 
  }
}

4. Demo

Run the application.
1. Result, radio option “Male” is selected.
android radio button demo1
2. Select “Female” and click on the “display” button, the selected radio button value is displayed.
android radio button demo2

Download Source Code

Download it – Android-RadioButton-Example.zip (15 KB)