Wednesday, 21 February 2018

Notify When Network Data is Enable Or Disable

Hi friends, In this Post we'll learn how to get notify when Mobile Data or Wifi is Enable or Disable.
In this post we'll create a BroadcastReceiver to get notify is Data or wifi enable or disable. When the network state will change it will notify us.

Permissions Required

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

To create a BroadcastReceiver we have to create NetworkChangeReceiver.java class. In which we have to extends BroadcastReceiver class and Override it's method onReceive(). All the work will be done in this method.

Creating Receiver 

Open NetworkChangeReceiver.java and do the following changes
package com.minixithub.notifymobiledatatutorial;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/** * Created by Vishnu Kumar Soni on 22/01/2018. */
public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        Handler handler =new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ConnectivityManager connMgr = (ConnectivityManager) 
                    context.getSystemService(Context.CONNECTIVITY_SERVICE);

                android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                android.net.NetworkInfo mobile = 
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (wifi.isConnected() || mobile.isConnected()) {
                    // Do something
                    Toast.makeText(context,"Network Data is Enable",
Toast.LENGTH_LONG).show();
                    Log.d("Network Available ", "Network Data Enable");
                }else
                    Toast.makeText(context,"Network Data is Disable",
Toast.LENGTH_LONG).show();
            }
        },10000);
    }
}

Here we used Handler Object and display a Toast after 10 sec of broadcast receive. Because sometimes it takes time to Enable Network Data or Wifi after pressing button of Network data or Wifi.

Declaring Receiver in Manifest

Do the following changes in manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.minixithub.notifymobiledatatutorial">
    
    <!-- Adding Permission -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<!-- Notify When Mobile Data or Wifi state change -->
        <receiver android:name=".NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
</application>

</manifest>


Learn How To Implement Swipe To Refresh in Android

In this tutorial we'll learn how to implement SwipeRefreshLayout. Here we'll create a ListView and then implement Swipe To Refresh on that.

Below is the widget code for SwipeRefreshLayout
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipe">
</android.support.v4.widget.SwipeRefreshLayout>

Create a new Project in Android Studio and select EmptyActivity.

1. Open main_activity.xml and do the following changes
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipe"
    tools:context="com.minixithub.swipetorefreshtutorial.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:nestedScrollingEnabled="true"
            android:layout_height="match_parent">
</ListView>
    </LinearLayout>

</android.support.v4.widget.SwipeRefreshLayout>

2.Open MainActivity.java class and Implement the following code
package com.minixithub.swipetorefreshtutorial;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity 
    implements SwipeRefreshLayout.OnRefreshListener{

    private ListView listView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ArrayList<String> arrayList;
    private Context context;
    private ArrayAdapter<String>adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        arrayList = new ArrayList<>();
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe);
        listView = (ListView)findViewById(R.id.list);
        setRecordToListView();
        swipeRefreshLayout.setOnRefreshListener(this);
    }

    private void setRecordToListView()
    {
        for(int i = 0;i<10;i++){
            addNewRecord();
        }
        adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(adapter);

    }
//    Function to Add new Record
    private void addNewRecord(){
        int size = arrayList.size();
        String record = "Record No "+size+1;
        arrayList.add(0,record);
    }

    @Override
    public void onRefresh() {
//        Displaying Loader 
        swipeRefreshLayout.setRefreshing(true);
//        Creating Handler
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                addNewRecord();
//                Notifing The ListView
                adapter.notifyDataSetChanged();
                listView.deferNotifyDataSetChanged();
            }
        },2000);
//        Hiding the Loader
        swipeRefreshLayout.setRefreshing(false);
    }
}

Tuesday, 20 February 2018

How to Implement Notification in Android

Notification
notification is a message you can display to the user outside of your application's normal UI.   
In this tutorial we'll learn how to implement Notification in your app.Here we'll Popup a notification on Button Click
Create a new project in Android Studio
1. Open main_activity.xml and create a Button.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.minixithub.notificationturorial.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
2.Open MainAcitvity.java and create a method to Popup a Local Notification.
package com.minixithub.notificationturorial;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Context context;
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addNotification();
            }
        });
    }

//  Method To Display Notification
    private void addNotification(){
        NotificationCompat.Builder builder= new  NotificationCompat
               .Builder(context);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("TextNotification")
                .setContentText("This is Notification");
//        Creating Intent
        Intent intent = new Intent(context,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context,
                      0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
//        Adding Pending Intent to Builder
        builder.setContentIntent(pendingIntent);

//        Add Notification
        NotificationManager manager= (NotificationManager)
               context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0,builder.build());
    }
}

Thursday, 8 February 2018

How to implement WebView in Android

WebView is a view that displays web pages inside your application. WebView turns your application as a web application.

Below is the syntax for WebView

<WebView
       android:i"@+id/webview"
       andorid:layout_width="fill_parent"
       android:layout_height="fill_parent"
/>
In order to use WebView you have to get a reference of it in  java file. To get reference you have to make an Object of WebView class.

WebView webview = (WebView)findViewById(R.id.webview);

In Order to load a web url in webview you have to call loadUrl(String url) method of the WebView class.
webview.loadUrl("http://www.androidcooltech.blogspot.in/");

1. Open mainactivity.xml and write the below code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.minixithub.webviewtutorial.MainActivity">

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

    </WebView>
    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="35dp" 
        android:layout_height="35dp"
        app:layout_constraintTop_toBottomOf="parent"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintRight_toLeftOf="parent"
        app:layout_constraintLeft_toRightOf="parent"        />

</android.support.constraint.ConstraintLayout>
2. Open MainActivity.java and write the below code.
package com.minixithub.webviewtutorial;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private Activity activity;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        webView = (WebView)findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        progressBar = (ProgressBar)findViewById(R.id.progressbar);

        //      For Open webpage in WEBVIEW
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode,
                   String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//          Displaying Loading Bar on Page Load Start
                progressBar.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
//          Removing Loading on PageLoad Finish
              progressBar.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }
        });
//      Loading WebPage
        webView.loadUrl("http://androidcooltech.blogspot.in/");
    }
    @Override
    public void onBackPressed() {
//        Going Back to last WebPages on BackButton Pressed
        if(webView.canGoBack()){
            webView.goBack();
        }else
            super.onBackPressed();
    }
}
3. Open Mainfest.xml and add Internet Permission
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.minixithub.webviewtutorial">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>



Tuesday, 6 February 2018

How to create a service in android

What is Service

Service is a component which run in background to perform long term operations. Service has no user interface.As service has no user interface it is not bound to life cycle of Activity.
Services are used for repetitive and potentially long operations. Internet downloads, checking for new data, data processing, updating content providers and the like.
In this tutorial we'll learn how to create and implement a service.

1. Create Service Class
Create a class named ServiceTest.java and use below code. It has to extends Service Class or one of it's child class.
ServiceTest.java
package com.example.servicetutorial;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/** * Created by Vishnu Kumar Soni on 2/6/2018. */
public class Servicetest extends Service{

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, 
        int flags, int startId) {
        Toast.makeText(getApplicationContext(),
        "Service Started",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override    public void onDestroy() {
    Toast.makeText(getApplicationContext(),
    "Service Stopped",Toast.LENGTH_LONG).show();

    }
}

2. Declaring Service In Manifest
It is must to declare Service class in Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicetutorial">
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
<service
            android:name=".Servicetest"
            android:label="TextService">
        </service>
</application>

</manifest>
3. Creating Main Activity
Do the following changes in activity_main.xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.servicetutorial.MainActivity"
    android:orientation="vertical"    android:gravity="center">

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"/>
    <Button
        android:id="@+id/end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="End Service"/>
</LinearLayout>


Now open MainActivity.java and do the following chages.
MainActivity.java
package com.example.servicetutorial;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        Button buttonStart = (Button)findViewById(R.id.start);
        Button buttonend = (Button)findViewById(R.id.end);
        buttonend.setOnClickListener(this);
        buttonStart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(context,Servicetest.class);
        if(v.getId()==R.id.start)
        {
            startService(intent);
        }else if(v.getId() ==R.id.end){
            stopService(intent);
        }

    }
}