Friday 21 August 2015

Android 6.0 Marshmallow.

After a long delay, Google has finally announced its next android version named "Marshmallow".



So now "M" is for MARSHMALLOW.

“Today with the final Developer Preview update, we’re introducing the official Android 6.0 SDK and opening Google Play for publishing your apps that target the new API level 23 in Android Marshmallow,” Jamal Eason, Product Manager, Android writes in a blogpost.

Here are the features you can expect from Android 6.0.
  • Android Pay:
Android Pay is Google's new mobile payments system designed to make the checkout process easier and faster. Compatible with phones running on Android KitKat and above, Android Pay will let you walk into stores and tap on an NFC terminal to pay for products.

According to Google, Android Pay will be pre-installed on AT&T, Verizon and T-Mobile devices and will be accepted in around 700,000 stores in the US which accept contact-less payment. Android Pay will replace the Google Wallet app. Android Pay can also be used to make in-app payments provided developers integrate Pay into their apps.
  • Google Now on Tap:
Google Now on Tap will give Google — with your permission, of course — even more insight into your life. If you're, say, texting someone about dinner plans at some hot new restaurant, a quick press of the home button will bring up more information about that restaurant. No more having to hop out of one app and into another to look up information. This is going to be big.
  • App permissions:
Permissions will now be requested the first time you try to use a feature, not at the point of installation. You don't have to agree to permissions that don't make sense to you. 
Additionally, if you want to have a better idea of what app permissions you've granted, you'll now be able modify permissions within the phone settings.
  • Fingerprint support:
While fingerprint technology is not really widespread on Android phones, Google is opening the necessary APIs to allow developers to add fingerprint support with any app. That improved biometric authentication will also be extended to Android Pay to authorise payments, making it work a lot like Apple Pay.
Of course, your device will need a hardware fingerprint scanner to begin with, but with Google's full support, expect to see these appear on many more devices in the future. 
  • Power management - Doze:
Doze is a new feature that aims to solve or mitigate this issue to a certain extent by reducing the power consumed by the device when in idle state. This feature works by letting system optimally manage the background processes. The OS keeps a tab on the motion detection sensor and if there is no activity for a long time, the system shuts down some processes.
According to Google, this feature has helped increase the standby-time on the Nexus 9 by almost two times over the Android 5.0 Lollipop.
  • USB Type C:
Android M will also support USB Type-C for charging. And considering USB Type-C is has a bi-directional port, you can use this port to either charge the phone as welll as charge another device.
  • App Linking:
Android M will let developers add in an auto-verify feature within their code, which will help open the link within the respective app (provided the app is installed on your phone). In the background, the Android M OS will verify the link with the app’s server and post-authentication will proceed to open the link within the app itself, without asking you where you want to open the link.
  • Direct Share and Floating Toolbar:
Direct Share can learn who you share content with frequently from different apps and turn the process into the press of a single button. With the floating toolbar, it'll also improve the way you can copy and paste content from web pages or documents.
  • RAM Manager:
There is a new and updated RAM Manager in the settings menu that lets the user see what the average amounts of RAM being used over a specific duration. The user can choose from 3 hours, 6 hours, 12 hours or one day. It also rates the performance and shows you the amount of free RAM. You can also view the applications and the amount of RAM they use in detail.




Wednesday 21 January 2015

How to get battery level.

How to get current battery charged level.

Determine the Current Battery Level


Use this method to get the current battery level in android.

public float getCurrentBatteryLevel(Context context) {

Intent batteryStatus = context.registerReceiver(null, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

return level / (float) scale * 100.0f;
}

Friday 31 January 2014

How to upload a file on server

Here we see how to upload a file on server.

In order to upload a file on server we need a server , but here we create a local server either by installing wamp or xampp. To access localhost from android emulator use address http://10.0.2.2/.

Note: Put tuts4mobile_upload.png (find it in project ) into your 
android emulator. 

Create a project with the following details :
  • ProjectName: UploadFile
  • PackageName: sat.tuts4mobile.uploadfile
  • ActivityName: UploadActivity  
In the UploadActivity.java , copy and paste the following code:
package sat.tuts4mobile.uploadfile;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class UploadActivity extends Activity {

String imageUrl;
String uploadUrl;

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

imageUrl = "/mnt/sdcard/tuts4mobile_upload.png";
uploadUrl = "http://10.0.2.2/upoadandroid/upload.php";

findViewById(R.id.buttonUpload).setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String responce = new ServerRequest().uploadFile(uploadUrl, imageUrl);
Toast.makeText(UploadActivity.this, responce,Toast.LENGTH_SHORT).show();
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.upload, menu);
return true;
}

}

Create a new class name ServerRequest.java , and copy paste the following code:
package sat.tuts4mobile.uploadfile;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class ServerRequest {
public String uploadFile(String upLoadServerUri, String sourceFileUri) {
StringBuffer response = null;
int serverResponseCode = 0;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
{
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setChunkedStreamingMode(1024);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200)
 {
System.out.println("Done Send to Server !!!");
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
String line;
response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
return response.toString();
} // End else block
}
}

In the activity_upload.xml  file ,copy and paste the following code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".UploadActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Note: Before upload make sure that you put (tuts4mobile_upload.png) file in the sdcard of emulator. You find ( tuts4mobile_upload.png ) file in the project folder." />

    <Button
        android:id="@+id/buttonUpload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Click to upload" />

</RelativeLayout>

In the AndroidManifest.xml file , copy and paste the following code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sat.tuts4mobile.uploadfile"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sat.tuts4mobile.uploadfile.UploadActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

After doing this , create a folder name “uploadandroid”  in your local server directory .
If you are using  xampp  then in “htdocs” or for wamp in “www”.
Now create a file in “uploadandroid”  folder with name “upload.php” and paste the following code:
<?php
                                $tmpfile=$_FILES["file"]["tmp_name"];
                                $size=$_FILES["file"]["size"];
                                $filename=basename($_FILES["file"]["name"]);                              
                                $type=$_FILES["file"]["type"];
                                $destination="uploads";
                                $file_upload=move_uploaded_file ( $tmpfile  ,$destination."/".$filename );
                                if($file_upload)
               {  
                 echo "Upload Successfully !!!";
                }
?>

And also create a folder name “uploads”.
Now run the application , it shows the following screen shots:




Thursday 19 December 2013


How to start and stop service in android.


Here we see how to start and stop a service dynamically.


What is Service ?


A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the lifecycle of an activity. 

As there are two methods by which we start and stop service  :
  1. startService (Intent service)
  2. stopService (Intent service)

In order to start a service we need to call a method name onStartCommand(Intent intent, int flags, int startId) and to stop a service call a method name onDestroy() . All this work we do in class which extends Service class.

Create a project with the following details :

·         ProjectName: StartStopServicee
·         PackageNamesat.tuts4mobile.startstop
·         ActivityNameMainActivity

In the MainActivity.java file, copy the following code :

package sat.tuts4mobile.startstop;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

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

                        Button start = (Button) findViewById(R.id.button1);
                        start.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                startService(new Intent(MainActivity.this, MyService.class));
                                    }
                        });

                        Button stop = (Button) findViewById(R.id.button2);
                        stop.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                stopService(new Intent(MainActivity.this, MyService.class));
                                    }
                        });

            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                        // Inflate the menu; this adds items to the action bar if it is present.
                        getMenuInflater().inflate(R.menu.main, menu);
                        return true;
            }

}

Create a new class name MyService.java file, copy the following code :

package sat.tuts4mobile.startstop;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service{

            @Override
            public IBinder onBind(Intent intent) {
                        // TODO Auto-generated method stub
                        return null;
            }
           
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            // TODO Auto-generated method stub
           
                        Toast.makeText(MyService.this, "Service Started!!!", Toast.LENGTH_SHORT).show();

            return super.onStartCommand(intent, flags, startId);
    }
   
    @Override
    public void onDestroy() {
            // TODO Auto-generated method stub
           
                        Toast.makeText(MyService.this, "Service Stoped!!!", Toast.LENGTH_SHORT).show();

            super.onDestroy();
    }

}

In the activity_main.xml file, copy the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Start Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="20dp"
        android:text="Stop Service" />

</RelativeLayout>

In the 
AndroidMainfest.xml file, copy the following code:

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

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

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="sat.tuts4mobile.startstop.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <service android:name="sat.tuts4mobile.startstop.MyService"></service>
       
    </application>

</manifest>

Click this to download source code

When you run the application , you see the following screens :