Type safe intent building for services and activities

Overview

#IntentBuilder Type safe intent building for services and activities.

IntentBuilder is a type safe way of creating intents and populating them with extras. Intents were created to be very dynamic but often times the dynamic nature of intents is not needed and just gets in the way of writing safe code.

##Installation

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    }
}

apply plugin: 'com.neenbedankt.android-apt'

dependencies {
    compile 'se.emilsjolander:intentbuilder-api:0.14.0'
    apt 'se.emilsjolander:intentbuilder-compiler:0.14.0'
}

##Usage Annotate your activities and services with an @IntentBuilder annotation so that they are picked up by the library. For every class with an @IntentBuilder annotation a class named MyActivityIntentBuilder will be generated (Replace 'MyActivity' in the class name whith whatever the name of your Activity or Service class is). If your activity or service takes in parameters via extras in the intent you can now mark field with the @Extra annotation and they can be injected with the static inject method on the generated intent builder class. Extras can be marked as optional with the @Nullable annotation.

Sample activity using IntentBuilder:

@IntentBuilder
class DetailActivity extends Activity {
	
	@Extra
	String id;

	@Extra @Nullable
	String title;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DetailActivityIntentBuilder.inject(getIntent(), this);
		// TODO use id and title
	}

startActivity(new DetailActivityIntentBuilder("12345")
	.title("MyTitle")
	.build(context))
}

Sample service using IntentBuilder:

@IntentBuilder
class DownloadService extends IntentService {

    @Extra
    String downloadUrl;
	
	@Override
    protected void onHandleIntent(Intent intent) {
        MyServiceIntentBuilder.inject(intent, this);
    }

}

startService(new DownloadServiceIntentBuilder("http://google.com").build(context))

##Contributing Contributions are very welcome! Both bug fixes and additional features if they make sense. Open a pull request to discuss any changes :)

Comments
  • Dynamic BroadcastReceiver Intent Accommodation

    Dynamic BroadcastReceiver Intent Accommodation

    I was able to get static(Manifest.xml) broadcast receivers to work with IntentBuilder, but not with dynamic

    registerReceiver(new MyReceiver(), new IntentFilter(MyReceiver.ACTION));
    Intent intent = new MyReceiverIntentBuilder().build(this).setAction(MyReceiver.ACTION);
    sendBroadcast(intent);
    

    Could IntentBuilder be modified to accommodate for BroadcastReceivers too?

    opened by ersin-ertan 1
  • Update sample project

    Update sample project

    Thank you for a good library. I slightly updated the sample project.

    Add DetailActivity's declaration

    I got an error when I tried to launch DetailActivity.

    06-29 20:07:37.018    9821-9821/se.emilsjolander.intentbuilder.sample E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: se.emilsjolander.intentbuilder.sample, PID: 9821
        android.content.ActivityNotFoundException: Unable to find explicit activity class {se.emilsjolander.intentbuilder.sample/se.emilsjolander.intentbuilder.sample.DetailActivity}; have you declared this activity in your AndroidManifest.xml?
                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1761)
                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
                at android.app.Activity.startActivityForResult(Activity.java:3736)
                at android.app.Activity.startActivityForResult(Activity.java:3697)
                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:820)
                at android.app.Activity.startActivity(Activity.java:4007)
                at android.app.Activity.startActivity(Activity.java:3975)
                at se.emilsjolander.intentbuilder.sample.MainActivity$1.onClick(MainActivity.java:23)
    

    I added declaration to the manifest file.

    Set extra values corresponding to views

    I succeeded to launch DetailActivity but I couldn't see any views.

    It seems that all extra values are set to (TextView)findViewById(R.id.one). So I set values corresponding to views.

    opened by rejasupotaro 1
  • NullPointerException when only optional extras

    NullPointerException when only optional extras

    Given the following activity:

    @IntentBuilder
    public class ActivityMain extends Activity {
    
        @Extra
        @Optional
        public String title;
    
    }
    

    It generates the following builder:

    public final class ActivityMainIntentBuilder {
      private String title;
    
      public ActivityMainIntentBuilder() {
      }
    
      public ActivityMainIntentBuilder title(String title) {
        this.title = title;
        return this;
      }
    
      public Intent build(Context context) {
        Intent intent = new Intent(context, ActivityMain.class);
        intent.putExtra("title", title);
        return intent;
      }
    
      public static void inject(Intent intent, ActivityMain activity) {
        Bundle extras = intent.getExtras();
        activity.title = (String) extras.get("title");
      }
    }
    

    But, when calling the method ActivityMainIntentBuilder.inject(getIntent(), this);, the application crashes on the extras.get("title") instruction because of extras nullity in the inject method.

    opened by RoRoche 1
  • Intents are missing Context and target class

    Intents are missing Context and target class

    Hi there!

    I was just going to give your library a try, but soon realized that all of the generated classes are incomplete which unfortunately makes this library unusable. Basically, the processor does not set the target class to the Intent which is obviously required for it to work. Also, it is missing a Context reference.

    Here's the exception:

    android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }

    And here's an example of a generated build() method using the no-arg Intent constructor:

    public Intent build() {
      Intent intent = new Intent();
      intent.putExtra("userName", userName);
      return intent;
    }
    

    You can obviously work around this issue by calling [setClass(Context, Class)](http://developer.android.com/reference/android/content/Intent.html#setClass%28android.content.Context, java.lang.Class<?>%29) on the generated Intent before using it, but that kind of misses the whole point of this library in my opinion.

    I might be able to send a pull request later this weekend if I don't get tied up.

    opened by jenzz 1
  • Inheritance between components

    Inheritance between components

    Considering 2 activities like:

    @IntentBuilder
    public class MainActivity extends AppCompatActivity {
    
        @Extra
        String id;
    
        @Extra
        @Optional
        String title;
    
        // ...
    }
    

    and:

    @IntentBuilder
    public class SubActivity extends MainActivity {
        @Extra
        String downloadUrl;
    
        // ...
    }
    

    I get the following Builder:

    public final class SubActivityIntentBuilder {
      private final String downloadUrl;
    
      public SubActivityIntentBuilder(String downloadUrl) {
        this.downloadUrl = downloadUrl;
      }
    
      public Intent build() {
        Intent intent = new Intent();
        intent.putExtra("downloadUrl", downloadUrl);
        return intent;
      }
    
      public static void inject(Intent intent, SubActivity activity) {
        Bundle extras = intent.getExtras();
        activity.downloadUrl = (String) extras.get("downloadUrl");
      }
    }
    

    Is it possible to add the support of inherited fields? So that the SubActivityIntentBuilder allows developer to manage the inherited fields id and title from MainActivity.

    opened by RoRoche 1
  • Non Nullable Primitives are Nulled

    Non Nullable Primitives are Nulled

    boolean use case, excerpt from the generated code. Don't know if this is an issue or intended, but the work-around is to use wrapper classes ex.Boolean.

    public static void inject(Intent intent, MainActivity activity) {
        Bundle extras = intent.getExtras();
        if (extras.containsKey("isTablet")) {
          activity.isTablet = (boolean) extras.get("isTablet");
        } else{
          activity.isTablet = null;
        }
    
    opened by ersin-ertan 0
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 0
  • Failed to generate code after adding this libraries into project

    Failed to generate code after adding this libraries into project

        compile 'com.github.VictorAlbertos:ReactiveCache:0.0.6'
        compile 'com.github.VictorAlbertos.Jolyglot:gson:0.0.3'
    

    symbol class not found MyActivityIntentBuilder

    opened by lectricas 0
  • Add check != null to intent

    Add check != null to intent

    Add check != null to intent , because if MainActivity is running in first time => Nullpointer exception

     public static void inject(Intent intent, MainActivity activity) {
        if (intent == null) return; // <---- add this line
        Bundle extras = intent.getExtras();
        if (extras.containsKey("mAppreciateSubmitted")) {
          activity.mAppreciateSubmitted = (Boolean) extras.get("mAppreciateSubmitted");
        } else {
          activity.mAppreciateSubmitted = null;
        }
      }
    
    
    opened by Kolyall 3
  • Remove allowBackup attribute

    Remove allowBackup attribute

    To fix below error:

    Error:Execution failed for task ':app:processDebugManifest'.
    > Manifest merger failed : Attribute application@allowBackup value=(false) from AndroidManifest.xml:9:9-36
        is also present at [se.emilsjolander:intentbuilder-api:0.14.0] AndroidManifest.xml:9:18-44 value=(true).
        Suggestion: add 'tools:replace="android:allowBackup"' to <application> element at AndroidManifest.xml:7:5-29:19 to override.
    
    opened by ypresto 0
  • Ability to set intent special options (action, flags) in builder and defaults of these values

    Ability to set intent special options (action, flags) in builder and defaults of these values

    With the builder style creation of intent there is consistency. Problem is when you want do specify intent flags and actions you can no longer only builder but manual change of final intent in another static helper method.

    Default values for intent flags, actions etc. in @IntentBuilder anotation would be great. Also ability to set this in builder like in: https://github.com/robertoestivill/intentbuilder

    opened by micutad 0
  • Generate static getters for obtaining extras without injection

    Generate static getters for obtaining extras without injection

    Injection is somewhat indirect way of getting extras. It is not always convenient / necessary especially if only one parameter is being passed to Activity or Service. Static accessors generated for each extra argument could be useful in aforementioned use cases.

    opened by vtsaplin 1
Owner
Emil Sjölander
Emil Sjölander
A set of helper classes for using dagger 1 with Android components such as Applications, Activities, Fragments, BroadcastReceivers, and Services.

##fb-android-dagger A set of helper classes for using dagger with Android components such as Applications, Activities, Fragments, BroadcastReceivers,

Andy Dennie 283 Nov 11, 2022
A small library which will save you from writing the same intent creation code again and again for the most simple tasks

Android Intents A small library which will save you from writing the same intent creation code again and again for the most simple tasks. I found myse

MarvinLabs 420 Nov 20, 2022
🎁 Android Intent & Bundle extensions that insert and retrieve values elegantly.

?? Android Intent & Bundle extensions that insert and retrieve values elegantly.

Jaewoong Eum 233 Dec 13, 2022
Criminal-Intent - An android app used to record office crimes

What is Criminal Intent? CriminalIntent records the details of “office crimes” –

Mohammad Rashid 1 Feb 11, 2022
XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them.

XClipper XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them ❤️

Kaustubh Patange 134 Dec 31, 2022
A simple Android utils library to write any type of data into cache files and read them later.

CacheUtilsLibrary This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize

Wesley Lin 134 Nov 25, 2022
CreditCardHelper 🖊️ A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations

CreditCardHelper ??️ A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations

Stelios Papamichail 18 Dec 19, 2022
compaKTset is a small library aimed at providing you with the most memory efficient Set implementation for any particular data type of your choosing.

compaKTset is a small library aimed at providing you with the most memory efficient Set implementation for any particular data type of your choosing.

Ignat Beresnev 3 Nov 16, 2021
Utility library that utilizes KSP to generate Room type converter classes.

Roomie Roomie is an annotation processing library that utilizes KSP to geaRoomie is an annotation processing library that utilizes KSP to generate TypeConverter classes for Room. TypeConverter classes most often involve same boiler-plate code and Roomie makes it really easy to quickly create them with a single annotation.nerate TypeConverter classes for Room. TypeConverter classes most often invol

Chukwuka Eze 12 Aug 26, 2022
Validator - Notify type based validation for input fields.

Validator - Notify type based validation for input fields.

Mustafa Yiğit 57 Dec 8, 2022
gRPC and protocol buffers for Android, Kotlin, and Java.

Wire “A man got to have a code!” - Omar Little See the project website for documentation and APIs. As our teams and programs grow, the variety and vol

Square 3.9k Dec 31, 2022
General purpose utilities and hash functions for Android and Java (aka java-common)

Essentials Essentials are a collection of general-purpose classes we found useful in many occasions. Beats standard Java API performance, e.g. LongHas

Markus Junginger 1.4k Dec 29, 2022
Access and process various types of personal data in Android with a set of easy, uniform, and privacy-friendly APIs.

PrivacyStreams PrivacyStreams is an Android library for easy and privacy-friendly personal data access and processing. It offers a functional programm

null 269 Dec 1, 2022
A simple and easy to use stopwatch and timer library for android

TimeIt Now with Timer support! A simple and easy to use stopwatch and timer library for android Introduction A stopwatch can be a very important widge

Yashovardhan Dhanania 35 Dec 10, 2022
Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platform the code is running.

Trail Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platfor

Mauricio Togneri 13 Aug 29, 2022
General purpose utilities and hash functions for Android and Java (aka java-common)

Essentials Essentials are a collection of general-purpose classes we found useful in many occasions. Beats standard Java API performance, e.g. LongHas

Markus Junginger 1.4k Dec 29, 2022
Matches incoming and/or outgoing text messages against set rules and sends them over to webhook.

Textmatic If you ever wanted a tool to simply push the SMS (or text messages) from your phone to somewhere remote, this is it. This app matches all in

Float 2 Jan 7, 2022
Command framework built around Kord, built to be robust and scalable, following Kord's convention and design patterns.

Command framework built around Kord, built to be robust and scalable, following Kord's convention and design patterns.

ZeroTwo Bot 4 Jun 15, 2022
DiskCache - Simple and readable disk cache for kotlin and android applications

DiskCache Simple and readable disk cache for kotlin and android applications (with journaled lru strategy) This is a simple lru disk cache, based on t

Giovanni Corte 14 Dec 2, 2022