Saturday, November 19, 2011

Android Add Permission Dynemically

public abstract boolean addPermission (PermissionInfo info)
Since: API Level 1
Add a new dynamic permission to the system. For this to work, your package must have defined a permission tree through the <permission-tree> tag in its manifest. A package can only add permissions to trees that were defined by either its own package or another with the same user id; a permission is in a tree if it matches the name of the permission tree + ".": for example, "com.foo.bar" is a member of the permission tree "com.foo".
It is good to make your permission tree name descriptive, because you are taking possession of that entire set of permission names. Thus, it must be under a domain you control, with a suffix that will not match any normal permissions that may be declared in any applications that are part of that domain.
New permissions must be added before any .apks are installed that use those permissions. Permissions you add through this method are remembered across reboots of the device. If the given permission already exists, the info you supply here will be used to update it.
Parameters
infoDescription of the permission to be added.
Returns
  • Returns true if a new permission was created, false if an existing one was updated.
Throws
SecurityExceptionif you are not allowed to add the given permission name.


Thursday, November 17, 2011

Android Facebook API example using FBRocket


Android Facebook API example using FBRocket

This post is posted as per the request of many comments on Android JTwitter Example.
Now let proceed ahead with Facebook using FBrocket.
Using FB rocket we can update our facebook profile status from mobile application.
Before we get into coding we got to make sure that we do the following steps
  1. Import the FBrocket JAR file to the eclipse project and add it to JAR libraries. Download here ( http://www.xeomax.net/fbrocket/download.php?d=bin&v=0.1a )
  2. Make sure you have created an application inhttp://www.facebook.com/developers/#!/developers/createapp.php
  3. Note down application name and API key, do not reveal API key to anybody.
[sourcecode language="java"]
package org.androidpeople.facebook;
import net.xeomax.FBRocket.FBRocket;
import net.xeomax.FBRocket.Facebook;
import net.xeomax.FBRocket.LoginListener;
import net.xeomax.FBRocket.ServerErrorException;
import android.app.Activity;
import android.os.Bundle;
public class FacebookRocketExample extends Activity implements LoginListener {
private FBRocket fbRocket;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareFacebook();
}
public void shareFacebook() {
fbRocket = new FBRocket(this, "Your App Name",
"Your API Key");
if (fbRocket.existsSavedFacebook()) {
fbRocket.loadFacebook();
} else {
fbRocket.login(R.layout.main);
}
}
@Override
public void onLoginFail() {
fbRocket.displayToast("Login failed!");
fbRocket.login(R.layout.main);
}
@Override
public void onLoginSuccess(Facebook facebook) {
// TODO Auto-generated method stub
fbRocket.displayToast("Login success!");
try {
facebook.setStatus("This is your status");
fbRocket.displayDialog("Status Posted Successfully!! "
facebook.getStatus());
} catch (ServerErrorException e) {
if (e.notLoggedIn()) {
fbRocket.login(R.layout.main);
} else {
System.out.println(e);
}
}
}
}
[/sourcecode]
Screenshots :
Download : This Example Click Here


Tuesday, November 15, 2011

Delete file in Internal Storage


Delete file in Internal Storage

Here method deleteFile() delete the given  file associated with this Context's application package.

Delete file in Internal Storage
Delete file in Internal Storage

package com.exercise.AndroidInternalStorage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidInternalStorageActivity extends Activity {
 
 EditText edFileName, edContent;
 Button btnSave;
 ListView listSavedFiles;
 
 String[] SavedFiles;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        edFileName = (EditText)findViewById(R.id.filename);
        edContent = (EditText)findViewById(R.id.content);
     btnSave = (Button)findViewById(R.id.save);
     listSavedFiles = (ListView)findViewById(R.id.list);
     
     ShowSavedFiles();
     
     btnSave.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    String fileName = edFileName.getText().toString();
    String content = edContent.getText().toString();
    
    FileOutputStream fos;
    try {
     fos = openFileOutput(fileName, Context.MODE_PRIVATE);
     fos.write(content.getBytes());
     fos.close();
     
     Toast.makeText(
       AndroidInternalStorageActivity.this, 
       fileName + " saved", 
       Toast.LENGTH_LONG).show();
     
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    ShowSavedFiles();
    
   }});
     
     listSavedFiles.setOnItemClickListener(listSavedFilesOnItemClickListener);
     
    }
    
    void ShowSavedFiles(){
     SavedFiles = getApplicationContext().fileList();
     ArrayAdapter<String> adapter
     = new ArrayAdapter<String>(this,
       android.R.layout.simple_list_item_1,
       SavedFiles);
  
     listSavedFiles.setAdapter(adapter);
    }
    
    OnItemClickListener listSavedFilesOnItemClickListener
    = new OnItemClickListener(){

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
    long id) {
   // TODO Auto-generated method stub
   String clickedFile = (String) parent.getItemAtPosition(position);
   OpenFileDialog(clickedFile);
  }
     
    };
    
    void OpenFileDialog(final String file){
     
     //Read file in Internal Storage
     FileInputStream fis;
     String content = "";
     try {
      fis = openFileInput(file);
      byte[] input = new byte[fis.available()];
      while (fis.read(input) != -1) {}
      content += new String(input);
     } catch (FileNotFoundException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace(); 
     }
     
     //Create a custom Dialog
     AlertDialog.Builder fileDialog 
     = new AlertDialog.Builder(AndroidInternalStorageActivity.this);
     fileDialog.setTitle(file);
     
     TextView textContent = new TextView(AndroidInternalStorageActivity.this);
     textContent.setText(content);
        LayoutParams textViewLayoutParams 
         = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        textContent.setLayoutParams(textViewLayoutParams);
        
        fileDialog.setView(textContent);
        
        fileDialog.setPositiveButton("OK", null);
        
        //Delete file in Internal Storage
        OnClickListener DeleteListener = new OnClickListener(){

   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    deleteFile(file);
    Toast.makeText(
      AndroidInternalStorageActivity.this, 
      file + " deleted", 
      Toast.LENGTH_LONG).show();
    ShowSavedFiles();
   }
 
        };
  fileDialog.setNeutralButton("DELETE", DeleteListener);
        
        fileDialog.show();
    }
}


Download the files.


Monday, November 7, 2011

Android Turn Off Screen


There are two choices for turning the screen off:

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);

// Choice 1
manager.goToSleep(int amountOfTime);


// Choice 2
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();
You will probably need this permission too:

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

UPDATE:

Try this method; android turns off the screen once the light level is low enough.

WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);


Saturday, November 5, 2011

Android How can i call API periodically?

If you want to call that API after 30 second again and again


use Service with Broadcast receiver.
Service will do your Task in Background but will not provide any UI so you need to register with Broadcast receiver.

Check this Sample , this sample show how to repeat a task and update UI using Service and Broadcast receiver.
Also refer this tutorial for further reference.


Thursday, November 3, 2011

Find back stack activities in an android application?


The code below can be used to extract all the tasks and the top activity within each task in the back stack


ActivityManager m = (ActivityManager) ctx.getSystemService( ctx.ACTIVITY_SERVICE );
List<RunningTaskInfo> runningTaskInfoList =  m.getRunningTasks(10);
Iterator<RunningTaskInfo> itr = runningTaskInfoList.iterator();
while(itr.hasNext()){
    RunningTaskInfo runningTaskInfo = (RunningTaskInfo)itr.next();
    int id = runningTaskInfo.id;
    CharSequence desc= runningTaskInfo.description;
    int numOfActivities = runningTaskInfo.numActivities;
    String topActivity = runningTaskInfo.topActivity.getShortClassName();
}


Wednesday, November 2, 2011

Android Introduction and Architecture(Part1)





What is Android?


Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

Features

  • Application framework enabling reuse and replacement of components
  • Dalvik virtual machine optimized for mobile devices
  • Integrated browser based on the open source WebKit engine
  • Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
  • SQLite for structured data storage
  • Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
  • GSM Telephony (hardware dependent)
  • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
  • Camera, GPS, compass, and accelerometer (hardware dependent)
  • Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Ec

Android Architecture

The following diagram shows the major components of the Android operating system. Each section is described in more detail below.


Applications

Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Application Framework

By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.
Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.
Underlying all applications is a set of services and systems, including:
  • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
  • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
  • Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
  • Notification Manager that enables all applications to display custom alerts in the status bar
  • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack
For more details and a walkthrough of an application, see the Notepad Tutorial.

Libraries

Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:
  • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
  • Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
  • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
  • SGL - the underlying 2D graphics engine
  • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
  • FreeType - bitmap and vector font rendering
  • SQLite - a powerful and lightweight relational database engine available to all applications

Android Runtime

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.
The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

Linux Kernel

Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

install Eclips and Androd Sdk on your system and do start Android Programming. Click on: Start


Tuesday, November 1, 2011

Android AsyncTask Example

 When an asynchronous task is executed, the task goes through 4 steps:
  1. onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Source code (main.xml)

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

Source code (TestActivity.java)
public class TestActivity extends Activity
{
Button btn;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.bnt1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
new Async().execute();
}
});
}
public class Async extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute()
{
dialog=new ProgressDialog(TestActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
   // perform desired task in this doInBackground Block.
for(int i=0;i<20;i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return "";
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.incrementProgressBy(5);
}

@Override
protected void onPostExecute(String result)
{
    dialog.dismiss();
AlertDialog.Builder a=new Builder(TestActivity.this);
a.setMessage("Successfully Done");
a.setTitle("Try");
a.setPositiveButton("OK",null);
a.show();
    }
}
}