Monday 6 July 2015

Android add calendar event Programatically | Android Codes: Insertion and Deletion of Calendar Events | Configure email notification with Calendar app in Android

Hello Friends,
          Today, I am sharing my another android tutorial which covers following things:

1. Android- Adding events to calendar via your android application
2. Programmatically add reminder in android calendara
3. Configure email notification with Calendar app in Android


A. For adding event on Calendar

try {
 String eventUriString = "content://com.android.calendar/events";
 ContentValues eventValues = new ContentValues();
 eventValues.put("calendar_id", 1); // id, We need to choose from
     // our mobile for primary its 1
 eventValues.put("title", title);
 eventValues.put("description", desc);
 eventValues.put("eventLocation", place);

 long endDate = startDate + 1000 * 10 * 10; // For next 10min
 eventValues.put("dtstart", startDate);
 eventValues.put("dtend", endDate);

 // values.put("allDay", 1); //If it is bithday alarm or such
 // kind (which should remind me for whole day) 0 for false, 1
 // for true
  eventValues.put("eventStatus", status); // This information is
   // sufficient for most
   // entries tentative (0),
   // confirmed (1) or canceled
   // (2):
 eventValues.put("eventTimezone", "UTC/GMT +5:30");
 /*
  * Comment below visibility and transparency column to avoid
  * java.lang.IllegalArgumentException column visibility is invalid
  * error
  */
 // eventValues.put("allDay", 1);
 // eventValues.put("visibility", 0); // visibility to default (0),
   // confidential (1), private
   // (2), or public (3):
   // eventValues.put("transparency", 0); // You can control whether
   // an event consumes time
   // opaque (0) or transparent
   // (1).
 eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

 Uri eventUri = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(Uri.parse(eventUriString), eventValues);
 eventID = Long.parseLong(eventUri.getLastPathSegment()); 
} catch (Exception ex) {
 log.error("Error in adding event on calendar" + ex.getMessage());
}


B. Set Reminder for above added event id:

if (needReminder) {
/***************** Event: Reminder(with alert) Adding reminder to event *******************/
        String reminderUriString = "content://com.android.calendar/reminders";
 ContentValues reminderValues = new ContentValues();
 reminderValues.put("event_id", eventID);
 reminderValues.put("minutes", 5); // Default value 
       //set time in min which occur before event start   
 reminderValues.put("method", 1); // Alert Methods: Default(0),
     // Alert(1), Email(2),SMS(3)
 Uri reminderUri = curActivity.getApplicationContext()
      .getContentResolver()
    .insert(Uri.parse(reminderUriString), reminderValues);
}
 

C: Send mail to user for attending the meeting added on calendar

/***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

if (needMailService) {
 String attendeuesesUriString = "content://com.android.calendar/attendees";

 /********
  * To add multiple attendees need to insert ContentValues
  * multiple times
  ***********/
 ContentValues attendeesValues = new ContentValues();
 attendeesValues.put("event_id", eventID);
 attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
 attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee email
 attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
       // Relationship_None(0),
       // Organizer(2),
       // Performer(3),
       // Speaker(4)
 attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
      // Required(2),
      // Resource(3)
 attendeesValues.put("attendeeStatus", 0); // NOne(0),
          // Accepted(1),
        // Decline(2),
        // Invited(3),
        // Tentative(4)

 Uri eventsUri = Uri.parse("content://calendar/events");
 Uri url = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(eventsUri, attendeesValues);

 // Uri attendeuesesUri = curActivity.getApplicationContext()
    // .getContentResolver()
    // .insert(Uri.parse(attendeuesesUriString), attendeesValues);
} 

D: For deletion of calendar event: Here "id" is event id.

Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(id));
getContentResolver().delete(uri, null, null); 

Finally All together: Add this method in your activity class

public long addAppointmentsToCalender(Activity curActivity, String title,
   String desc, String place, int status, long startDate,
   boolean needReminder, boolean needMailService) {
/***************** Event: add event *******************/
long eventID = -1;
try {
        String eventUriString = "content://com.android.calendar/events";
 ContentValues eventValues = new ContentValues();
 eventValues.put("calendar_id", 1); // id, We need to choose from
              // our mobile for primary its 1
 eventValues.put("title", title);
 eventValues.put("description", desc);
 eventValues.put("eventLocation", place);

 long endDate = startDate + 1000 * 10 * 10; // For next 10min
 eventValues.put("dtstart", startDate);
 eventValues.put("dtend", endDate);

 // values.put("allDay", 1); //If it is bithday alarm or such
   // kind (which should remind me for whole day) 0 for false, 1
   // for true
 eventValues.put("eventStatus", status); // This information is
   // sufficient for most
   // entries tentative (0),
   // confirmed (1) or canceled
   // (2):
 eventValues.put("eventTimezone", "UTC/GMT +5:30");
 /*
  * Comment below visibility and transparency column to avoid
  * java.lang.IllegalArgumentException column visibility is invalid
  * error
  */
 // eventValues.put("allDay", 1);
 // eventValues.put("visibility", 0); // visibility to default (0),
                                      // confidential (1), private
                                      // (2), or public (3):
 // eventValues.put("transparency", 0); // You can control whether
                                        // an event consumes time
                          // opaque (0) or transparent (1).
   
        eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

 Uri eventUri = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(Uri.parse(eventUriString), eventValues);
 eventID = Long.parseLong(eventUri.getLastPathSegment());

 if (needReminder) {
 /***************** Event: Reminder(with alert) Adding reminder to event ***********        ********/
 
        String reminderUriString = "content://com.android.calendar/reminders";
        ContentValues reminderValues = new ContentValues();
 reminderValues.put("event_id", eventID);
 reminderValues.put("minutes", 5); // Default value of the
       // system. Minutes is a integer
 reminderValues.put("method", 1); // Alert Methods: Default(0),
     // Alert(1), Email(2),SMS(3)

 Uri reminderUri = curActivity.getApplicationContext()
     .getContentResolver()
     .insert(Uri.parse(reminderUriString), reminderValues);
 }

/***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

 if (needMailService) {
 String attendeuesesUriString = "content://com.android.calendar/attendees";
 /********
  * To add multiple attendees need to insert ContentValues
  * multiple times
  ***********/
 ContentValues attendeesValues = new ContentValues();
 attendeesValues.put("event_id", eventID);
 attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
 attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee Email
 attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
       // Relationship_None(0),
       // Organizer(2),
       // Performer(3),
       // Speaker(4)
 attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
      // Required(2),
      // Resource(3)
 attendeesValues.put("attendeeStatus", 0); // NOne(0),
        // Accepted(1),
        // Decline(2),
        // Invited(3),
        // Tentative(4)

 Uri eventsUri = Uri.parse("content://calendar/events");
 Uri url = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(eventsUri, attendeesValues);

 // Uri attendeuesesUri = curActivity.getApplicationContext()
    // .getContentResolver()
    // .insert(Uri.parse(attendeuesesUriString), attendeesValues);
 }
} catch (Exception ex) {
 log.error("Error in adding event on calendar" + ex.getMessage());
}

return eventID;

}
 

Also need to add following permission in your AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />


Hope this will help some one.

Enjoy Coding :)

Tuesday 26 May 2015

Android Read Status Bar Notification | Android Read all incoming notification | Android Read Incoming Sms | Android Read Incoming Call

Hello Friends,
    Today, I am going to share a small tutorial on android "NotificationListenerService"
    which help us to read the all app notifications. This tutorial covers following
    points.

 




Feature:
1. We can easily read the notification of other android application or read all status bar
     notification,
2. Read|Listen incoming whatsapp messages
3. Read all incoming SMS
4. Read all incoming calls
5. Battery Low

Step1 : Create a Notification Service Class :
                    This class extends NotificationListenerService class which contains
                    two method:
                 a) onNotificationPosted(StatusBarNotification sbn) :
                           Implement this method to learn about new notifications as they are
                           posted by apps.
                 b) onNotificationRemoved(StatusBarNotification sbn) :
                           Implement this method to learn when notifications are removed.                         

 Note: The StatusBarNotifcation object contains extras, app package name and
            ticker name

1. NotificationService.java

package android.notifications;

import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;

import java.io.ByteArrayOutputStream;

/**
 * Created by mukesh on 19/5/15.
 */
public class NotificationService extends NotificationListenerService {

    Context context;

    @Override

    public void onCreate() {

        super.onCreate();
        context = getApplicationContext();

    }
    @Override

    public void onNotificationPosted(StatusBarNotification sbn) {
        String pack = sbn.getPackageName();
        String ticker ="";
        if(sbn.getNotification().tickerText !=null) {
            ticker = sbn.getNotification().tickerText.toString();
        }
        Bundle extras = sbn.getNotification().extras;
        String title = extras.getString("android.title");
        String text = extras.getCharSequence("android.text").toString();
        int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
        Bitmap id = sbn.getNotification().largeIcon;


        Log.i("Package",pack);
        Log.i("Ticker",ticker);
        Log.i("Title",title);
        Log.i("Text",text);

        Intent msgrcv = new Intent("Msg");
        msgrcv.putExtra("package", pack);
        msgrcv.putExtra("ticker", ticker);
        msgrcv.putExtra("title", title);
        msgrcv.putExtra("text", text);
        if(id != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            id.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            msgrcv.putExtra("icon",byteArray);
        }
        LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);


    }

    @Override

    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i("Msg","Notification Removed");

    }
}

2.MainActivity.java

package android.notifications;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import java.util.ArrayList;

/**
 * Created by mukesh on 19/5/15.
 */
public class MainActivity extends Activity {

    ListView list;
    CustomListAdapter adapter;
    ArrayList modelList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        modelList = new ArrayList();
        adapter = new CustomListAdapter(getApplicationContext(), modelList);
        list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);
        LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent(
                        "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private BroadcastReceiver onNotice= new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
           // String pack = intent.getStringExtra("package");
            String title = intent.getStringExtra("title");
            String text = intent.getStringExtra("text");
            //int id = intent.getIntExtra("icon",0);

            Context remotePackageContext = null;
            try {
//                remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
//                Drawable icon = remotePackageContext.getResources().getDrawable(id);
//                if(icon !=null) {
//                    ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
//                }
                byte[] byteArray =intent.getByteArrayExtra("icon");
                Bitmap bmp = null;
                if(byteArray !=null) {
                    bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                }
                Model model = new Model();
                model.setName(title +" " +text);
                model.setImage(bmp);

                if(modelList !=null) {
                    modelList.add(model);
                    adapter.notifyDataSetChanged();
                }else {
                    modelList = new ArrayList();
                    modelList.add(model);
                    adapter = new CustomListAdapter(getApplicationContext(), modelList);
                    list=(ListView)findViewById(R.id.list);
                    list.setAdapter(adapter);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

3. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="android.notifications">
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="android.notifications.MainActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="android.notifications.NotificationService"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SER                          VICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationLi                                  stenerService" />
            </intent-filter>
        </service>
        <receiver android:name="android.notifications.IncomingSms">
           <intent-filter>
               <action android:name="android.provider.Telephony.SMS_RECEIVED" />
           </intent-filter>
        </receiver>
        <receiver android:name=".ServiceReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>


4. Android check Notification Access Setting is enable or not:


//check notification access setting is enabled or not
public static boolean checkNotificationEnabled() {
         try{
       if(Settings.Secure.getString(MainActivity.mActivity.getContentResolver(),
                 "enabled_notification_listeners").contains(App.getContext().getPackageName())) 
      {
    return true;
      } else {
         return false;
      }

 }catch(Exception e) {
  e.printStackTrace();
 }
 return false;
}



Download Complete Code From Here NotificationListener


Hope, this will helps someone.
Enjoy Coding .... :)

Monday 9 March 2015

Android applying custom fonts

Hello Friends,
      Today, I am sharing my small blog which helps you in applying custom fonts
on android text view from xml or styles file. Its very easy and reduces the number
of java line from your code and also make the performance of your app more better.
                                     


Steps:
1.Placed all your custom fonts file inside assets folder i.e: assets/fonts/digitalism.ttf)
2.Add the path of above custom font file your string.xml file
<string name="FONT_d3_digitalism">fonts/d3-digitalism.ttf</string>
<string name="FONT_digitalism">fonts/digitalism.ttf</string>
<string name="FONT_Mohave_Bold">fonts/Mohave-Bold.ttf</string>
<string name="FONT_Roboto_Black">fonts/Roboto-Black.ttf</string>
<string name="FONT_Roboto_Bold">fonts/Roboto-Bold.ttf</string>
<string name="FONT_Roboto_Medium">fonts/Roboto-Medium.ttf</string>
<string name="FONT_RobotoCondensed_Bold">fonts/RobotoCondensed-Bold.ttf</string>

3. Declartion of style inside values/styles.xml file for eg:
        <style name="CustomDigital">
          <item name="font">@string/FONT_digitalism</item>
        </style>

4. Inside attrs.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
      <declare-styleable name="Fontify">
<attr name="font" format="string" />
      </declare-styleable>

   <!-- Allows attribute use in an AppTheme definition -->
   <declare-styleable name="FontifyTheme">
<attr name="fontifyStyle" format="reference"/>
   </declare-styleable>
</resources>
5. finally, In our layout file we have to use this :
      <com.android.developer.solutions.font.TextClock
         android:id="@+id/textClock1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignLeft="@+id/btn"
         android:layout_alignRight="@+id/btn"
         android:layout_below="@+id/btn"
         android:layout_marginTop="20dp"
         android:gravity="center"
         android:textSize="18sp"
         style="@style/CustomDigital"
         android:text="TextClock" />


For more check below link:
https://github.com/danh32/Fontify


Download Demo Code : CustomTextFont

Hope this will help some one.
Enjoy Coding :)

 

Copyright @ 2013 Android Developers Blog.