Service Example

R.layout.single_item

Service which is used for long time task and running in main thread and combination of thread for long running mostly

Service which is used for long time task and running in main thread and combination of thread for long running mostly

Service which is used for long time task and running in main thread and combination of thread for long running mostly

Service which is used for long time task and running in main thread and combination of thread for long running mostly

MainActivity[MainActivity.class]


package com.androidfeeders.serviceexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * Created by ramasamy on 7/06/2018.
 * */

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    String message = "";
    Button mstartServiceButton;
    Button mstopServiceButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mstartServiceButton = (Button) findViewById(R.id.start_service);
        mstopServiceButton = (Button) findViewById(R.id.stop_service);
        mstartServiceButton.setOnClickListener(this);
        mstopServiceButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.start_service:
                startService(new Intent(this, MyServiceManager.class));
                break;
            case R.id.stop_service:
                stopService(new Intent(this, MyServiceManager.class));
                break;
        }
    }
}

MyServiceManager[MyServiceManager.class]

package com.androidfeeders.serviceexample;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by ramasamy on 7/06/2018.
 */
public class MyServiceManager extends Service {

    private final int UPDATE_INTERVAL = 1 * 1000;
    private Timer timer = new Timer();
    private static final int NOTIFICATION_EX = 1;
    private NotificationManager notificationManager;

    public MyServiceManager() {}

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // Code to execute when the service is first created
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        Context context = getApplicationContext();
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = android.R.drawable.stat_notify_sync;
        CharSequence tickerText = "AndroidFeeder";
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Welcome to androidfeeder";
        long when = System.currentTimeMillis();

        Intent notificationIntent = new Intent(this,MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        NotificationCompat.Builder mNotification = new NotificationCompat.Builder(context);
        mNotification.setContentTitle(contentTitle)
                .setContentText(contentText)
                .setContentIntent(contentIntent)
                .setSmallIcon(icon)
                .setContentInfo(tickerText)
                .setWhen(when);
        Notification notification = mNotification.getNotification();
        notificationManager.notify(NOTIFICATION_EX, notification);
        Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
            }
        }, 0, UPDATE_INTERVAL);
        return START_STICKY;
    }

    private void stopService() {
        if (timer != null) timer.cancel();
    }
}

Layout Resource[activity_main.xml]

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="20dp"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/start_service"
        android:text="Start Services"
        android:textColor="@android:color/white"
        android:background="@color/colorAccent"
        android:layout_centerHorizontal="true"
         />

    <Button
        android:layout_width="match_parent"
        android:textColor="@android:color/white"
        android:layout_below="@+id/start_service"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:background="@color/colorAccent"
        android:text="Stop Services"
        android:id="@+id/stop_service"
        />

</RelativeLayout>

Gradle Scripts~build.gradle[Module:app]

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.androidfeeders.serviceexample"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


Gradle Scripts~build.gradle[Project:ServiceExample]

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Resource[strings.xml]

<resources> <string name="app_name">ServiceExample</string> </resources>

manifests

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidfeeders.serviceexample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:enabled="true" android:name=".MyServiceManager"/> </application> </manifest>

Ramasamy

I started to learn android and Kotlin and iOS and Hybrid application and i cant code IOS very well. But i love more interesting to code and finding new developer minds who are join to me You're welcome to keep on using my website.Instead, you can join our FB page for developer comments and post there: https://www.facebook.com/ramasamy.m.779 Best wishes :) Ramasamy(Software Developer)

Android Development and IOS Development & React Native Application

See what's new in Android & IOS & Hybrid development … explore and learn in site

About Ramasamy

Kotlin and React native example too

Related Posts

3 Comments

Ramasamy

5 min ago

Kotlin and React native example too

Reply

Ramasamy

5 min ago

Kotlin and React native example too

Reply

Ramasamy

5 min ago

Kotlin and React native example too

Reply

Leave a reply