Breaking News


Thursday, 6 February 2014

Android Notification LED sample

Note : You should lock(screen) the phone before run this project(via android IDE) , because notification LED will be highlighted only when screen is off


Source SVN:LEDNotification
Zipped Source:LEDNotification 

 
  public class LEDNotification extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  for (int i = 0; i < 8; i++) {
   notif.cancel(1); // clear previous notification 
   final Notification notification = new Notification();
   if (i == 0){
    notification.ledARGB = Color.MAGENTA;
   }else if (i == 1){
    notification.ledARGB = Color.BLUE;
   }else if (i == 2){
    notification.ledARGB = Color.CYAN;
   }else if (i == 3){
    notification.ledARGB = Color.GRAY;
   }else if (i == 4){
    notification.ledARGB = Color.GREEN;
   }else if (i == 5){
    notification.ledARGB = Color.RED;
   }else if (i == 6){
    notification.ledARGB = Color.WHITE;
   }else if (i == 7){
    notification.ledARGB = Color.YELLOW;
   }
   notification.ledOnMS = 1000;
   notification.flags |= Notification.FLAG_SHOW_LIGHTS;
   notif.notify(1, notification);
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {    
    e.printStackTrace();
   }
  }

 }

 

} 
No Special permission required for this project (LED Notification)


Android Get IP Address

Android application for fetching network IP address of the android device

Create new android project and add below code changes on MainActivity.java

Source SVN:Android IP Address Zipped Source :IPAddressDisplay.zip

package com.javaorigin.ipdisplay;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  try {
   for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
              NetworkInterface intf = en.nextElement();
              for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                  InetAddress inetAddress = enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                  TextView ipView= (TextView) findViewById(R.string.ip);
                  ipView.setText(inetAddress.getHostAddress());
                  }
              }
          }
  } catch (Exception e) {
   Log.e("------------", e.toString());
  }
   
 }


}

Add network permission to AndroidManifest.xml 

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

Android RTP Sample (Receiving via VLC player)

Simple demonstrate application for creating rtp audio stream using android.net.rtp package

   RTP Sender    : Android Application
   RTP Receiver : VLC Player

 Source :RtpSender (SVN)
 Zipped Source : RTPSender.zip

 Steps : 
       Create new android project with minimum sdk vesrion 12
       Open the MainActivity.java and make below code changes

     

package com.javaorigin.rtpsender;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.net.rtp.AudioCodec;
import android.net.rtp.AudioGroup;
import android.net.rtp.AudioStream;
import android.net.rtp.RtpStream;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
  try {   
      AudioManager audio =  (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
      audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
      AudioGroup audioGroup = new AudioGroup();
      audioGroup.setMode(AudioGroup.MODE_NORMAL);        
      AudioStream audioStream = new AudioStream(InetAddress.getByAddress(getLocalIPAddress ()));
      audioStream.setCodec(AudioCodec.PCMU);
      audioStream.setMode(RtpStream.MODE_NORMAL);
                           //set receiver(vlc player) machine ip address(please update with your machine ip)
      audioStream.associate(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, (byte)1, (byte)19 }), 22222);
      audioStream.join(audioGroup);
     
   
  } catch (Exception e) {
   Log.e("----------------------", e.toString());
   e.printStackTrace();
  }
 }
public static byte[] getLocalIPAddress () {
    byte ip[]=null;
       try {
           for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
               NetworkInterface intf = en.nextElement();
               for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                   InetAddress inetAddress = enumIpAddr.nextElement();
                   if (!inetAddress.isLoopbackAddress()) {
                    ip= inetAddress.getAddress();
                   }
               }
           }
       } catch (SocketException ex) {
           Log.i("SocketException ", ex.toString());
       }
       return ip;
       
 }
 

}


please update the corresponding  remote ip address
Add  below permissions to AndroidManifest.xml
    

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

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

    <uses-permission android:name="android.permission.RECORD_AUDIO" >

    </uses-permission>

    
Run the above rtp sender application
Now start the vlc player and click Media-->Open Network Stream menu
Enter the following url  (please update with your machine ip) and click play button

         rtp://192.168.1.19:22222

Android Notification LED





Now you can hear the voice  and analysis the receiving data using following vlc options



     Open  Tools--->Codec Information
            

Android Notification LED


Android Notification LED
            

Android Home And Lock Screen Widget - (Temperature Widget)

Create TemperatureWidget class and register with Temperature sensor intend
Download Source 

package com.javaorigin.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RemoteViews;

package com.javaorigin.widget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RemoteViews;

public class TemperatureWidget extends AppWidgetProvider {
 double temp=0;
 @Override
 
 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
  context.getApplicationContext().registerReceiver(this,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  updateUI(context) ;
 }

 @Override
 public void onReceive(Context context, Intent intent) {  
  temp=intent.getIntExtra("temperature", 0)/10.0D;
  updateUI(context) ;
  super.onReceive(context, intent);
 }

 private void updateUI(Context context) {
  RemoteViews thisViews = new RemoteViews(context.getApplicationContext() .getPackageName(), R.layout.widget_layout);
  thisViews.setTextViewText(R.id.update, temp + "");

  ComponentName thisWidget = new ComponentName(context,TemperatureWidget.class);
  AppWidgetManager.getInstance(context).updateAppWidget(thisWidget,thisViews);
 }
}

Create widget_layout.xml under res/layout folder 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="8dip"
    android:background="@drawable/myshape" >

    <TextView
        android:id="@+id/update"
        style="@android:style/TextAppearance.Medium"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center_horizontal|center_vertical"
        android:layout_margin="4dip"
        android:text="Static Text" >
    </TextView>

</LinearLayout> 
Create myshape.xml under res/drawable folder
<?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="#FFFFFFFF" />

    <gradient
        android:angle="225"
        android:endColor="#DD2ECCFA"
        android:startColor="#DD000000" />

    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

</shape>
Create widget_info.xml under res/xml folder ,We can create this xml file using " File-->New --> Android xml file " menu with resource type is AppWidget Provider option ,then set attributeandroid:widgetCategory="keyguard|home_screen" 
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"  
    android:initialLayout="@layout/widget_layout"
    android:minHeight="20dp"
    android:minWidth="20dp"
    android:updatePeriodMillis="30000" android:widgetCategory="keyguard|home_screen">  
    

</appwidget-provider>

Configure android manifest xml 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javaorigin.widget"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
           <receiver android:name="TemperatureWidget" >
            <intent-filter >
                <action 
                    android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
        </receiver>
    </application>

</manifest>

Android Device/Battery Temperature Sensor Sample

Create Temperature activity and create instance for android.intent.action.BATTERY_CHANGED intend  and register with Temperature Broadcast Receiver
Download Source 

package com.javaorigin.temperature;

import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class TemperatureActivity extends Activity   {
 TemperatureReceiver receiver=new TemperatureReceiver(this);
 TextView tempDisplay=null;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
   tempDisplay=(TextView) findViewById(R.id.tempDisplay);

   IntentFilter localIntentFilter = new IntentFilter();
   localIntentFilter.addAction("android.intent.action.BATTERY_CHANGED");
   registerReceiver(receiver, localIntentFilter);   
 }


}


Create Temperature Broadcast Receiver
package com.javaorigin.temperature;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class TemperatureReceiver extends BroadcastReceiver{
 TemperatureActivity activity=null;
 public TemperatureReceiver(TemperatureActivity mainActivity) {
  activity=mainActivity;
 }
 @Override
 public void onReceive(Context arg0, Intent arg1) {
  activity.tempDisplay.setText(arg1.getIntExtra("temperature", 0)/10.0D+"");
 }

}


Android Audio Demo - AudioTrack , AudioRecord - (Echo Sample)

Simple echo application for how to use android AudioTrack and AudioRecord classes
Download Source 
Step 1
    Create MainActivity class for audio record and play

package com.javaorigin.audio;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
 AudioManager am = null;
 AudioRecord record =null;
 AudioTrack track =null;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  setVolumeControlStream(AudioManager.MODE_IN_COMMUNICATION);
  init();
  (new Thread() {
   @Override
   public void run() {
    recordAndPlay();
   }
  }).start();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 private void init() {
  int min = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
  record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, 8000, AudioFormat.CHANNEL_IN_MONO,
    AudioFormat.ENCODING_PCM_16BIT, min);

  int maxJitter = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
  track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, 8000, AudioFormat.CHANNEL_OUT_MONO,
    AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
 }

 private void recordAndPlay() {
  short[] lin = new short[1024];
  int num = 0;
  am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
  am.setMode(AudioManager.MODE_IN_COMMUNICATION);
  record.startRecording();
  track.play();
  while (true) {
   num = record.read(lin, 0, 1024);
   track.write(lin, 0, num);
  }
 }
 
 boolean isSpeaker = false;

 public void modeChange(View view) {
  Button modeBtn=(Button) findViewById(R.id.modeBtn);
  if (isSpeaker == true) {   
   am.setSpeakerphoneOn(false);
   isSpeaker = false;
   modeBtn.setText("Call Mode");
  } else {   
   am.setSpeakerphoneOn(true);
   isSpeaker = true;
   modeBtn.setText("Speaker Mode");
  }
 }
    
 boolean isPlaying=true;
 public void play(View view){
  Button playBtn=(Button) findViewById(R.id.playBtn);
  if(isPlaying){
   record.stop();
   track.pause();
   isPlaying=false;
   playBtn.setText("Play");
  }else{
   record.startRecording();
   track.play();
   isPlaying=true;
   playBtn.setText("Pause");
  }
 }
 
}
Step 2
        Add Button for Play/Pause and Call mode/ Speaker mode

<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/modeBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="24dp"
        android:text="Call Mode" 
        android:onClick="modeChange"/>

    <Button
        android:id="@+id/playBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/modeBtn"
        android:layout_alignBottom="@+id/modeBtn"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/modeBtn"
        android:onClick="play"
        android:text="Pause" />

</RelativeLayout>

Step 3
    Add audio related permission to Android.xml 

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

Blocking Incoming call - Android

Step 1:
Create Broadcast receiver class for incoming call

package com.javaorigin.android.sample;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Phone call";
 private ITelephony telephonyService;

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v(TAG, "Receving....");
  TelephonyManager telephony = (TelephonyManager) 
  context.getSystemService(Context.TELEPHONY_SERVICE);  
  try {
   Class c = Class.forName(telephony.getClass().getName());
   Method m = c.getDeclaredMethod("getITelephony");
   m.setAccessible(true);
   telephonyService = (ITelephony) m.invoke(telephony);
   //telephonyService.silenceRinger();
   telephonyService.endCall();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }

 
}


Step 2:
Create IDL interface for getting core Telephony service
package name must be com.android.internal.telephony

FileName : ITelephony.aidl

  package com.android.internal.telephony;

  interface ITelephony {

   
    boolean endCall();

  
    void answerRingingCall();

   
    void silenceRinger();

  }


Step 3:
AndroidManifest.xml configuration

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.javaorigin.android.sample"
      android:versionCode="1"
      android:versionName="1.0">  
    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver  android:name=".PhoneCallReceiver">
            <intent-filter  android:priority="100" >
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="5" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

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

</manifest>
Share This
Blogger
Facebook
Disqus

comments powered by Disqus

No comments :

Post a Comment

Subscribe
Labels
Popular Posts

Subscribe Via Email

About Us

THIS IS ANDROID AND JAVA FREE TUTORIAL AND ALL PROVIDE SOLUTION IN ANDROID AND JAVA INTERVIEW QUE AND ANS IS AVAILABLE IN MY BLOG AND ANY QUERY PLEASE CONTACT ME GO NOW CONTACT US PAGE.

Total Pageviews

© Android and Java solution All rights reserved | Designed By Fireandroids