Thursday, 6 June 2013

Android Alarm Manager to Start Service every hour

 Start Service every hour


     Hi Guys  Today we will create a service which will start after every hour ,
So we can use such service to fetch  or updated data from web to our app.

Here is simple example.


Service Started

Service Running Background



Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name and other things.

Create simple Layout 
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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/stopBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="155dp"
        android:text="Stop" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/stopBtn"
        android:layout_alignLeft="@+id/stopBtn"
        android:layout_marginBottom="41dp"
        android:text="start" />

</RelativeLayout>


In MainActivity.java  copy Paste  following  code 


public class MainActivity extends Activity {

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

              // Start service using AlarmManager

              Calendar cal = Calendar.getInstance();
              cal.add(Calendar.SECOND, 10);
             
              Intent intent = new Intent(this, TestService.class);
      
              PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
             
              AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
              //for 30 mint 60*60*1000
              alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                           60*60*1000, pintent);

              Button startBtn = (Button) findViewById(R.id.startBtn);
              startBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           startService(new Intent(getBaseContext(), TestService.class));
                     }
              });

              Button stopBtn = (Button) findViewById(R.id.stopBtn);
              stopBtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           stopService(new Intent(getBaseContext(), TestService.class));
                     }
              });

       }


}


and here is your Service code 

TestService.java




public class TestService extends Service {

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

       @Override
       public void onCreate() {
              // TODO Auto-generated method stub

              Toast.makeText(getApplicationContext(), "Service Created", 1).show();
              super.onCreate();
       }

       @Override
       public void onDestroy() {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
              super.onDestroy();
       }

       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
              // TODO Auto-generated method stub
              Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
              return super.onStartCommand(intent, flags, startId);
       }


}


one more thing to be done is that you will have to declare the service in the manifest to make it functional.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarmservice.MainActivity"
            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="com.example.alarmservice.TestService"            android:enabled="true"            android:exported="true" >        </service>

    </application>

</manifest>

you can download complete example here, 


Happy Codding :)





Include tag in android



      Hi guys Today we will see include tag of android xml

This is one of the best thing that we can reuse existing xml file in other xml.
so here is good example,

home_page.xml

just create xml as bleow Assume that this top_layout.xml  is a  top bar of each page of app. 

top_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/genericbar_background_tile" >

    <Button
        android:id="@+id/BackBtn"
        style="@style/K_style"
        android:layout_alignParentLeft="true"
        android:text="@string/backBtn" />

    <Button
        android:id="@+id/HomeBtn"
        style="@style/K_style"
        android:layout_alignParentRight="true"
        android:text="@string/HomeStr" />

    <TextView
        android:id="@+id/titleTv"
        style="@style/K_style"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/titleStr"
        android:textAppearance="?android:attr/textAppearanceMedium" />


</RelativeLayout>





To include this layout in our hompage or any page just add the
    <include layout="@layout/ layoutname"/>



home_page.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <include layout="@layout/top_lyaout"/>
  
    <LinearLayout
        android:id="@+id/TopLNLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/MidleLNLaoyout"
        android:layout_centerHorizontal="true" >

        <Button
            android:id="@+id/TopleftBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/TopRightBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/MidleLNLaoyout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >

        <Button
            android:id="@+id/MidleftBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/MidRightBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/BottonLNLaout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/MidleLNLaoyout"
        android:layout_centerHorizontal="true" >

        <Button
            android:id="@+id/BottomLeftBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/BottomRightBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>


</RelativeLayout>

So final screen will be look like this as top_Layout.xml included in home-page xml. 
this can be reuse in any number of screens.

                               


I hope It might be help full,
Happy Codding :)

Saturday, 16 March 2013

Push Message To Inbox


      Today we are developing Simple "Message Push App" that push messages from your app to default Messaging App of Android.

 In one of my project I found I situation where I am taking some message from my  Web service and I need to put this message into Original Messaging App of Android to provide  naturality in Message  and All other Task related to Messaging Such as Read message Status,Unread Status and all other options responsibility will be handled by Android Default Messaging App.

To do this we need


getContentResolver().insert(Uri.parse("content://sms/inbox"),
contentValues);


two permissions as



 <uses-permission android:name="android.permission.WRITE_SMS" />
 <uses-permission android:name="android.permission.READ_SMS" />



Just Create New project As PushMessage.java





Your main class PushMessage.java


public class PushMessage extends Activity {
       EditText editTextTitle;
       EditText editTextBody;
       Button cancelbtn;
       Button pushSMSbtn;

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

              /**
               * Setting UI
               */
              editTextTitle = (EditText) findViewById(R.id.editTextTitle);
              editTextBody = (EditText) findViewById(R.id.editTextTitle);
              cancelbtn = (Button) findViewById(R.id.btnCancel);
              pushSMSbtn = (Button) findViewById(R.id.btnPushSms);

              /**
               * Seating On click listener
               */
              cancelbtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {

                           finish();
                     }
              });

              /**
               * Seating On click listener
               */
              pushSMSbtn.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           pushMesgIntoInbox();
                     }
              }); 
       } 
       /**
        * This Method push Message Into Inbox
        */           
       public void pushMesgIntoInbox() {
              String title = editTextTitle.getText().toString();
              String body = editTextBody.getText().toString();

              /**
               * This requires <uses-permission
               * android:name="android.permission.READ_SMS" /> <uses-permission
               * android:name="android.permission.WRITE_SMS" />
               */

              if (!title.equals("")) {
                     try {

               /** Creating Simple New Message 
               */
                           ContentValues contentValues = new ContentValues();
                           contentValues.put("address", title);
                           contentValues.put("body", body);
                           contentValues.put("date", ava.lang.System.currentTimeMillis());

               /** Message 
               */                    
                           getContentResolver().insert(Uri.parse("content://sms/inbox"),
                                         contentValues);


                           Toast.makeText(getApplicationContext(), "Message Pushed",
                                         Toast.LENGTH_LONG).show();

                           // set EditText to empty
                           editTextBody.setText("");
                           editTextTitle.setText("");
                     } catch (Exception e) {
                           e.printStackTrace();
                           Toast.makeText(getApplicationContext(),
                                         "No Messaging App Found. " + e,                 
                           Toast.LENGTH_LONG).show();
                     }
              } else {
                      Toast.makeText(getApplicationContext(),
                                  "Please Enter Title"  , Toast.LENGTH_LONG)
                                  .show();
              }

       }
}


And xml layout activity_push_message.xml

    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/editTextTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="SMS Title / Number " />

        <EditText
            android:id="@+id/edittextBody"
            android:layout_width="match_parent"
            android:layout_height="222dp"
            android:ems="10"
           
            android:hint="Message Body"
            android:singleLine="false" />

        <Button
            android:id="@+id/btnPushSms"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Push SMS To Inbox" />

        <Button
            android:id="@+id/btnCancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Cancel" />

    </LinearLayout>

  
 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.blogspot.khurramitdeveloper"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
   
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.blogspot.khurramitdeveloper.PushMessage"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thats end You had done :)
Now run Your App 




Hope it is useful to you :)
Happy Codding :)