Friday, April 1, 2016

android - Start an Activity from a Service

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#f7f9f4"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Start The Service"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

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


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private Button mButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButton = (Button) findViewById(R.id.btn);

        // Set a click listener for the button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize a new Intent for the service
                Intent intent = new Intent(mContext, RandomNumberService.class);

                // Start the service
                startService(intent);
            }
        });
    }
}
activity_another.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".AnotherActivity"
    android:background="#6ea96d"
    >
</RelativeLayout>
AnotherActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class AnotherActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another);
    }
}
RandomNumberService.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

import java.util.Random;

public class RandomNumberService extends Service {
    private Handler mHandler;
    private Runnable mRunnable;
    private Random mRandom = new Random();

    public RandomNumberService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        // Initialize a new Handler instance
        mHandler = new Handler();

        // Initialize a new Runnable instance
        mRunnable = new Runnable() {
            @Override
            public void run() {
                // Do a task
                doTask();

                // Reschedule the Handler
                mHandler.postDelayed(mRunnable, 1000);
            }
        };

        // Do the task after specified time
        mHandler.postDelayed(mRunnable,1000);

        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        // Remove the handler callback
        mHandler.removeCallbacks(mRunnable);
    }

    // Custom method to do a task
    public void doTask(){
        // Generate a random number
        int randomNumber = mRandom.nextInt(25);

        // Display the generated random number
        Toast.makeText(this,"Random Number : " + randomNumber,Toast.LENGTH_SHORT).show();

        // If random number is equal to 5
        if(randomNumber == 5){
            // Initialize a new Intent
            Intent intent = new Intent(this, AnotherActivity.class);
            // Set the flags for the Intent
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // Start the specified Activity
            this.startActivity(intent);
        }
    }
}