WELCOME Abdennour : Software engineer

Apr 6, 2012

Summary Of Matos's Android Tutos(Part1)

Summary Of Introduction's Tuto :(1)

Structure of a typical Android Application:



Delivering Intents:

Difference Between  startActivity & startActivityForResult:
Context.startActivity()
Activity.startActivityForResult()
to launch an activity
get an existing activity to do something
new
asynchronous
synchronously



-Intent  is passed to Context.startService()èinitiate a service
-Intenent can be passed to Context.bindService()èEstablish connexion(compenonent+target service).

TYPES OF INTENTS:

1)Explicit Intent:to start service+to launch a sister activity
2)Implicit Intent: to activate component in other applications.

INTENTFilters:

-intentFilter=Relation btween :Intent+Application.
è Has field named Categoryè to classify the action.
è Exemple: CATEGORY_LAUNCHER .==è Activity sould be visible in the home screen.
è Filter describe that the component is willing(prêt) to receive.
è <intent-filter>: defined in xml AndroidManifest.

The components of Android Application:

1)Activity;2)Service:3)BroadCast Receiver; 4)Content Provider

1)Service Component:

-run in background+not interacting with the user+run in the main thread.
-in AndroidManifest it’s define by <service>
-Signature du class  Service:public class Service1 extends Service implements Runnable {
       
-Ds onCreate : start the new Thread(this)
-Ds method Run : implement the service.
-Other Class extens Activity which is a driver of Service(create intent(this,Service*.class) and call startService)

2)Broadcast Receiver:

-Don’t have interface UI as Services.
-Receive or respond to a global event èExple:pohne rining,sms.
-In xml AndMfst : define in intentFilter : register & intents to receive by this register.
-onReceive:method of this component è pas des persistences de operations.
-if the BroadCast Receiver cannot support several code to execute, The code should initiate a service which will complete fonctionnalities.
sendBroadCast è onReceive

Intents vs. Broadcasts
Starting an Activity with an IntentBroadcasting an Intent
*is foreground operation*is background operation
– Starting an Activity with an Intent is a foreground
operation that modifies what the user is currently
interacting with.
– Broadcasting an Intent is a background operation
that the user is not normally aware of.

-TYPES Of BROADCAST:
Normal (By sendBroadCast)
Ordered
-Asychronous
-receiver run in disorder
-sendOrderedBroadcast.
-Delivre to one receiver at time.
-Control order of receiver by =>  android:priority
è often use a Service in conjunction with a BroadcastReceiver to keep the containing process
 active for the entire time of your operation.


BroadCast Code Source Example : Click Here

3)Content providers: (Les fournisseurs de contenu)

-Store+retrieve data.
-make accebile[data] to  all Applications. è The only way to share dataè it’s th DATA LAYER.
-it provides data to an activity or a service.
-use data storage if data persistence is not required.


-The data model of Android:
*Content providers expose their data as a simple table on a database model.
* each row is a record 
* and each column is data of a particular type & meaning
Example Of Content Provider database:(Annuaire):
__
-data set of C.Provider  defined by URI.
-all Uri start by :”content://”
-ContentResolver takes Uri as argument to define: provider+ table of the provider.
-To Query a Provider it should have:
             1.  id_provider(which is Uri)
              2.name of fields
            3.data types for those field
       -to Query Record in provider:Add 4.ID_Record
èQuery return :Cursor

Manifest xml File:


Example Currency Converter:


=================================================================================================


Summary Android Emulator Tuto: (2)





Emulator Snippets:




Configure AVD Sample:

Create AVD with  Cmd Line:
$android create avd -n <avd_name> -t <targetID>  -c <size>[K|M]
Example :
$android create avd -n myAVD4SD1G -t 4  -c 1024M
Create SD Card:
mksdcard <size> <file>
Example:
//Creer SD Card
1$mksdcard 1024M c:/mysdcard.iso

2$emulator -sdcard c:\mysdcard.img
3$emulator -avd  myAvdFile

Moving Data, Enechid and Pictures to the Sdcard:




Shell linux of Android:

$adb shell <cmd>
Exemple

adb  shell ls
(adb=Android Debug Bridge)

REMARQUE:

-There no cmd ‘cp’ after adb shell.
-Instead of ‘cp ’ use ‘cat’:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
$adb  shell cat  data/app/theInstalledApp.apk > cache/theInstalledApp.apk




 Commandes ADB
1.   Get a list of all active emulators
$adb devices
2.   Run adb application as follows:  
$adb  -s emulator-5554  shell
ds





To Move App in phone to Emulatorèfollow this steps:
1)$adb devices    //make sure: if the phone is connected , Terminal show id of Phone.(soit id= HT845G)
2) $adb -s HT845G pull data/app/theInstalled.apk   c:/theInstalled.apk
3) adb -s  emulator-5554  install c:\theInstalledApp.apk
adb -s  emulator-5554  uninstall data/app/theInstalled.apk
To Sending Text Messages to the Emulator 
1.    Start the emulator. 
2.     $c:>   telnet localhost <id_of_emulator> 
3.     $sms  send  <Sender’s phone number>  <text message>

Making a Voice Call to the Emulator 
1 & 2 is the same compare to previous .
3.     $gsm call <caller’s phone number>

==============================
Summary of Application’s Life Cycle Tuto(4)



Activities managed as in Stack(pile):

-Activity started placed on top of the stack(tête de la pile).
-Pressing in back button(retour) the next activity move up & becomes active.


1)Running Activity =è in foreground.
2)Paused Activity èlost focus but is visible to user.(can be killed by the system if low memory situations)
3)stopped Activity è obscured by another actv. à not visible to the user.

·        Methodes Killable:
                     -onPause(), onStop(), and onDestroy()
                      -onPause nly garantis d’etre called before the process is killed(onStop&onDestroy may be)
                      èUse onPause to the persistence data(editing of users…)
Preferences: (mechanism to store&retrieve key-value pairs of  primitives data types)
- Context.getSharedPreferences()==to read and write values.
- Activity.getPreferences()=instance of preference.(but cannot share preference unless assign name to it.
-Cannot share preference across(entre) apllications.

View Class:
-ViewGroup=base class of layouts
-Views in Windows arranged in a single tree.
-Methods:1)set Properties;2)set focus; 3)set up listners;4)set visibility…
-Type of layouts:

Some Components:

 1. AutoCompleteTextView=EditText with suggestions when write onkey.
UI Graphic layout : 1)By ADT eclipse ; 2)DroidDraw;3) Asset Studio
- HierarchyViewer.bat =(in /sdk/tools/*) utilisty display the hierarchy of current device.

Summary of Basic XML Layouts Tuto(5)

Types basic of layouts are 5:

1.Frame:blank space in screen
2. Linear,:align chifren views in same orientation(Ver,HORZ) by (android:orientation)
3. Relative, :lets  child views specify their position relative to the parent view or to each other.
    Example : android:layout_toLeftOf=“@+id/my_button"   (left %button my_button)
                        android:layout_below="@+id/label"        (below=au dessous)
                            android:layout_alignParentRight="true" (aligned to right % parent view)          
             android:layout_alignTop="@+id/ok“ (aligned % Y)
4.Table: positions into rows & colonne(<TableRow>:define single row in the table)
Exple: <TableRow></TableRow><TableRow></TableRow>  è2lignes
5. Absolute:With x & y coordennates

Attaching Layouts to Java Code

-setContentView(R.layout.main);
-Button btn = (Button) findViewById(R.id.myButton);


Widgets Samples:
 1)Button:
<Button
android:id="@+id/btnExitApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10px"
android:layout_marginLeft="5px"
android:text="Exit Application"
android:textSize="16sp"
android:textStyle="bold"
android:gravity="center"
android:layout_gravity="center_horizontal"
> 
</Button>
Manage listener of 2 buttons:

2) ImageView and ImageButton(subclass  of  ImageView)



3)EditText : (Extension of textView):
To set Text by Default è android:hint=”<text_par_defaut>”



4)RadioButton:
-toggle() èselect radio
-RadioGroupin Xml:
<RadioGroup> <RadioButton>..</RadioButton>…<RadioButton>..</RadioButton> </RadioGroup>


Container:

The simplest layout is frame layout.



Summary of Selection Widgets Tuto(6)
*ListBox Example: 

A)Layout XML:
    <ListView android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" ></ListView>
B) Activity Code :


package slm.toumi.test.android.listDeroulant;



import android.app.Activity;

import android.app.ListActivity;

import android.os.Bundle;

import android.widget.ArrayAdapter;



public class ListBoxActivity extends ListActivity {

    /** Called when the activity is first created. */

    

    private String[] itemText={

        "Faith","Shahadah","Salat","Zakat",

        "Sawm of Ramadan","Hajj"

    };

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        ArrayAdapter<String> adapter=new ArrayAdapter<String>(

            this, android.R.layout.simple_list_item_1,itemText);

        setListAdapter(adapter);

    }

}



Result :

=================================
Summary Of Data/time /tabs(onglets) Tuto (7A):

Date:

-Two widgets for Date :
     1)DatePicker
     2)TimePicker.

1)DatePicker:year,month(0-11),day.
==> Listners:OnDateChangedListener ; OnDateSetListener .

2)TimePicker : hours(0-23);minutes(0-59) . AM/PM with toggle
==> Listners:OnTimeChangedListener ; OnTimeSetListener .=>to notify.

3) DigitalClock
4)AnalogClock

Tabs(Onglets)



With Tab Widget:
1.   TabHost =the main container for the tab (include TabWidget+FrameLAyout)
2.   TabWidget=the row of tab buttons(where we click to change the onglet)
3.   FrameLayout is the container for the tab .
Exemple:
<TabHost android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

<FrameLayout
             ﷟HYPERLINK "mailto: android:id="@android:id/tabcontent" android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
              android:layout_height="fill_parent"
             android:paddingTop="62px">
              <!-- PUT HERE FrameLayout1(can you use include tag or define a component ) -->
            <!-- PUT HERE FrameLayout2  -->
</FrameLayout>

in FrameLayout(i ) make :
1)Component (Button,..) or(FrameLayout:arround component with <Framelayout> is optionally.
2) Include other layout ; for example,if we have the name of the layout to include is"scree2.xml": <include layout="@layout/screen2" /> it should be arround by <FrameLayout>

TO select aTab:

1)method1: tabs.setCurrentTab(<numero>) ; //strat by 0
2)method 2:tabs.setCurrentTabByTag(<name_onglet>)

Listner of onglets:

-tabs.setOnTabChangedListener (implement the method onTabChanged.

Date&Time Code Source Example :

A)Layout XML File:

T 
<Button
    android:id="@+id/widget42"
    android:layout_width="284dp"
    android:layout_height="wrap_content"
    android:layout_x="8dp"
    android:layout_y="83dp"
    android:text="Set Date" />

<Button
    android:id="@+id/widget43"
    android:layout_width="288dp"
    android:layout_height="wrap_content"
    android:layout_x="6dp"
    android:layout_y="143dp"
    android:text="Set Time" />

<TextView
    android:id="@+id/widget44"
    android:layout_width="292dp"
    android:layout_height="62dp"
    android:layout_x="12dp"
    android:layout_y="14dp"
    android:background="#ff7797ce"
    android:text="TextView" />
B)Activity Code:


package slm.aBdennour.android.formation;



import java.text.DateFormat;

import java.util.Calendar;



import android.app.Activity;

import android.app.DatePickerDialog;

import android.app.TimePickerDialog;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.DatePicker;

import android.widget.TextView;

import android.widget.TimePicker;



public class DateAndTimeActivity extends Activity {

  DateFormat fmt = DateFormat.getDateTimeInstance();

  TextView displayer;

  Button btnDate;

  Button btnTime;

  Calendar myCalendar = Calendar.getInstance();

  DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {



    public void onDateSet(DatePicker view, int year, int monthOfYear,

        int dayOfMonth) {

      // TODO Auto-generated method stub

      // cldr.setTime(fmt.)

      myCalendar.set(Calendar.YEAR, year);

      myCalendar.set(Calendar.MONTH, monthOfYear);

      myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

      updateLabel();



    }

  };

  TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

      myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);

      myCalendar.set(Calendar.MINUTE, minute);

      updateLabel();

    }

  };



  private void updateLabel() {

    displayer.setText(fmt.format(myCalendar.getTime()));

  }



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle icicle) {

    super.onCreate(icicle);

    setContentView(R.layout.main);

    displayer=(TextView)this.findViewById(R.id.widget44);

    btnDate=(Button)this.findViewById(R.id.widget42);

    btnTime=(Button)this.findViewById(R.id.widget43);

    btnDate.setOnClickListener(new OnClickListener() {

      

      public void onClick(View v) {

                   new DatePickerDialog(DateAndTimeActivity.this,d,myCalendar.get(Calendar.YEAR)

                       ,myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)

                       

                       ).show();        

      }

    });

          btnTime.setOnClickListener(new OnClickListener() {

      

      public void onClick(View v) {
        new TimePickerDialog(DateAndTimeActivity.this, t,myCalendar.get(Calendar.HOUR_OF_DAY),myCalendar.get(Calendar.MINUTE),true).show();

      }
    });
  }
}

C)Result:
f






SlidingDrawer :

-cache le contenu hors de l'écran.
-allows user to drag ahandle to bring the content on screen.

==> SlidingDrawer= define the id of the handle + the content:
That Meaning :When I click On "The "Handle" ,"the Content" will appear






handle
small graphic ==> indicate opening/closing ctrl
content
type of container holding(as GridView)

SlidingDraw.animateClose();  //cacher le slidingDraw


























.
.
.
.
.



Tabs(Onglets) Code Source Example :

A)Activity Code File:

package slm.Abdennour.android.formation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;

public class OngletsManage extends Activity {

  TabHost tabs;

  TabHost.TabSpec spec;



  @Override

  public void onCreate(Bundle icicle) {

    super.onCreate(icicle);

    setContentView(R.layout.main);

    TabHost tabs = (TabHostfindViewById(R.id.tabhost);

    tabs.setup();

    TabHost.TabSpec spec;

    spec = tabs.newTabSpec("tag1");

    spec.setContent(R.id.tab1);

    spec.setIndicator("1-Clock");

    tabs.addTab(spec);

    spec = tabs.newTabSpec("tag2");

    spec.setContent(R.id.tab2);

    spec.setIndicator("2-Login");

    tabs.addTab(spec);

    tabs.setCurrentTab(0);

    spec = tabs.newTabSpec("tag2");

    spec.setContent(R.id.tab2);

    spec.setIndicator("2-Login",

        getResources().getDrawable(R.drawable.ic_launcher));

    tabs.addTab(spec);

    Button btnGo = (ButtonfindViewById(R.id.btnGo);

    btnGo.setOnClickListener(new OnClickListener() {

      @Override

      public void onClick(View arg0) {

        EditText txtPerson = (EditTextfindViewById(R.id.txtPerson);

        String theUser = txtPerson.getText().toString();

        txtPerson.setText("Hola " + theUser);

      }

    });

  }

}




B)Layout XML File:
Main.xml include screen2.xml
Layout OF Tab(0) (layout/main.xml)
Layout Of Tab(1) (layout/screen2.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TabHost
        android:id="@+id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:paddingTop="62px" >

            <AnalogClock
                android:id="@+id/tab1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerHorizontal="true" />

            <FrameLayout
                android:id="@+id/tab2"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >

                <include layout="@layout/screen2" />
            </FrameLayout>
        </FrameLayout>
    </TabHost>

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

    <TextView
        android:id="@+id/caption1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:text="Person Name"
        android:textSize="20px" >
    </TextView>

    <EditText
        android:id="@+id/txtPerson"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="txtPerson"
        android:textSize="18sp" >
    </EditText>

    <Button
        android:id="@+id/btnGo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go" >
    </Button>

</LinearLayout>

C)Structure Of Project:


D)Result:

Slidingdraw Code Source Example :

A)Activity Code File:



package slm.Abdennour.android.formation.slidingdraw;



import java.util.Date;



import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.SlidingDrawer;

import android.widget.TextView;



public class slidingdrawManager extends Activity {

  Button btn1;

  Button btn2;

  TextView label1;

  TextView label2;

  TextView label3;

  SlidingDrawer myDrawer;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    myDrawer = (SlidingDrawerfindViewById(R.id.drawer);

    btn1 = (ButtonfindViewById(R.id.btn1);

    btn2 = (ButtonfindViewById(R.id.btn2);

    label1 = (TextViewfindViewById(R.id.label1);

    label2 = (TextViewfindViewById(R.id.label2);

    label3 = (TextViewfindViewById(R.id.label3);

    btn1.setOnClickListener(new OnClickListener() {

      @Override

      public void onClick(View v) {

        Date dt = new Date();

        String now = dt.toLocaleString();

        label1.setText("111 - Selem3leikom " + now);

        label2.setText("222 - Selem3leikom " + now);

        label3.setText("333 - Selem3leikom " + now);

      }

    });

    btn2.setOnClickListener(new OnClickListener() {

      @Override

      public void onClick(View v) {

        myDrawer.animateClose();

      }

    });

  }

}



B)Layout XML Code File:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FF4444CC" >

    <SlidingDrawer
        android:id="@+id/drawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:content="@+id/content"
        android:handle="@+id/handle" >

        <ImageView
            android:id="@id/handle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:id="@id/content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ff006666"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/label1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#ff006666"
                android:text="Line 1"
                android:textSize="22sp" />

            <TextView
                android:id="@+id/label2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#ff669900"
                android:text="Line 2"
                android:textSize="22sp" />

            <TextView
                android:id="@+id/label3"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#ff0000cc"
                android:text="Line 3"
                android:textSize="22sp" />

            <TextView
                android:id="@+id/filler1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textSize="6sp" />

            <Button
                android:id="@+id/btn1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4px"
                android:text=" btn1 - time? " />

            <Button
                android:id="@+id/btn2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4px"
                android:text=" btn2 - close " />
        </LinearLayout>
    </SlidingDrawer>

</RelativeLayout>

C)Result:

fd




Summary Of Hard & Soft Keyboards :(7B)

Structure of a typical Android Application:

IMF=Input Method Framework.

==> IFM arbitrate the interaction between applications and the current input method chosen by the user.
IMF=know with conscience the hardware and its actual state.
IME=Input Method Editor=Clavier virtuelle.



Selon le type de TextEditor , Clavier viruel affiche les caracters appropies(Si int =>affiche les chiffres , Si String=>Afficher les alphabets)
<==LE type de TextEditor se fait par:android:inputType=“...”  ou editTextBox.setRawInputType(int)

To use more then one type for EditorText , use pipe | to define it :
==>Example:android:text="inputType: text|textCapWords"
Avec prgmmation :android.text.InputType.*

TXTBOX:

-to  disable the action of Clavier virtuel   ==>txtBox.setInputType( InputType.TYPE_NULL  );  //with txtBox is  an EditText box.
-
Listener of txbox==>txtBox.setOnTouchListener(*)

Close SoftKeyboard Window / Hide SoftKeyboard

1)To Close it ::::InputMethodManager  imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow  (theEditTextField.getWindowToken(), 0);
2)To hide it:::::the method onTouch of TouchListener should return true(cad: we have consumed the event  without need to keyboard)
TextWatcher:is used to instead the keyListener beacause peut etre ne fonctionne pas avec le clavier virtuel.
==>public void afterTextChanged (Editable theWatchedText).
======================================================
Summary Of Menus's Tuto :(8)


there are two types:
1)Options MEnu
2)Context Menu
MENU contein :
1.   Text
2.   Icons
3.   Radio Buttons
4.   Check Boxes
5.   Sub-menus
6.   Short-cut keys
STEP1:
-registerForContextMenu(editorText1);  =>method to register an individual context menu for this view only(editorText1)
-populateMyFirstMenu(menu); ==>only one Option menu per activity
STEP2 :

Methods related to Menu :

1)onCreateOptionsMenu(Menu menu) => set the option menu for the current activity
2) onCreateContextMenu(ContextMenu m, View v,ContextMenuInfo menuInf)
------
3) boolean onContextItemSelected(MenuItem item) => called whenever an item in your context menu is selected
4) boolean onOptionsItemSelected(MenuItem item) =>called whenever an item in your options menu is selected


          => detect what view is calling(by test of v.getId()==?) and create its context menu.

Arguments of menu.add:(with menu is a type of Menu

menu.add(groupId, optionId, order, title)  ==> Exemple::::menu.add(groupId, 1, 1, "10 points");

Methods sur ItemMenu:

 item.getId.
item.setIcon(R.drawable.uno);  (cad il ya icone (uno.png)ds le chemin:android-sdk-*\platforms\android-*\data\res\drawable)
item1.setShortcut('1', '1');  =>raccourcis  utilisant keyboard-keypad

SubMenu:

-Ceate by ==> menu.addSubMenu  (==menu.add in arguments)
-setHeaderIcon
-.setIcon(R.drawbla.ic_toumi)
subMenu.add==> Ajouter the items.


Menus Code Source Example :

A)Layout XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"  >
<EditText
     android:id="@+id/etMessage1"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
      android:layout_width="fill_parent"
    android:text="Selemou 3leikom" />
<EditText
    android:id="@+id/etMessage2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:text="Hamdou Li ALLAH" />
<TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Press the MENU key, or \nLong-press text-boxes" />

</LinearLayout> 
B)Activity Java Code :

package slm.Abdennour.android.formation.menus;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MenuManager extends Activity {

  EditText etMessage1;
  EditText etMessage2;
  Integer[] arrayPointSize = 1020304050 };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    etMessage1 = (EditTextfindViewById(R.id.etMessage1);
    etMessage2 = (EditTextfindViewById(R.id.etMessage2);

    // you may register an individual context menu for each view

    registerForContextMenu(etMessage1);
    registerForContextMenu(etMessage2);

  // onCreate

    // set the option menu for the current activity

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // only one Option menu per activity
    populateMyFirstMenu(menu);
    return super.onCreateOptionsMenu(menu);
  }
  // detect what view is calling and create its context menu
  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,

      ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    // decide what context menu needs to be made
    if (v.getId() == etMessage1.getId())
      // create a menu for etMessage1 box
      populateMyFirstMenu(menu);
    if (v.getId() == etMessage2.getId()) {
      // create a menu for etMessage2 box
      populateMySecondMenu(menu);
    }
  // onCreateContextMenu

  private void populateMyFirstMenu(Menu menu){

    int groupId = 0int order= 0;

    //arguments: groupId, optionId, order, title

    menu.add(groupId, 11"10 points");
    menu.add(groupId, 22"20 points");
    menu.add(groupId, 33"30 points");
    menu.add(groupId, 44"40 points");
    menu.add(groupId, 55"50 points");
    menu.add(groupId, 68"Red text");
    menu.add(groupId, 77"Green Text");
    menu.add(groupId, 86"Blue text");
    //populateMyMenu

    private void populateMySecondMenu(Menu menu){

    int groupId = 0int order= 0;

    //arguments: groupId, optionId, order, title

    menu.add(groupId,  91"Bold");

    menu.add(groupId, 102"Italic");

    menu.add(groupId, 113"Normal");

    }//populateMySecondMenu

    

}




C)Result :


Summary Of Fonts's Tuto :(9)


There are by default three fonts in android : sans >serif>monospaced

-To Add Font in the Application:

1)create folder /fonts in /assets
2)copy fonts into this folder
3)by java code, bind the font with the UI widget
 Example :
-If We have a TextView named tvCustom :
THen

        // bind the  custom  textview with chosen font

        TextView tvCustom=(TextView)findViewById(R.id.custom);

        Typeface myNewFace=Typeface.createFromAsset(

        getAssets()"fonts/Jokerman.ttf" );

        tvCustom.setTypeface(myNewFace);


Summary Of WebKit's Tuto (Browser/Navigateur):(9)

-Android Browser is based on webkit.
WebView=to host pages of browser.
-App uses WebView must request permission.web
==>(Ds manifest XML) before<application>: <uses-permission android:name="android.permission.INTERNET" />
-myWebView.setSettings().setJavaScriptEnabled(true);  ==>Enable JavaScript
-myWevView.loadUrl("http://**" =>load url
-myWebView.loadData("<h1>Esselem</h1>", mimeType, encoding) =>Ecrire code HTML directement ds le browser.
-Code HTML of GoogleMAp:   String aGoogleMap = "<img src=\"http://maps.googleapis.com/maps/api/"
                 + "staticmap?center=41.5020952,-81.6789717&zoom=14&size=300x300&sensor=false\"> "

Combining HTML + JAVASCRIPT + ANDROID

browser.addJavaScriptToInterface(<nom_interface>,"<nom_method_js>");

Menus Code Source Example :

A)Layout XML File:

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

  <WebView
      android:id="@+id/webkit"
      android:layout_width="fill_parent"
      android:layout_height="406dp" />

  <Button
      android:id="@+id/button1"
      android:layout_width="121dp"
      android:layout_height="wrap_content"
      android:text="Button" />
  
</LinearLayout>       

B)Activity Java File:


package slm.Abdennour.android.formation.browsereshopping;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class BrowserManager extends Activity {
  WebView browser;
  EditText htmlCode;
  Button injectCode;

 
    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        htmlCode=(EditText)this.findViewById(R.id.htmlCode);
        injectCode=(Button)this.findViewById(R.id.button1);
        setContentView(R.layout.main);

        String aGoogleMap = "<img src=\"http://maps.googleapis.com/maps/api/" 

                "staticmap?center=41.5020952,-81.6789717&zoom=14&size=300x300&sensor=false\"> "

        browser=(WebView)findViewById(R.id.webkit)

        browser.loadUrl("http://google.com");

        //browser.loadData("<h1>fd</h1>"  , "text/html","UTF-8"); 

        browser.getSettings().setJavaScriptEnabled(true)

        injectCode.setOnClickListener(new OnClickListener() {

      

      @Override

      public void onClick(View v) {

              browser.loadData("<h2>Html Code Is Injected</h2>""text/html""UTF-8");

          //    browser.reload();

            //  browser.refreshDrawableState();

        

      }

    });

        

    }

}



C)Manifest XML File:

<uses-permission android:name="android.permission.INTERNET" />
    <application



NOTE(GOOGLE Map Required 3 Permissions defined in Manifest)

  <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Summary Of The DialogBox:(11)
-There are two :
1)AlertDialog.
2)Toast.
1)AlertDialog :
-oBscures the underlying view
-does not an inputBox (as .NET) .
-not stop the main thread.

AlertDialog myDial= new AlertDialog.Builder(this)      
               .setTitle("T...r") .setMessage(" ....t?") .setIcon(R.drawable.ic_buzz)         
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                               //CODE
                    }
                })
                .setNeutralButton(  ...)// setNeutralButton
                .setNegativeButton(...)// setNegativeButton
                .create();
                  myDial.show();

2)Toast:

They never receive focus
Toast.makeText ( context,  message,  duration ).show(); 
Toast.makeText ( <view_environement>,  message,  <LONG|SHORT|1> ).show(); 
-Two types of context:
a)Activity:passed to class & methods needed context
b)Application.

-Change the placement of a Toast :

1)void setGravity (int gravity, int xOffset, int yOffset)
==>gravity: Overall (Global)placement.(Gravity.TOP,Gravity.BOTTOM,….)
==>xOffset €[-160,160]
==>yOffSet€[-240,240]
2)void setMargin (float horizontalMargin, float verticalMargin)
==>horizontalMargin €[-50,50]
==>verticalMargin€[-50,50]
=====> centre =>(0,0)

-Custom Toast:

-Custom Combination between /color/shape/text/background/ By Toast:

Setps:
1.    Define the XML layout of the new custom view
2.    Make sure there is a TextView named:  text
3.    Additionally you could attach an android: background to the TextView.
4.    The background could be a figure (such as a .png file) or an XML defined shape (see next example).
Les principes instructions:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.my_toast_layout, (ViewGroup) findViewById(R.id.my_toast_layout_root));
public View inflate (int resource, ViewGroup root)    //to inflate(gonfler) a new view hierarchy
===resource:ID of XML layout resource to load,
- using layout inflation we  may draw a new Hierarchy on top of the existing screen.


1.AlertDialog Code Source Example :

A)Activity File:

package slm.Abdennour.android.formation;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class AlertDialogManager extends Activity {

  Button okBtn;

  EditText txt;

  String msg;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    okBtn = (ButtonfindViewById(R.id.btnGo);

    txt = (EditTextfindViewById(R.id.txtMsg);

    okBtn.setOnClickListener(new OnClickListener() {



    

      public void onClick(View v) {

        // TODO Auto-generated method stub

        AlertDialog dialBox = createDialogBox();

        dialBox.show();

        // WARNING: (in general...)

        // after showing a dialog you should have NO more code. Let the

        // buttons of

        // the dialog box handle the rest of the logic. For instance, in

        // this

        // example a modal dialog box is displayed (once shown you can

        // not do

        // anything to the parent until the child is closed) however the

        // code in

        // the parent continues to execute after the show() method is

        // called.

        txt.setText("I'am here");



      }

    });

  }



  protected AlertDialog createDialogBox() {

    AlertDialog quitting = new AlertDialog.Builder(this)

        .setTitle("Terminator")

        .setMessage("Are you sure that you want to quit?")

        .setIcon(R.drawable.ic_buzz)

        .setPositiveButton("Yes"new DialogInterface.OnClickListener() {



          public void onClick(DialogInterface dialog, int which) {

            // whatever should be done when answering "YES" goes

            // here

            msg = "Yes" + Integer.toString(which);

            txt.setText(msg);

          }

        })

        .setNeutralButton("Cancumiel",

            new DialogInterface.OnClickListener() {

              public void onClick(DialogInterface dialog,

                  int whichButton) {

                // whatever should be done when answering

                // "CANCEL" goes here

                msg = "CANCEL " + Integer.toString(whichButton);

                txt.setText(msg);

              }// OnClick

            })// setNeutralButton

        .setNegativeButton("NO"new DialogInterface.OnClickListener() {

          public void onClick(DialogInterface dialog, int whichButton) {

            // whatever should be done when answering "NO" goes here

            msg = "NO " + Integer.toString(whichButton);

            txt.setText(msg);

          }

        })// setNegativeButton

        .create();



    return quitting;

  }

}


C)Result:


2.Toast Position Code Source Example :

A)Layout XML File:

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

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myTableLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff0000ff"
    android:orientation="vertical"
    android:stretchColumns="1,2" >

    <TableRow
        android:id="@+id/myRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/myCaption"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:background="#ff009999"
            android:gravity="center"
            android:text="Testing Toast - Gravity.CENTER  320x480 pixels"
            android:textSize="20sp" >
        </TextView>
    </TableRow>

    <TableRow
        android:id="@+id/myRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:orientation="horizontal"
        android:padding="10px" >

        <TextView
            android:id="@+id/xLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" X offset: "
            android:textSize="18sp" >
        </TextView>

        <EditText
            android:id="@+id/xBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="numberSigned"
            android:text="0"
            android:textSize="18sp" >
        </EditText>
    </TableRow>

    <TableRow
        android:id="@+id/myRow2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:orientation="horizontal"
        android:padding="10px" >

        <TextView
            android:id="@+id/yLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Y offset: "
            android:textSize="18sp" >
        </TextView>

        <EditText
            android:id="@+id/yBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="numberSigned"
            android:text="0"
            android:textSize="18sp" >
        </EditText>
    </TableRow>

    <TableRow
        android:id="@+id/myRow3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000ff"
        android:orientation="horizontal"
        android:padding="10px" >

        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:text=" Show Toast " >
        </Button>
    </TableRow>

</TableLayout>
B)Activity File:

package slm.Abdennour.android.formation.toastposition;

import android.app.Activity;

import android.os.Bundle;

import android.view.Gravity;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;



public class ToastManager extends Activity {

  EditText xBox;

  EditText yBox;

  Button btn1;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    xBox = (EditTextfindViewById(R.id.xBox);
    yBox = (EditTextfindViewById(R.id.yBox);
    btn1 = (ButtonfindViewById(R.id.btn1);
    btn1.setOnClickListener(new OnClickListener() {

      @Override

      public void onClick(View v) {

        try {

          Toast myToast = Toast.makeText(getApplicationContext(),
              "Esselm Amigos \n Ye 7esraten 3le 3ibed",
              Toast.LENGTH_LONG);


          myToast.setGravity(Gravity.CENTER,
              Integer.valueOf(xBox.getText().toString()),
              Integer.valueOf(yBox.getText().toString()));

          myToast.show();

        catch (NumberFormatException e) {

          Toast.makeText(getApplicationContext(), e.getMessage(),
              Toast.LENGTH_LONG).show();

        }

      }// onClick

    })// listener

  }// onCreate

}// class


C)Result


3.Custom Toast (Toast Fancy)Code Source Example :

A)Layout XML File:
Layout Xml(layout/main.xml)
Layout Xml(layout/my_toast_layout.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#777"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="&quot;Testing Custom TOAST&quot;" />

    <Button
        android:id="@+id/btnShowToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" Show Custom - Normal  Toast " >
    </Button>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/my_broder"
        android:padding="20dp" >
    </TextView>

</LinearLayout>
*Custom Drawable(res/drawable/my_border.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:shape="rectangle">
      <stroke android:width="2dp" android:color="#ffffff00" />
      <solid android:color="#ff990000" />
      <padding android:left="10dp" android:top="4dp" android:right="10dp"
            android:bottom="4dp" />
      <corners android:radius="15dp" />
</shape>
B)Activity File:


package slm.Abdennour.android.formation.fancytoastview;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;



public class MainActivity extends Activity {

  Button btnShowToast;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        btnShowToast=(Button)findViewById(R.id.btnShowToast);
        btnShowToast.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(
        R.layout.my_toast_layout, 
        (ViewGroupfindViewById(R.id.my_toast_layout_root));
        TextView text = (TextViewlayout.findViewById(R.id.text);
        Toast toast = new Toast(getApplicationContext());

        text.setText("Hola mundo \nI'm a fancy Toast");

        toast.setGravity(Gravity.CENTER, 00);

        toast.setDuration(Toast.LENGTH_SHORT);

        toast.setView(layout);

        toast.show();        

        // normal TOAST

        Toast.makeText(getApplicationContext()

        "Hola mundo \nnow I am quite normal"

        Toast.LENGTH_SHORT).show();
      }

    });
        
    }
}


C)Result


Summary Of Intents's Tutos :(12)


-Activity.setContentView (...) la méthode pour exposer (généralement) un interface utilisateur unique
-exchanges between activities are DATA & ACTIONS.
-Moving from Activity A to Activity B ,=>Exexute an intent in A.
-Interaction between Activities is in asynchronous mode.


-Agruments of Intents(the principals):
1)data:expressed as URI , expleN°Mobile to be called (tel:// , http:// ,
2)Action:exple=ACTION_VIEW,  ACTION_EDIT,  ACTION_MAIN,user‐createdactivity.
EXEMPLES OF ACTION/DATA:
Action
data
ACTION_DIAL
tel:123
ACTION_VIEW
http://yaaho.com
ACTION_EDIT
   content://contacts/people/2
ACTION_VEIW
   content://contacts/people/2
ACTION_VIEW
   content://contacts/people/
ACTIONS STANDARS:


there are two types:




Intent myActivity2 = new Intent (Intent. ACTION_DIAL,

Uri.parse( "tel:555-1234"));

 Secondary Attributes:

Secondary Attributes={Extras,Type,Category,Components
myIntent.putExtrar(…., <secondary_attirbute>);
With secondaryAttribute =extras..

Built‐in Standard Broadcast Actions:

Def:Actions used by intents for receiving broadcasts
-We have soit : registerReceiver(BroadcastReceiver, IntentFilter)  , or soit : <receiver> tag in manisfestXML
Calling Immediatilly:
Needs Permission:
<uses‐permission android:name="android.permission.CALL_PHONE" />

retreive the result of the Intent when it finish:

Use :startActivityForResult ( Intent, requestCodeID )

===>requestCodeID=id of call(chosen arbitary)
-Pour capter le resultat , Placer un listener: onActivityResult ( requestCodeID(int), resultCode(int), Intent )
-Avant que l'intent termine l'excution ,elle peut appeller  setResult (resultCode)  as signal to parent activity
===>Exple of Standard ResultCodes={Activity.RESULT_CANCELED,    Activity.RESULT_OK}.
If Child Activity(=intent) is crashed(failed) ==> Parent Activity receive resultCode= RESULT_CANCELED
Part2:Intent :

the IPC expressions actual parameter list, and formal parameter list are used to designated the signature of particpating arguments, and the currently supplied data.
 Android Bundle container
-mechanism used to pass data between activities.
Type Bundle is a collection of <name, value> pairs.
==>Store Bundle=>Bundle myBundle = new Bundle();
                                 myBundle.putDouble ( " var1 " , 3.1415);
==>Retreive Bundle=>Double v1 = myBundle.getDouble( " var1 " );
Example:
Sender(Activity1)
Receiver(Activity2)
Intent myIntentA1A2 = new Intent  (Activity1.this,
Activity2.class);
Bundle myBundle1 = new Bundle();
myBundle1.putInt ("val1", 123);
myIntentA1A2.putExtras(myBundle1);
startActivityForResult(myIntentA1A2, 1122);
Intent myCallerIntent2 = getIntent();
Bundle myBundle  = myCallerIntent.getExtras();
int  val1 = myBundle.getInt("val1");
//-----------------RENVOI--------------------------
myBundle.putString("val1", 456 );
myCallerIntent.putExtras(myBundle);
setResult(Activity.RESULT_OK,
myCallerIntent);
   

Bundling Complex Objects:

Person p1 = new  Person("3bdennour", "GL4");
myData.putSerializable("person", p1);
====================

 Code Source Of 20 Intents  :



package slm.Abdennour.android.formation.intentactiondata;



import android.app.Activity;

import android.app.SearchManager;

import android.content.Intent;

import android.location.Location;

import android.net.Uri;

import android.os.Bundle;



public class MainActivity extends Activity {

  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

  }



  public Intent callNumber(String number) {

    Intent myActivity2 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"

        + number));



    return myActivity2;

  }



  public Intent googleSearch(String query) {

    Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);

    intent.putExtra(SearchManager.QUERY, query);

    return intent;

  }



  public Intent sendSMS(String numberPhone, String sms) {

    Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"

        + numberPhone));

    intent.putExtra("sms body", sms);

    return intent;

  }



  public Intent showingAllImages(String Path) {

    if (Path.equals(null)) {

      Path = "image/pictures/*";

    }

    Intent myIntent = new Intent();

    myIntent.setType("image/pictures/*");

    myIntent.setAction(Intent.ACTION_GET_CONTENT);

    return myIntent;

  }



  public Intent showAllCantact() {

    String myData = " content://contacts/people/";

    Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(myData));

    return myActivity2;

  }



  public Intent showContactById(int ID) {

    String myData = " content://contacts/people/" + String.valueOf(ID);

    Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(myData));

    return myActivity2;

  }



  public Intent editContactById(int ID) {

    String myData = " content://contacts/people/" + String.valueOf(ID);

    Intent myActivity2 = new Intent(Intent.ACTION_EDIT, Uri.parse(myData));

    return myActivity2;

  }



  public Intent viewWebURL(String URL) {

    Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));

    return myActivity2;

  }



  public Intent viewMapWithAddress(String geoCode) {

    if (geoCode.equals(null)) {

      geoCode = "geo:0,0?q=1860+east+18th+street+cleveland+oh";

    }

    Intent myActivity2 = new Intent(Intent.ACTION_VIEW, Uri.parse(geoCode));

    return myActivity2;

  }



  public Intent viewMapWithCoordenate(double latitude, double longitude) {

    String geoCode = "geo";

    if (latitude == || longitude == 0) {

      geoCode = "geo:36.843181,10.196255"// INSAT IN TUNISIA

    }



    geoCode = "geo:" + latitude + "," + longitude;

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoCode));

    return intent;

  }



  public Intent translateOnMap(Location startCity, Location endCity) {

    // Uri.parse("http://maps.google.com/maps?saddr=9.938083,‐84.054430&daddr=9.926392,‐84.055964"));

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW,

        Uri.parse("http://maps.google.com/maps?saddr="

            + startCity.getLatitude() ","

            + startCity.getLongitude() "&daddr="

            + endCity.getLatitude() "," + endCity.getLongitude()));

    return intent;

  }



  public Intent searchCityOnMap(String nameOfCity) {

    // Uri.parse("http://maps.google.com/maps?saddr=9.938083,‐84.054430&daddr=9.926392,‐84.055964"));

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW,

        Uri.parse("geo:0,0?q= (" + nameOfCity + ")"));

    return intent;

  }



  /**

   @author Abdennour

   @param location

   *            (try with location(41.5020952,‐81.6789717)

   @return

   */

  public Intent walkIntheStreet(Location location) {

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW,

        Uri.parse("google.streetview:cbll=" + location.getLatitude()

            "," + location.getLongitude()

            "&cbp=1,270,,45,1&mz=1"));

    return intent;

  }



  public Intent showAudios() {

    Intent intent = new Intent("android.intent.action.MUSIC_PLAYER");

    return intent;

  }



  public Intent playAudioFromSDcard(String pathFile, String typeFile,

      boolean readySample) {

    // Ready Ex

    Intent myActivity2 = new Intent(android.content.Intent.ACTION_VIEW);

    Uri data = Uri.parse("file:///sdcard/amarcord.mp3");

    String type = "audio/mp3";

    if (readySample) {

      data = Uri.parse("file:///sdcard/amarcord.mp3");

      type = "audio/mp3";

    else {

      data = Uri.parse("file:///sdcard/" + pathFile);

      type = typeFile;

    }



    myActivity2layout .setDataAndType(data, type);

    return myActivity2;

  }



  public Intent addImageFromSdToMms(int IdImg, String numberPhone,

      String smsTxt, String extensionOfImage) {

    Uri uri = Uri.parse("content://media/external/images/media/" + IdImg)// Exemple=

    Intent myActivity2 = new Intent(Intent.ACTION_SEND);

    myActivity2.putExtra("address", numberPhone);

    myActivity2.putExtra("sms_body", smsTxt)// exempe:"this is the picture of insat"

    myActivity2.putExtra(Intent.EXTRA_STREAM, uri);

    myActivity2.setType("image/" + extensionOfImage)// exple:"image/png"

    return myActivity2;

  }



  public Intent sendMail(String addressMail, String subject,

      String bodyMessage) {

    Uri uri = Uri.parse("mailto:" + addressMail);// Exple:mail="v.matos@csuohio.edu"

    Intent myActivity2 = new Intent(Intent.ACTION_SENDTO, uri);

    // you may skip the next two pieces [subject/text]

    myActivity2.putExtra(Intent.EXTRA_SUBJECT, subject);

    myActivity2.putExtra(Intent.EXTRA_TEXT, bodyMessage);

    //in main invoc 

    //startActivity(myActivity2);

    return myActivity2;

  }

  public Intent showSettingSystem(){

    return new Intent(android.provider.Settings.ACTION_SETTINGS)

  }

  public Intent showSettingLanguge(){
    return new Intent(android.provider.Settings.ACTION_LOCALE_SETTINGS);
  }

}


intent Make Call Code Source Example :

A)Layout XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/label1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000cc"
        android:text="This is Activity1"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="54px"
        android:text="tel:555-1234"
        android:textSize="18sp"
        width="fill parent" />

    <Button
        android:id="@+id/btnCallActivity2"
        android:layout_width="149px"
        android:layout_height="wrap_content"
        android:text="Make Phone Call"
        android:textStyle="bold" />

</LinearLayout>
B)Activity File:


package slm.Abdennour.android.intentmakecall;

import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

/**

 * IntentDemo1_Intent: making a phone call

 

 @author Abdennour

 

 */

public class CallWithIntentManager extends Activity {

  TextView label1;

  EditText text1;

  Button btnCallActivity2;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    try {



      setContentView(R.layout.main);

      label1 = (TextViewfindViewById(R.id.label1);

      text1 = (EditTextfindViewById(R.id.text1);

      btnCallActivity2 = (ButtonfindViewById(R.id.btnCallActivity2);

      btnCallActivity2.setOnClickListener(new ClickHandler());



    catch (Exception e) {

      Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)

          .show();

    }



  }



  private class ClickHandler implements OnClickListener {

    @Override

    public void onClick(View v) {

      try {

        // myActivity2 places a phone call

        // for ACTION_CALL or ACTION_DIAL

        // use 'tel:' formatted data: "tel:555-1234"

        // for ACTION_VIEW use data: "http://www.youtube.com"

        // (you also need INTERNET permission - see Manifest)

        String myData = "tel:555-1234";

        Intent myActivity2 = new Intent(Intent.ACTION_DIAL,

            Uri.parse(myData));

        startActivity(myActivity2);

      catch (Exception e) {

        Toast.makeText(getBaseContext(), e.getMessage(),

            Toast.LENGTH_LONG).show();

      }

    }// onClick

  }

}



Intent To Make Call Code Source Example :

A)Layout XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/label1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000cc"
        android:text="This is Activity1"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="54px"
        android:text="content://contacts/people/"
        android:textSize="18sp"
        width="fill parent" />

    <Button
        android:id="@+id/btnPickContact"
        android:layout_width="149px"
        android:layout_height="wrap_content"
        android:text="Make Phone Call"
        android:textStyle="bold" />

</LinearLayout>

B)Activity:


package slm.Abdennour.android.intentmakecall;

import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

/**

 * IntentDemo1_Intent: making a phone call

 

 @author Abdennour

 

 */

public class CallWithIntentManager extends Activity {

  TextView label1;

  EditText text1;

  Button btnCallActivity2;



  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    try {



      setContentView(R.layout.main);

      label1 = (TextViewfindViewById(R.id.label1);

      text1 = (EditTextfindViewById(R.id.text1);

      btnCallActivity2 = (ButtonfindViewById(R.id.btnCallActivity2);

      btnCallActivity2.setOnClickListener(new ClickHandler());



    catch (Exception e) {

      Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)

          .show();

    }



  }



  private class ClickHandler implements OnClickListener {

    @Override

    public void onClick(View v) {

      try {

        // myActivity2 places a phone call

        // for ACTION_CALL or ACTION_DIAL

        // use 'tel:' formatted data: "tel:555-1234"

        // for ACTION_VIEW use data: "http://www.youtube.com"

        // (you also need INTERNET permission - see Manifest)

        String myData = "tel:555-1234";

        Intent myActivity2 = new Intent(Intent.ACTION_DIAL,

            Uri.parse(myData));

        startActivity(myActivity2);

      catch (Exception e) {

        Toast.makeText(getBaseContext(), e.getMessage(),

            Toast.LENGTH_LONG).show();

      }

    }// onClick

  }

}


A)Result:






Summary Content Provider Tuto (Last)
To Write a Content Provider:
1. Plan your database, URIs, column names, and so on, and create a metadata class
  that defines constants for all of these metadata elements.
2. Extend the abstract class ContentProvider.
3. Implement these methods: query, insert, update, delete, and getType.
4. Register the provider in the manifest file.


No comments:

Post a Comment