Search This Blog

Showing posts with label Intent. Show all posts
Showing posts with label Intent. Show all posts

Friday, October 14, 2016

Pick images from default gallery intent

Pick image from default gallery images... from android


final PackageManager packageManager = getPackageManager();
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                                                      PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
         startActivityForResult(intent, PICK_IMAGE_REQUEST);
} else {
          Toast.makeText(UserProfileEditActivity.this, "No app can perform this action",                        Toast.LENGTH_LONG).show();
           return;
}

Wednesday, January 2, 2013

Get all the application installed on your system



First of all add the xml for the list of the application installed on your devices.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android1:id="@+id/listView1"
        android1:layout_width="match_parent"
        android1:layout_height="wrap_content"
        android1:layout_alignParentLeft="true"
        android1:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

Here is the code for the row of the list.

<?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"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="22dp"
       />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_marginLeft="36dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="TextView" />

</RelativeLayout>


Now after that add the following code in your main activity.


public class MainActivity extends Activity {

ArrayList<PInfo> arrylist;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PInfo p = new PInfo();

arrylist = getPackages();

for (int i = 0; i < arrylist.size(); i++) {
Log.i("log_tag", "=======" + arrylist.get(i).icon);
}

ListView l = (ListView) findViewById(R.id.listView1);

l.setAdapter(new ListAdatp(this, arrylist));

}

class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private String move2sd;
private Drawable icon;

private void prettyPrint() {
Log.v(appname + "\t" + pname + "\t" + versionName + "\t"
+ versionCode, "");
}

}

private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /*
* false = no system
* packages
*/

final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i).prettyPrint();

}
return apps;

}

private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager())
.toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());

res.add(newInfo);
}
return res;
}

public class ListAdatp extends BaseAdapter {

Activity ativity;
ArrayList<PInfo> adptarrlist;

public ListAdatp(MainActivity mainActivity, ArrayList<PInfo> arrylist) {

// TODO Auto-generated constructor stub
ativity = mainActivity;
adptarrlist = arrylist;

}

@Override
public int getCount() {
// TODO Auto-generated method stub
return adptarrlist.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub

LayoutInflater inflt = (LayoutInflater) ativity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = inflt.inflate(R.layout.listrow, null);

ImageView img = (ImageView) convertView
.findViewById(R.id.imageView1);
TextView txt = (TextView) convertView.findViewById(R.id.textView1);
img.setBackgroundDrawable(adptarrlist.get(position).icon);
txt.setText("(" + adptarrlist.get(position).appname + ")  "
+ adptarrlist.get(position).pname);

txt.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Intent LaunchIntent = getPackageManager()
.getLaunchIntentForPackage(
adptarrlist.get(position).pname);
startActivity(LaunchIntent);
}
});

return convertView;
}

}

}

Thursday, June 7, 2012

How to get the battery level And the phone number of the phone

For the bettery level of the phone we need to write the following code.


private void batteryLevel() {
             BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
                       public void onReceive(Context context, Intent intent) {
                                    context.unregisterReceiver(this);
                                    int rawlevel = intent.getIntExtra("level", -1);
                                    int scale = intent.getIntExtra("scale", -1);
                                    int level = -1;
                                    if (rawlevel >= 0 && scale > 0) {
                                                       level = (rawlevel * 100) / scale;
                                    }
             batterLevel.setText("Battery Level Remaining: " + level + "%");
         }
        };
   IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
   registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}



Here level indicates the bettery level of the phone.


For getting the phone number of the phone we have to insert the following code...


TelephonyManager phoneManager = (TelephonyManager) getApplicationContext()                            
                                                                     .getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = phoneManager.getLine1Number();

Here phoneNumber indicates the number of the current phone.


Tuesday, February 28, 2012

Uploading Image to the server using webservice

first of all reach to the gallery of the phone using the intent.


Button btnBrowse = (Button)findViewById(R.id.btn_browse);
        btnBrowse.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                "Select Picture"), SELECT_PICTURE);

}
});


Now onActivityResult should be like this.





public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) {
       if (requestCode == SELECT_PICTURE) {
           Uri selectedImageUri = data.getData();
           selectedImagePath = getPath(selectedImageUri);
           EditText imageBrowse = (EditText)findViewById(R.id.thumb_url);
           imageBrowse.setText(selectedImagePath);
           byte[] strBytes = convertToBytes(selectedImagePath);
           
           imageBytes = strBytes;
       }
   }
}
    


    public byte[] convertToBytes(String selectedImagePath)
    {
    try
    {
    FileInputStream fs = new FileInputStream(selectedImagePath);

    Bitmap bitmap = BitmapFactory.decodeStream(fs);
   
    ByteArrayOutputStream bOutput = new ByteArrayOutputStream();
   
    bitmap.compress(CompressFormat.JPEG,1, bOutput);
   
    byte[] dataImage = bOutput.toByteArray();
   
    return dataImage;
    }
    catch(NullPointerException ex)
    {
    ex.printStackTrace();
    return null;
    } 
    catch (FileNotFoundException e)
    {  
e.printStackTrace();
return null;
}
   
    }


public String getPath(Uri uri) {
   String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = managedQuery(uri, projection, null, null, null);
   int column_index = cursor
           .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   cursor.moveToFirst();
   return cursor.getString(column_index);
}




Using this bytes you'll get the image uploaded to the web service and store the image on to the server.

Friday, February 10, 2012

Selecting The Image From The Gallery And Set The Path Into The EditText

First of all we have to reach to the android default gallery and select the file from that and set that path to the edit text.


Make an .xml file named main.xml file and copy this into it.


<?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">
   <EditText android:id="@+id/absolutepathofimage" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" />
  <Button android:text="Browse" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/btnBrowse" />
  </LinearLayout>


Now make the java file named BrowseImagefromGallery and copy this code into it



import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class BrowseImagefromGallery extends Activity {
private static final int GET_PICTURE = 1;


private String selectedImagePath;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btnBrowse = (Button)findViewById(R.id.btnBrowse);
        btnBrowse.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), GET_PICTURE);

}
});
        
        
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) {
       if (requestCode == GET_PICTURE) {
           Uri selectedImageUri = data.getData();
           selectedImagePath = getPath(selectedImageUri);
           EditText imageBrowse = (EditText)findViewById(R.id.absolutepathofimage);
           imageBrowse.setText(selectedImagePath);
       }
   }
}


public String getPath(Uri uri) {
   String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = managedQuery(uri, projection, null, null, null);
   int column_index = cursor
           .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   cursor.moveToFirst();
   return cursor.getString(column_index);
}
}

Friday, January 13, 2012

How to switch between Activities and pass the Data

In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java

Opening new Activity

To open new activity following startActivity() or startActivityForResult() method will be used.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);


sending parameters to new Activity

To send parameter to newly created activity putExtra() methos will be used.
i.putExtra("key", "value");
// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

Receiving parameters on new Activity

To receive parameters on newly created activity getStringExtra() method will be used.
Intent i = getIntent();
i.getStringExtra("key");
// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

Opening new Activity and expecting result

In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
             // Storing result in a variable called myvar
             // get("website") 'website' is the key value result data
             String mywebsite = data.getExtras().get("result");
        }
    }

Sending result back to old activity when StartActivityForResult() is used
Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");
// Setting resultCode to 100 to identify on old activity
setResult(100,in);

Closing Activity

To close activity call finish() method
finish();

Add entry in AndroidManifest.xml

To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags
<activity android:name=".NewActivityClassName"></activity>

Let’s Start with a simple project

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java,SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.

Now lets start by creating a simple project.

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.

2. Now you need to create user interface for the FirstScreenActivity.java

3. Create a new xml file in layout folder or rename the main.xml to screen1.xml

Right Click on Layout -> New -> Android XML file and name it as screen1.xml

4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Name: "/>
    <EditText android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email: "
        />
    <EditText android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <Button android:id="@+id/btnNextScreen"
             android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send to Next Screen"
            android:layout_marginTop="15dip"/>
</LinearLayout>



5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.
package com.example.androidswitchviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class FirstScreenActivity extends Activity {
    // Initializing variables
    EditText inputName;
    EditText inputEmail;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);
        inputName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
        //Listening to button event
        btnNextScreen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Starting a new Intent
                Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);
                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());
                Log.e("n", inputName.getText()+"."+ inputEmail.getText());
                startActivity(nextScreen);
            }
        });
    }
}
6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java
Android creating new class

7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="You Entered..."
              android:textSize="25dip"
              android:gravity="center"
              android:layout_margin="15dip"/>
  <TextView android:id="@+id/txtName"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_margin="15dip"
              android:textSize="18dip"/>
  <TextView android:id="@+id/txtEmail"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_margin="15dip"
              android:textSize="18dip"/>
  <Button android:id="@+id/btnClose"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_marginTop="15dip"
              android:text="Close"/>
</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen

package com.example.androidswitchviews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreenActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);

TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
Button btnClose = (Button) findViewById(R.id.btnClose);

Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String email = i.getStringExtra("email");
Log.e("Second Screen", name + "." + email);

// Displaying Received data
txtName.setText(name);
txtEmail.setText(email);

// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
//Closing SecondScreen Activity
finish();
}
});

}
}


9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and 
modify the code as below


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

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstScreenActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Add new Activity class name here --->
<activity android:name=".SecondScreen"></activity>

</application>
</manifest>
10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens.