Monday, December 16, 2013

Android Alarm Manager Example | How to Start and Stop Alarm Manager in Android | Notification Manager Example in Android

Hello Friend,

Today I am going to share code for "Create Alarm Manager in Android". And Notification Manager with sound and vibration.


EDIT:stop was not working


1)MainActivity-


package com.manish.alarmmanager;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 *
 * @author manish
 *
 */

public class MainActivity extends Activity implements OnClickListener{

Button btnStartAlarm,btnStopAlarm;
Context context;
static PendingIntent pendingIntent;
static AlarmManager alarmManager;

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


Intent intentsOpen = new Intent(this, AlarmReceiver.class);
intentsOpen.setAction("com.manish.alarm.ACTION");
pendingIntent = PendingIntent.getBroadcast(this,111, intentsOpen, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);


btnStartAlarm=(Button)findViewById(R.id.button1);
btnStopAlarm=(Button)findViewById(R.id.button2);

btnStartAlarm.setOnClickListener(this);
btnStopAlarm.setOnClickListener(this);

}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==btnStartAlarm){
fireAlarm();
}
if(v==btnStopAlarm){
stopAlarm();
}
}
public void fireAlarm() {
/**
* call broadcost reciver
*/
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10000, pendingIntent);


}
public void stopAlarm(){
alarmManager.cancel(pendingIntent);



}


}


3)OutPut.java

package com.manish.alarmmanager;

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

public class OutPut extends Activity {
TextView textmessage;
String stringValue;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);

textmessage = (TextView) findViewById(R.id.textView1);

Intent intent = getIntent();
stringValue = intent.getStringExtra("content");
textmessage.setText(stringValue);
System.out.println(stringValue);

}
}

4)Manifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.alarmmanager.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>
        <activity android:name="com.manish.alarmmanager.OutPut" />

        <receiver android:name=".AlarmReceiver" >
            <intent-filter>
                <action android:name="com.manish.alarm.ACTION" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

DOWNLOAD ZIP CODE

Thanks!

Thursday, November 14, 2013

Fitbit Integration in Android | Login with Fitbit

Hello friends!

on many demand today i am sharing fitbit account integration in android application.

REF-

http://dev.fitbit.com/

https://github.com/manishsri01/FitbitIntegration

NOTE: please create your application on fitbit and replace with yours credential. Don't use mine in your application.



For this i created a MainActivity.java and put a button for login with fitbit account and open a web-view in next page. see below code hope it will help you-

MainActivity.java-


package com.manish.fitbitintegration;

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

public class MainActivity extends Activity {

Button btnLogin;

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

btnLogin = (Button) findViewById(R.id.button1);

btnLogin.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,
FitBitActivity.class);
startActivity(intent);
}
});
}

}

And on FitBitActivity.java class-


private void login() {

try {

HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
HttpConnectionParams.setSoTimeout(httpParameters, 20000);
HttpClient client = new DefaultHttpClient(httpParameters);

HttpGet request = new HttpGet(
"http://api.fitbit.com/oauth/request_token?oauth_consumer_key=7af733f021f649bcac32f6f7a4fe2e9a&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1358921319&oauth_nonce=456236281&oauth_callback=http://androidhub4you.com/&oauth_version=1.0&oauth_token=5cefb18d2a80073520211f03f8d75321&oauth_signature=QdVUzMvT6tveGyoPu%2BEevzvo07s%3D");
response = client.execute(request);

BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));

String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.e("****Step 1***", "Webservice: " + webServiceInfo);
String result[]=webServiceInfo.split("=");
String result2 = result[1];
String result3[]=result2.split("&");
authToken = result3[0];
Log.e("Auth token:", "Webservice: " + authToken);

}

} catch (Exception e) {http://google.com/
// TODO: handle exception
e.printStackTrace();
}

}


DOWNLOAD FULL CODE HERE

Thanks!

Thursday, October 24, 2013

Android Printer Integration | Google Cloud Printing in Android Application | Printer demo in Android

Hello Dear Friends,

My this post is based on "How to Integrate printer in android app". the best way of doing that Google cloud printing. Google provide us Print Dialog code, we can use it in our application. Important steps are given below-

1)Login with your gamil-id in your desktop and add your printers in your browser.
2)Create a demo app and put below code.
3)Add Internet permissions and read storage.
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />





1)MainActivity.java
package com.manish.googleprintdemo;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
 *
 * @author manish
 *
 */

public class MainActivity extends Activity {
       Button btnPrint;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              btnPrint=(Button)findViewById(R.id.button1);
             
              btnPrint.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub

                            if (isNetworkAvailable() == false) {
                                         Toast.makeText(MainActivity.this,
                                                       "Network connection not available, Please try later",
                                                       Toast.LENGTH_SHORT).show();
                                  } else {
                                         File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/personal/xyz.pdf");
                                         Intent printIntent = new Intent(MainActivity.this, PrintDialogActivity.class);
                                         printIntent.setDataAndType(Uri.fromFile(file), "application/pdf");
                                         printIntent.putExtra("title", "Android print demo");
                                         startActivity(printIntent);
                                  }
                     }
              });
       }

       public boolean isNetworkAvailable() {

              ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo networkInfo = cm.getActiveNetworkInfo();
              // if no network is available networkInfo will be null
              // otherwise check if we are connected
              if (networkInfo != null && networkInfo.isConnected()) {
                     Log.e("Network Testing", "***Available***");
                     return true;
              }
              Log.e("Network Testing", "***Not Available***");
              return false;
       }

}

2)PrintDialogActivity.java

package com.manish.googleprintdemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class PrintDialogActivity extends Activity {
  private static final String PRINT_DIALOG_URL = "https://www.google.com/cloudprint/dialog.html";
  private static final String JS_INTERFACE = "AndroidPrintDialog";
  private static final String CONTENT_TRANSFER_ENCODING = "base64";

  private static final String ZXING_URL = "http://zxing.appspot.com";
  private static final int ZXING_SCAN_REQUEST = 65743;

  /**
   * Post message that is sent by Print Dialog web page when the printing dialog
   * needs to be closed.
   */
  private static final String CLOSE_POST_MESSAGE_NAME = "cp-dialog-on-close";

  /**
   * Web view element to show the printing dialog in.
   */
  private WebView dialogWebView;

  /**
   * Intent that started the action.
   */
  Intent cloudPrintIntent;

  @SuppressLint("JavascriptInterface") @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.print_dialog);
    dialogWebView = (WebView) findViewById(R.id.webview);
    cloudPrintIntent = this.getIntent();

    WebSettings settings = dialogWebView.getSettings();
    settings.setJavaScriptEnabled(true);

    dialogWebView.setWebViewClient(new PrintDialogWebClient());
    dialogWebView.addJavascriptInterface(
      new PrintDialogJavaScriptInterface(), JS_INTERFACE);

    dialogWebView.loadUrl(PRINT_DIALOG_URL);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == ZXING_SCAN_REQUEST && resultCode == RESULT_OK) {
      dialogWebView.loadUrl(intent.getStringExtra("SCAN_RESULT"));
    }
  }

  final class PrintDialogJavaScriptInterface {
    public String getType() {
      return cloudPrintIntent.getType();
    }

    public String getTitle() {
      return cloudPrintIntent.getExtras().getString("title");
    }

    public String getContent() {
      try {
        ContentResolver contentResolver = getContentResolver();
        InputStream is = contentResolver.openInputStream(cloudPrintIntent.getData());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[4096];
        int n = is.read(buffer);
        while (n >= 0) {
          baos.write(buffer, 0, n);
          n = is.read(buffer);
        }
        is.close();
        baos.flush();

        return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return "";
    }

    public String getEncoding() {
      return CONTENT_TRANSFER_ENCODING;
    }

    public void onPostMessage(String message) {
      if (message.startsWith(CLOSE_POST_MESSAGE_NAME)) {
        finish();
      }
    }
  }

  private final class PrintDialogWebClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      if (url.startsWith(ZXING_URL)) {
        Intent intentScan = new Intent("com.google.zxing.client.android.SCAN");
        intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE");
        try {
          startActivityForResult(intentScan, ZXING_SCAN_REQUEST);
        } catch (ActivityNotFoundException error) {
          view.loadUrl(url);
        }
      } else {
        view.loadUrl(url);
      }
      return false;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
      if (PRINT_DIALOG_URL.equals(url)) {
        // Submit print document.
        view.loadUrl("javascript:printDialog.setPrintDocument(printDialog.createPrintDocument("
          + "window." + JS_INTERFACE + ".getType(),window." + JS_INTERFACE + ".getTitle(),"
          + "window." + JS_INTERFACE + ".getContent(),window." + JS_INTERFACE + ".getEncoding()))");

        // Add post messages listener.
        view.loadUrl("javascript:window.addEventListener('message',"
            + "function(evt){window." + JS_INTERFACE + ".onPostMessage(evt.data)}, false)");
      }
    }
  }
}



3)activity_main.xml

<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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Print" />

</RelativeLayout>


4)print_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>


5)AndroidManifest.xml

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.googleprintdemo.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>
        <activity android:name=".PrintDialogActivity" />
    </application>

</manifest>




Thanks!