Service in Android
MyNewService.java
package com.ithub.myservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.Toast;public class MyNewService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO: Return the communication channel to the service. //throw new UnsupportedOperationException("Not yet implemented"); return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Toast.makeText(MyNewService.this, "Hello, How are you ?", Toast.LENGTH_SHORT).show(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show(); }}
main_activity.java
package com.ithub.myservice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View v) {
// start service
startService(new Intent(getBaseContext(), MyNewService.class));
}
public void stopService(View v) {
//stop services
stopService(new Intent(getBaseContext(), MyNewService.class));
//Toast.makeText(this, "Service is Stop u can see it here in this Toast..", Toast.LENGTH_SHORT).show();
}
}
Comments
Post a Comment