Before you can start using the In-app Billing service, you’ll need to add the library that contains the In-app Billing Version 3 API to your Android project. You also need to setting the permissions for your application to communicate with Google Play. In addition, you’ll need to establish a connection between your application and Google Play. You should also verify that the In-app Billing API version that you are using in your application is supported by Google Play.
Download the Sample Application
In this training class, you will use a reference implementation for the In-app Billing Version 3 API called the TrivialDrive sample application. The sample includes convenience classes to quickly set up the In-app Billing service, marshal and unmarshal data types, and handle In-app Billing requests from the main thread of your application.
Select Google Play Billing Library. Make sure to select the download for In-app Billing Version 3 or above.
Click Install to complete the download.
The sample files will be installed to /your/sdk/location/extras/google/play_billing/in-app-billing-v03.
Add Your Application to the Developer Console
The Google Play Developer Console is where you publish your In-app Billing application and manage the various digital goods that are available for purchase from your application. When you create a new application entry in the Developer Console, it automatically generates a public license key for your application. You will need this key to establish a trusted connection from your application to the Google Play servers. You only need to generate this key once per application, and don’t need to repeat these steps when you update the APK file for your application.
To add your application to the Developer Console:
Go to the Google Play Developer Console site and log in. You will need to register for a new developer account, if you have not registered previously. To sell in-app items, you also need to have a Google Checkout Merchantaccount.
Click on Try the new design to access the preview version of the Developer Console, if you are not already logged on to that version.
In the All Applications tab, add a new application entry.
Click Add new application.
Enter a name for your new In-app Billing application.
Click Prepare Store Listing.
In the Services & APIs tab, find and make a note of the public license key that Google Play generated for your application. This is a Base64 string that you will need to include in your application code later.
Your application should now appear in the list of applications in Developer Console.
Add the In-app Billing Library
To use the In-app Billing Version 3 features, you must add the IInAppBillingService.aidl file to your Android project. This Android Interface Definition Language (AIDL) file defines the interface to the Google Play service.
You can find the IInAppBillingService.aidl file in the provided sample app. Depending on whether you are creating a new application or modifying an existing application, follow the instructions below to add the In-app Billing Library to your project.
New Project
To add the In-app Billing Version 3 library to your new In-app Billing project:
Copy the TrivialDrive sample files into your Android project.
Modify the package name in the files you copied to use the package name for your project. In Eclipse, you can use this shortcut: right-click the package name, then select Refactor > Rename.
Open the AndroidManifest.xml file and update the package attribute value to use the package name for your project.
Fix import statements as needed so that your project compiles correctly. In Eclipse, you can use this shortcut: press Ctrl+Shift+O in each file showing errors.
Modify the sample to create your own application. Remember to copy the Base64 public license key for your application from the Developer Console over to your MainActivity.java.
Existing Project
To add the In-app Billing Version 3 library to your existing In-app Billing project:
Copy the IInAppBillingService.aidl file to your Android project.
If you are using Eclipse: Import the IInAppBillingService.aidl file into your /src directory.
If you are developing in a non-Eclipse environment: Create the following directory /src/com/android/vending/billing and copy the IInAppBillingService.aidl file into this directory.
Build your application. You should see a generated file named IInAppBillingService.java in the /gendirectory of your project.
Add the helper classes from the /util directory of the TrivialDrive sample to your project. Remember to change the package name declarations in those files accordingly so that your project compiles correctly.
Your project should now contain the In-app Billing Version 3 library.
Set the Billing Permission
Your app needs to have permission to communicate request and response messages to the Google Play’s billing service. To give your app the necessary permission, add this line in your AndroidManifest.xml manifest file:
You must bind your Activity to Google Play’s In-app Billing service to send In-app Billing requests to Google Play from your application. The convenience classes provided in the sample handles the binding to the In-app Billing service, so you don’t have to manage the network connection directly.
To set up synchronous communication with Google Play, create an IabHelper instance in your activity’s onCreate method. In the constructor, pass in the Context for the activity, along with a string containing the public license key that was generated earlier by the Google Play Developer Console.
Security Recommendation: It is highly recommended that you do not hard-code the exact public license key string value as provided by Google Play. Instead, you can construct the whole public license key string at runtime from substrings, or retrieve it from an encrypted store, before passing it to the constructor. This approach makes it more difficult for malicious third-parties to modify the public license key string in your APK file.
IabHelper mHelper;@Overridepublicvoid onCreate(Bundle savedInstanceState){// ...String base64EncodedPublicKey;// compute your public key and store it in base64EncodedPublicKey
mHelper =newIabHelper(this, base64EncodedPublicKey);}
Next, perform the service binding by calling the startSetup method on the IabHelper instance that you created. Pass the method an OnIabSetupFinishedListener instance, which is called once the IabHelpercompletes the asynchronous setup operation. As part of the setup process, the IabHelper also checks if the In-app Billing Version 3 API is supported by Google Play. If the API version is not supported, or if an error occured while establishing the service binding, the listener is notified and passed an IabResult object with the error message.
mHelper.startSetup(newIabHelper.OnIabSetupFinishedListener(){publicvoid onIabSetupFinished(IabResult result){if(!result.isSuccess()){// Oh noes, there was a problem.Log.d(TAG,"Problem setting up In-app Billing: "+ result);}// Hooray, IAB is fully set up! }});
If the setup completed successfully, you can now use the mHelper reference to communicate with the Google Play service. When your application is launched, it is a good practice to query Google Play to find out what in-app items are owned by a user. This is covered further in the Query Purchased Items section.
Important: Remember to unbind from the In-app Billing service when you are done with your activity. If you don’t unbind, the open service connection could cause your device’s performance to degrade. To unbind and free your system resources, call the IabHelper‘s dispose method when your Activity gets destroyed.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting button click
findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Creating an intent for sending to service
Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
intent.putExtra("id", 101);
intent.putExtra("msg", "hi");
//starting service
startService(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
//register broadcast receiver for the intent MyTaskStatus
LocalBroadcastManager.getInstance(this).registerReceiver(MyReceiver, new IntentFilter("MyServiceStatus"));
}
//Defining broadcast receiver
private BroadcastReceiver MyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("serviceMessage");
Toast.makeText(MainActivity.this, "Received : " + message, Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onStop()
{
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(MyReceiver);
}
}
MyIntentService.java
public class MyIntentService extends IntentService {
public MyIntentService() {
super(MyIntentService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent) {
//retrieving data from the received intent
int id = intent.getIntExtra("id",0);
String message = intent.getStringExtra("msg");
Log.i("Data ", "id : "+id+" message : "+ message );
//-----------------------------------------------
//Do your long running task here
//------------------------------------------------
//Broadcasting some data
Intent myIntent = new Intent("MyServiceStatus");
myIntent.putExtra("serviceMessage", "Task done");
// Send broadcast
LocalBroadcastManager.getInstance(this).sendBroadcast(myIntent);
}
}
1.First Create Interface an Always remember that Interface is Always public.
public interface MyInterface
{
public void value(String abc);
}
2.then use that interface where you want to use.
String nameValues="Ganesh Divekar";
MyInterface myInterface = (MyInterface)context;
myInterface .value(nameValues);
3.then we need to implement we created Interface where you want to needed.
implements MyInterface;
@Override
public void value(String abc) {
NameValue.setText(abc);
}
Kotlin is a great fit for developing Android applications, bringing all of the advantages of a modern language to the Android platform without introducing any new restrictions:
Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues. The Kotlin tooling is fully supported in Android Studio and compatible with the Android build system.
Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure. With Kotlin’s support for inline functions, code using lambdas often runs even faster than the same code written in Java.
Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application. This includes annotation processing, so databinding and Dagger work too.
Footprint: Kotlin has a very compact runtime library, which can be further reduced through the use of ProGuard. In a real Application, the Kotlin runtime adds only a few hundred methods and less than 100K to the size of the .apk file.
Compilation Time: Kotlin supports efficient incremental compilation, so while there’s some additional overhead for clean builds, Faster Than Java.
Learning Curve: For a Java developer, getting started with Kotlin is very easy. The automated Java to Kotlin converter included in the Kotlin plugin helps with the first steps. Kotlin koans offer a guide through the key features of the language with a series of interactive exercises.
From Java To Kotlin
Java
System.out.print("Ganesh Divekar");
Kotlin
print("Ganesh Divekar")
Java
String name ="Ganesh Divekar";
Kotlin
varname="Ganesh Divekar"
Java
String otherName;
otherName =null;
Kotlin
varotherName:String?
otherName =null
Java
if(text !=null){
int length = text.length();
}
Kotlin
text?.let {
vallength= text.length
}
Java
String firstName ="Ganesh";
String lastName ="Divekar";
String message ="My name is: "+ firstName +""+ lastName;
Kotlin
valfirstName="Ganesh"vallastName="Divekar"valmessage="My name is: $firstName$lastName"
Java
String text ="First Line\n"+"Second Line\n"+"Third Line";
Kotlin
valtext=""" |First Line |Second Line |Third Line""".trimMargin()
Java
String text = x >5?"x > 5":"x <= 5";
Kotlin
valtext=if (x >5)
"x > 5"else"x <= 5"
Java
if(object instanceofCar){
}
Car car = (Car) object;
Kotlin
if (object is Car) {
}
varcar= object asCar
Java
if(object instanceofCar){
Car car = (Car) object;
}
Kotlin
if (object is Car) {
varcar= object // smartcasting
}
varscore=// some scorevargrade=when (score) {
9, 10->"Excellent"in6..8->"Good"4, 5->"Ok"in1..3->"Fail"else->"Fail"
}
Java
for (int i =1; i <=10 ; i++) { }
for (int i =1; i <10 ; i++) { }
for (int i =10; i >=0 ; i--) { }
for (int i =1; i <=10 ; i+=2) { }
for (int i =10; i >=0 ; i-=2) { }
for (String item : collection) { }
for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
for (i in1..10) { }
for (i in1 until 10) { }
for (i in10 downTo 0) { }
for (i in1..10 step 2) {}
for (i in10 downTo 1 step 2) {}
for (item in collection) {}
for ((key, value) in map) {}
void doSomething(int... numbers) {
// logic here
}
Kotlin
fundoSomething(varargnumbers:Int) {
// logic here
}
Java
int getScore() {
// logic herereturn score;
}
Kotlin
fungetScore():Int {
// logic herereturn score
}
// as a single-expression functionfungetScore():Int= score
Java
int getScore(int value) {
// logic herereturn2* value;
}
Kotlin
fungetScore(value:Int):Int {
// logic herereturn2* value
}
// as a single-expression functionfungetScore(value:Int):Int=2* value
Java
publicclassUtils {
privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticintgetScore(intvalue) {
return2* value;
}
}
Kotlin
class Utilsprivateconstructor() {
companion object {
fungetScore(value:Int):Int {
return2* value
}
}
}
// other way is also there
object Utils {
fungetScore(value:Int):Int {
return2* value
}
}
Java
publicclassDeveloper {
privateString name;
privateint age;
publicDeveloper(Stringname, intage) {
this.name = name;
this.age = age;
}
publicStringgetName() {
return name;
}
publicvoidsetName(Stringname) {
this.name = name;
}
publicintgetAge() {
return age;
}
publicvoidsetAge(intage) {
this.age = age;
}
@Overridepublicbooleanequals(Objecto) {
if (this== o) returntrue;
if (o ==null|| getClass() != o.getClass()) returnfalse;
Developer developer = (Developer) o;
if (age != developer.age) returnfalse;
return name !=null? name.equals(developer.name) : developer.name ==null;
}
@OverridepublicinthashCode() {
int result = name !=null? name.hashCode() :0;
result =31* result + age;
return result;
}
@OverridepublicStringtoString() {
return"Developer{"+"name='"+ name +'\''+", age="+ age +'}';
}
}
Kotlin
data class Developer(varname:String, varage:Int)
Java
publicclassUtils {
privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticinttriple(intvalue) {
return3* value;
}
}
int result =Utils.triple(3);
Kotlin
fun Int.triple():Int {
returnthis*3
}
varresult=3.triple()
Installing the Kotlin Plugin in Android Studio
The very first thing you need to do is add Kotlin support to your Android Studio installation.
Before we get started, make sure you’re running the most recent, stable version of Android Studio, as you’re more likely to encounter bugs with the Kotlin plugin on experimental versions of Android Studio. It’s also worth opening the SDK Manager and checking whether updates are available for any of the packages you’ve installed.
Once you’re confident that your development environment is up to date, you’re ready to install the Kotlin plugin. Launch Android Studio and you should see the Welcome to Android Studio window—if this window doesn’t appear, then close Android Studio completely and relaunch it.
Give the Configure icon a click, and then select Plugins from the subsequent dropdown.
Click the Install JetBrains plugins… button.
Select Kotlin from the menu, and then click the green Install button. You’ll need to restart your IDE before the Kotlin plugin becomes active, so either click the Restart Android Studio button that appears or restart your IDE manually.
Configuring Your Project to Use Kotlin
At this point, your IDE can understand and run Kotlin code, but you’ll still need to configure Kotlin every time you want to use it in a new project. Let’s create a new project and configure that project to use Kotlin now. Create a new project with the settings of your choice, but for the sake of simplicity, select Empty Activity when prompted.
Thanks to the Kotlin plugin, configuring a project to use Kotlin couldn’t be simpler: just select Tools from the Android Studio toolbar, followed by Kotlin and Configure Kotlin in Project.
This opens a popup where you can choose to configure Kotlin for:
all modules
all modules containing Kotlin files
or a single, named module
Since I’m only going to use Kotlin code in my project, I opted for All modules. You can also choose which version of Kotlin you want to use—typically, this will be the latest version.
Alternatively, you can configure Kotlin by selecting Help from the Android Studio menu bar, followed by Find Action… In the Find Action bar, start typing Configure Kotlin in Project, and then select this option when it appears.
The Configure Kotlin in Project option makes a number of tweaks to your project’s build.gradle files, so let’s take a closer look at how these files have changed. Open your project-level build.gradle file—it should look something like this:
buildscript {
//Declares the version of Kotlin that you’re using. You’ll notice that the version of Kotlin is mentioned in both the buildscript classpath and in your project’s compile dependencies - the version number must be the same in both places//
ext.kotlin_version = '1.0.5-2'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
//Declares the Kotlin Gradle plugin as a classpath dependency//
//Although Gradle will compile any Kotlin files it finds in src/main/java, it’s good practice to store your Kotlin files in a dedicated Kotlin directory. Here, you can see that the Kotlin plugin has added a src/main/kotlin declaration to build.gradle, but note that it hasn’t actually created this directory, so we’ll create it ourselves later in this article//
Finally, sync your changes either by clicking Sync Now from the popup that appears or by clicking the Sync Project with Gradle Files icon in Android Studio’s toolbar.
Convert Any Java File to Kotlin
One feature of the Kotlin plugin that’s particularly useful for Kotlin newcomers is its ability to convert any Java source file to Kotlin, while maintaining full runtime compatibility.
Being able to see exactly how any Java file would translate into Kotlin is ideal for helping you learn the language, but it can also come in useful throughout your Kotlin journey—if you’re ever struggling to work out how to write something in Kotlin, you can always write it in Java and then use this feature to convert that code into Kotlin.
Let’s convert our project’s MainActivity file into a Kotlin source file. There are two ways of invoking the Kotlin plugin’s Convert Java File to Kotlin File action, so either:
Select your MainActivity file, and then select Code from Android Studio’s menu bar, followed by Convert Java File to Kotlin File.
Or select Help from the Android Studio menu bar, followed by Find Action. In the subsequent popup, start typing Convert Java file to Kotlin file and then select this option when it appears. Note, you can also launch the Find Action popup with a keyboard shortcut: if you’re on a Mac, press the Command-Shift-A keys, and if you’re on Windows or Linux then press Control-Shift-A.
Just be aware that, depending on the complexity of your code, the conversion may not always be 100% accurate, so you should always check your converted code for errors.
Your newly-converted MainActivity should look something like this:
importandroid.support.v7.app.AppCompatActivity
importandroid.os.Bundle
classMainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
You’ll also notice that the file’s extension has changed, transforming from MainActivity.java to MainActivity.kt.
This may be a simple Activity, but these few lines illustrate some key characteristics of the Kotlin syntax. Since this is our first look at some actual Kotlin code, let’s pick this class apart line by line.
Understanding Kotlin Syntax
In Kotlin, you declare classes using the keyword class, exactly like in Java. However, in Kotlin, classes (and methods) are public and final by default, so you can create a class simply by writing class MainActivity.
When it comes to extending a class, you replace Java’s extends with a colon, and then attach the name of the parent class. So in the first line of our MainActivity.kt file, we’re creating a public, final class called MainActivity that extends AppCompatActivity:
If you do want to override a class or method, then you’ll need to explicitly declare it as open or abstract.
In Kotlin, functions are defined using the fun keyword, followed by the function name and the parameters in brackets. In Kotlin, the function’s name comes before its type:
override fun onCreate(savedInstanceState: Bundle?) {
This is the opposite of Java, where type comes before name:
publicvoidonCreate(Bundle savedInstanceState)
Note that we’re not specifying that this method is final, as in Kotlin all methods are final by default.
The rest of this Activity looks pretty similar to Java. However, these few lines do illustrate another key characteristic of Kotlin:
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
In Kotlin you don’t need to finish your lines with semicolons, hence the absence of colons in the above snippet. You can add colons if you really want to, but your code will be cleaner and easier to read without them.
Now that we’ve deciphered our MainActivity.kt file, let’s move it to its proper home. Since the Kotlin plugin went to the trouble of adding a src/main/kotlin declaration to our build.gradle file, let’s actually create this directory. This step isn’t mandatory, but keeping your Kotlin files in a dedicated directory will make for a much cleaner project.
In Android Studio’s Project Explorer, Control-click your project’s Main directory and select New from the menu that appears, followed by Directory. Name this directory kotlin and then click OK.
If you’re struggling to spot your project’s main directory, then open the little dropdown in the upper-left of the Project Explorer and select Project. You should now have no problems spotting that elusive src/main directory.
Once you’ve created a dedicated Kotlin directory, drag your MainActivity.kt file into it. Just be sure to retain your MainActivity.kt file’s existing package name so that your project still runs.
Also, if you’re only going to use Kotlin in this project, then you may want to delete the Java directory, rather than cluttering up your project with empty and unnecessary directories.
Since Kotlin compiles to bytecode, an application that’s written in Kotlin feels exactly the same as an application that’s written in Java, so try installing this app on your Android device or a compatible AVD—it should feel as if nothing has changed.
Creating Extra Kotlin Files
If you continue working with Kotlin in your project, then sooner or later you’re going to need to start creating new Kotlin files rather than simply converting existing Java ones.
To create a Kotlin file, Control-click your app/src/main/kotlin directory and select New > Kotlin Activity.
Give your class a name and select class from the dropdown menu. Your new class should look something like this:
classSecondActivity
{
}
At this point, your Activity is empty. To get to the point where you can start adding some real functionality, you’ll need to complete a few steps. Firstly, add the import statements you want to use. The only difference between import statements in Kotlin and import statements in Java is that you don’t need to finish each line with a semicolon. For example:
importandroid.app.Activity
importandroid.os.Bundle
importandroid.app.Activity
You’ll then need to specify the class you’re extending, using the same format we saw in our MainActivity.kt file:
classSecondActivity : Activity() {
}
Next, you need to override the Activity’s onCreate method:
You can now add whatever functionality you want to this Activity (and in the next section, I’ll show you how to use Kotlin extensions to manipulate UI widgets, so this may be a good place to start), but one last bit of setup you need to complete is declaring your Kotlin Activity in your Manifest. This follows exactly the same formula as declaring a new Java Activity, for example:
<activity
android:name=".SecondActivity"
android:label="@string/second"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
Kotlin Android Extensions: Wave Goodbye to findViewById
Now that we’ve mastered the basics, let’s take a closer look at what Kotlin is really capable of—starting with a feature that can really cut the amount of boilerplate code you need to write.
In Android, every time you want to work with any View in an Activity, you need to use the findViewByIdmethod to obtain a reference to that View. This makes findViewById one of the most important, but also one of the most frustrating bits of code that you’ll find yourself writing over and over, and over again in your Android projects. The findViewById method is a huge source of potential bugs, and if you’re working with multiple UI elements in the same Activity, then all those findViewByIds can really clutter up your code, making it difficult to read.
While there are a number of libraries, such as Butter Knife, that aim to remove the need for findViewByIds, these libraries still require you to annotate the fields for each View, which can lead to mistakes and still feels like a lot of effort that would be better invested in other areas of your project.
The Kotlin Android Extensions plugin (which has recently been incorporated into the standard Kotlin plugin) promises to make findViewById a thing of the past, offering you the benefits of the aforementioned libraries without the drawback of having to write any additional code or ship an additional runtime.
You can use Kotlin extensions to import View references into your source files. At this point the Kotlin plugin will create a set of “synthetic properties” that enable you to work with these views as though they were part of your activity—crucially, this means you no longer have to use findViewById to locate each Viewbefore you can work with it.
To use extensions, you’ll need to enable the Kotlin Android Extensions plugin in each module, so open your module-level build.gradle file and add the following:
apply plugin: 'kotlin-android-extensions'
Sync these changes by clicking the Sync Now popup.
You can then import the references to a single View, using the following format:
For example, if your acitivity_main.xml file contained a TextView with the ID textView1, then you’d import the reference to this view by adding the following to your Activity:
You’d then be able to access textView1 within this activity using its ID alone—and without a findViewById in sight!
Let’s take a look at extensions in action, by adding a TextView to our activity_main.xml file, importing it into our MainActivity.ktfile, and using extensions to set the TextView’s text programmatically.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myTextView.setText("Hello World")
}
}
Note, if you want to work with multiple widgets from the same layout file, then you can import the entire contents of a layout file in one fell swoop, using the following formula:
importkotlinx.android.synthetic.main.<layout>.*
For example, if you wanted to import all the widgets from your activity_main.xml file, then you’d add the following to your Activity:
The first thing that needs to be done is to create a string called BROADCAST_ACTION, this is simply a string that identifies what kind of action is taking place. Most of the time, it’s common to use the package name with the kind of action added to the end, so we’ll do that here. The next step is to create a handler that will be used to broadcast our data every 5 seconds. It’s better to use a Timer instead of Handler.
In onCreate, I’ve created a Intent and passed the BROADCAST_ACTION to the constructor of the intent. Notice that the Intent was defined as a global variable above. The intent will be called repeatedly in the Timer below and there is no reason to create a new intent every 5 seconds, so I’ll create it once here.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView)findViewById(R.id.textview);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
//Start our own service
Intent intent = new Intent(MainActivity.this,
com.apps.broadcastrapp.MyService.class);
startService(intent);
super.onStart();
}
/*@Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}*/
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int datapassed = intent.getIntExtra("DATAPASSED", 0);
String s = intent.getAction().toString();
String s1 = intent.getStringExtra("DATAPASSED");
textview.setText(s1);
Toast.makeText(context,
"Triggered by Service!\n"
+ "Data passed: " + String.valueOf(s1),
Toast.LENGTH_LONG).show();
}
};
}
MyService.java class
public class MyService extends Service {
final static String MY_ACTION = "MY_ACTION";
private static Context context;
private Timer timer;
public String Data;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
MyThread myThread = new MyThread();
myThread.start();
return super.onStartCommand(intent, flags, startId);
}
public class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
try {
int delay = 1000; // delay for 1 sec.
int period = 12 * 1000; // repeat every 120 sec.
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Calendar c = Calendar.getInstance();
Data = String.valueOf((c.get(Calendar.MILLISECOND)));
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED", Data);
sendBroadcast(intent);
}
}, delay, period);
} catch (Exception ex) {
ex.printStackTrace();
}
stopSelf();
}
}
}