banner



How To Start A Service From Mainactivity Android

What is a Service in Android?

A Service is an application component that tin perform long-running operation in the background and does not provide a use interface.

So, a Service, yous can say, it ever run on the background and it has nothing to do with user interface. For example, a Service can be downloading something in the background or long running database operation in the background. Or you tin say, if you desire to provide some music in the groundwork then you can use Service for that.

Service can essentially take 2 forms.

  1. Started Service
  2. Bound Service.

Started Service

A Service is Started when an application component such as an activity starts it by calling a method called startService method. And once the Service has started, it can run in background indefinitely unless and until it's destroyed past some component

Spring Service.

A Service is called Leap when application component binds to it by calling bindService method.

Basic Component o Service in Android

i) To create a service in Android we need to create a subclass of Service.

2) The near of import callback method you should override are

  • onStartCommand,
  • onBind,
  • onCreate method and on Destroy method

Started Service in Android application.

Please follow the steps below for creating Started Service in Android application:

Step 1) First in the blank projection drag and drop ii buttons and change the text of this button every bit Start Service and the second button text will name it equally Stop Service. So we accept ii buttons, Start Service and Stop Service.

Stride 2) Then go to the design of this activity and in there add one more aspect, one we will call onClick attribute and start service method.

Same we want to exercise with the button which is Stop Service, so we volition phone call a method, onClick, which will exist a Terminate service.

Step 3) Now, go to Java, mainactivity.java class

And in there we will create these two methods which are startservice method and stopservice method.

Pace four) Now afterward creating these 2 methods, create a class which will bracket from serviceclass.therefore go bundle,  right click here and volition create a new Coffee course.

proper name the class every bit, for example, 'TheService'.

Pace 5) At present a class called TheService will be created

Now we take to extend from this serviceclass but one time you extend from it, y'all will come across it will show this footling fault with this little seedling considering there is a method we must implement, so just click this bulb and but click Implement Method.

And this method nosotros must implement is onBind. Fifty-fifty if nosotros are creating a Started Service, nosotros must implement this or overwrite this so now this error is gone.

Step 6) At present, nosotros will just add our three more than method which we should implement. First is onCreate, 2nd is onStartCommand and third is onDestroy.

Stride vii) Now in one case you lot create or implement these methods what  you lot can start a Service using this onStart command and you can destroy a Service using this onDestroy control, okay

Then, nosotros will do just the same therefore just delete this line and what we can do is, we tin create a Toast and so we know that the Service has started.

Next, what nosotros can do here is we will render our constant here and so return, and we'll return a abiding called START_STICKY.

Now, what is this constant? When you press your Control push and click this constant, you will go to the definition of this constant and hither you will run into,

"This mode makes sense for the things that will be explicitly started and stopped to run for arbitrary periods of time." And that's what we are exactly doing. So, that'south why we are returning this constant called START_STICKY hither.

Step 8) And inside this onDestroy method, what we want to do is we want to display this Toast message once again. But this time nosotros will say that the Service is Destroyed,  Then, we know when Service has Started and When Service is Destroyed.

Pace nine) Now, once nosotros take these method implemented, nosotros will get to mainactivity.java file where we have defined our startService and stopService methods and in here, we can offset the Service using our Intent object.

And once you create an object of this intent you lot tin get-go service past using this intent. And so, you tin can merely pass this intent object

Aforementioned we want to practise in the stopService method and this fourth dimension, instead of starting the Service, nosotros just desire to stop it.

Once everything is done, we but need to do one more thing. We simply need to go to manifest.xml file

 And in there inside our application, we need to create a tag called "service" and we will name this tag service equally 'TheService'  because our class name is 'TheService'. And ane more thing yous can do here is you lot can add an attribute called android export and make it false. And what this will do is information technology'll prevent the other apps or other activities to utilise this Service.


Once everything is washed, we just need to practise one more than thing. We just need to go to manifest.xml file

 And in there inside our application, we need to create a tag called "service" and nosotros will name this tag service as 'TheService', because our class name is 'TheService'. And one more thing y'all can do here is yous can add together aspect called android export and make it false. And what this will do is it'll preclude the other apps or other activities to apply this Service

Now let's run our app. So, now our app is running and then when we click the First Service push, it shows Service Started. But it's running in the background. So, how we can check that the Service is running?

What yous tin can exercise is you can go to the settings of your phone and inside Settings-> Apps. And inside the Apps in that location are downloaded apps and there are running apps, then just click running apps here. And inside the apps which are running, and so you will see Service Demo here.

Now, to destroy this Service, get-go the Service Demo, over again and click Finish Service push button. And you can see Service Destroyed. And once again, become to the settings, and you will run across this service is destroyed and we cannot come across this service.

Complete Code For Creating Started Service in Android

app-java-MainActivity.coffee

          package com.example.programmingknowledge.servicedemo;  import ... public form MainActivity extends ActionBarActivity {     @Override     protected void onCreate(Bundle savedInstanceState){         super.onCreate(savedInstanceState);         setContentView(R.layout.activty_main);     }     public void startService(View view){         Intent intent = new Intent(this, theService.class);         startService(intent);     }     public void stopService(View view){         Intent intent = new Intent(this, theService.course);         stopService(intent);     }     @Override     public boolean onCreateOptionMenu(Menu menu){         //Inflate the carte du jour; this adds items to the action bar if it is present         getMenuInflater().inflate(R.menu.menu_main, bill of fare);         return truthful;     }     @Override      public boolean onOptionsItemSelected(MenuItem item) {         int id = item.getItemId();         if(id == R.id.action_settings)         {             return true;         }         return super.onOptionsItemSelected(item);     } }        

app-java-TheService.java

          package com.example.programmingknowledge.servicedemo;  import android.app.Service; import android.content.Intent; import android.bone.IBinder; /**  * Created past ProgrammingKnowledge on 7/26/2015 */ public class TheService extends Service {         @Override     public void onCreate() {         super.onCreate();     }     @Override     public int onStartCommand(Intent intent, int flags, int startId) {         Toast.makeText(TheService.this,"Service Started",Toast.LENGTH_LONG).show();         render START_STICKY;     }     @Override     public void onDestroy() {         Toast.makeText(TheService.this,"Service Destroyed",Toast.LENGTH_LONG).show();     }     @Override     public IBinder onBind(Intent intent) {         return null;     } }        

app-Manifests-AndroidManifest.xml

          <?xml version="one.0" encoding="utf-8" ?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.programmingknowledge.servicedemo" >     <application         android:allowBackup="true"         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/AppTheme" >         <activity             android:proper noun=".MainActivity"             android:label="@string/app_name" >             <intent-filter>                 <activity android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>         <service android:name=".TheService"             android:exported="false"></service>     </application> </manifest>                  

app-res-layout-activity_main.xml

          <RelativeLayout xmlns="http://schema.android.com/apk/res/android"     xmlns:tools="http://schema.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="16dp"     android:paddingLeft="16dp"     android:paddingRight="16dp"     android:paddingTop="16dp"     tools:context=".MainActivity">     <Button         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Start Service"         android:id="@+id/push button"         android:layout_alignParentTop="truthful"         android:layout_alignParentLeft="true"         android:layout_alignParentStart="true"         android:layout_marginLeft="74dp"         android:layout_marginStart="74dp"         android:layout_marginTop="66dp"         android:onClick="startService" />     <Push         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Stop Service"         android:id="@+id/button2"         android:layout_below="@+id/button"         android:layout_alignEnd="@+id/push button"         android:layout_marginTop="28dp"         android:onClick="stopService"  /> </RelativeLayout>        

Read Adjacent Leap Service Instance in Android

How To Start A Service From Mainactivity Android,

Source: https://www.stechies.com/android-service-introduction-creating-started-service/

Posted by: bratcherwithile1984.blogspot.com

0 Response to "How To Start A Service From Mainactivity Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel