Wednesday, 24 September 2014

Service in Android (GENERATING RANDOM NUMBER ON EACH 30 SEC INTERVALS)



    SERVICE

1. service is an independent process
2. Not affecting activity foreground


 CREATION OF SERVICE FOR GENERATING RANDOM NUMBER ON EACH 30 SEC  INTERVALS




public class CheckingUpdates extends  Service {
Context ctx=this;

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.v("one", "one");
//Creating timer which executes once after 30 seconds
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TaskExampleRepeating(), 30000, 30000);
}

public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}

public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v("one", "four");
//for test -mediaplayer.stop();
Log.v("one", "five");
}

class TaskExampleRepeating  extends TimerTask{
int randomresult1=0,
randomresult2=0,
randomresult3=0;

//This task will execute just once after seven seconds of starting the program
public void run(){

System.out.println(" displayed after " + " ->" + new Date());
Random randomGenerator = new Random();
for (int idx = 1; idx <= 1; ++idx){
randomresult1 = randomGenerator.nextInt(100);
System.out.println("after 30 seconds first-value" + " ->" + randomresult1);

}
for (int idx = 1; idx <= 1; ++idx){
randomresult2 = randomGenerator.nextInt(100);
System.out.println("after 30 seconds second-value" + " ->" + randomresult2);
}
for (int idx = 1; idx <= 1; ++idx){
randomresult3 = randomGenerator.nextInt(100);
System.out.println("after 30 seconds third-value" + " ->" + randomresult3);
}

System.out.println("value" + " ->" + "inserted all" );

}

}
}


CHANGES ON MANIFEST FILE 

       <service
            android:name="com.Packagename.services.CheckingUpdates" android:enabled="true"
            android:process=":myprocess" />
    </application>



ACTIVITY CLASS


@Override
protected void onResume() {
// TODO Auto-generated method stub
startService(new Intent(ActivityOne.this, CheckingUpdates.class));
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
super.onResume();
}


@Override
protected void onStop() {
// TODO Auto-generated method stub
stopService(new Intent(ActivityOne.this, CheckingUpdates.class));
Toast.makeText(this, "Service Stop", Toast.LENGTH_LONG).show();
super.onStop();
}






No comments:

Post a Comment

How to do text writing animation?  In Android Development we do not have the option to use any other custom font in our default Tex...