[Tutorial] Learn to use WebSockets on Android with OkHttp - Android Software Development

Hello,
I create that post to present you a tutorial aiming to learn you to use WebSockets on Android with OkHttp. Like you should know, WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. It is supported in HTML 5. Since the version 3.5 of the OkHttp library, you can also use WebSockets connection in your Android applications. In this tutorial, you are going to learn how to create a simple chat application with the Echo WebSocket Server which is available at the following address : http://www.websocket.org/echo.html .
Note that you can also discover this tutorial in video on Youtube :
First step is to add the OkHttp dependency in your Gradle build file
Code:
compile 'com.squareup.okhttp3:okhttp:3.6.0'
Don’t forget to add the Internet permission in your Android manifest since the application will use the network to create a WebSocket connection to the Echo WebSocket server. For this tutorial, we will need a simple layout with a Button to start the connection and the exchange with the server and a TextView which will be used as a console output for the messages received from the server :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="com.ssaurel.websocket.MainActivity">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Start !"
android:layout_marginTop="40dp"
android:textSize="17sp"/>
<TextView
android:id="@+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/start"
android:layout_centerHorizontal="true"
android:textSize="16sp"
android:layout_marginTop="30dp"/>
</RelativeLayout>
Then, we can write the Java code of the application. The main part will be the method used to create the connection to the WebSocket connection and the WebSocketListener object used to exchange with the server :
Code:
private final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello, it's SSaurel !");
webSocket.send("What's up ?");
webSocket.send(ByteString.decodeHex("deadbeef"));
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
output("Receiving : " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
output("Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
}
We send messages to the server in the onOpen method. The messages received from the Echo WebSocket server are displayed inside the onMessage method. Note that you can send text or hexadecimal messages. Lastly, we close the connection by using the close method of the WebSocket object. To create the WebSocket connection with OkHttp, we need to build a Request object with the URL of the Echo WebSocket server in parameter, then calling the newWebSocket method of the OkHttpClient object.
The code will have the following form :
Code:
package com.ssaurel.websocket;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public class MainActivity extends AppCompatActivity {
private Button start;
private TextView output;
private OkHttpClient client;
private final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello, it's SSaurel !");
webSocket.send("What's up ?");
webSocket.send(ByteString.decodeHex("deadbeef"));
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
output("Receiving : " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
output("Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start);
output = (TextView) findViewById(R.id.output);
client = new OkHttpClient();
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start();
}
});
}
private void start() {
Request request = new Request.Builder().url("ws://echo.websocket.org").build();
EchoWebSocketListener listener = new EchoWebSocketListener();
WebSocket ws = client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
}
private void output(final String txt) {
runOnUiThread(new Runnable() {
@Override
public void run() {
output.setText(output.getText().toString() + "\n\n" + txt);
}
});
}
}
Finally, you have just to run your application and enjoy the result :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Don't hesitate to give it a try and give me your feedbacks.
Thanks.
Sylvain

Hi want to fetch data on my Android app from bitfinex websocket api. Can you explain how to do it here? In detail would be great and if you don't have time, some general advice would be appreciated too.
Thank you

Related

[GUIDE][UP] How to easly Implement J.W. ViewPagerIndicator + transitions [SAMPLE APP]

IF YOU MAKE USE OF THIS GUIDE AND YOU WILL MAKE PUBLIC YOUR APPLICATION, PLEASE THANK THE OP AND GIVE ME & ENRICOCID CREDITS/MENTION . THANK YOU
1) Set Up Jake Wharton ViewPagerIndicator
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
​
IF YOU WANNA DOWNLOAD MY SAMPLE APP GO HERE:
http://forum.xda-developers.com/showpost.php?p=45742129&postcount=4​
SITE>>>http://viewpagerindicator.com/<<<SITE​
1 - Download JakeWharton ViewPagerIndicator:
​
Download from here: JakeWharton ViewPagerIndicator download
Or from the website: http://viewpagerindicator.com/
2 - OPEN ECLIPSE
First you need to extract "library" folder from the zip and save it in your documents folder, like the picture below:
Now drag & drop "library" folder to your Documents directory:
- Import downloaded ViewPagerIndicator Library to your workspace:
GO TO FILE > NEW > OTHER > ANDROID > ANDROID PROJECT FROM EXISTING CODE:
- Click next button and browse directory (1) to select the downloaded ViewPagerIndicator Library (2):
(1) CLICK BROWSE...
(2) AND SELECT "LIBRARY" FOLDER, GO TO Libraries > My Documents > Library, click OK.
Now give a name to this project (for example "ViewPagerIndicator") and check "Copy project into workspace", like the picture:
Click "Finish"
If you like my work don't Forget To Hit Thanks, five star
:good: or offer me a beer :good:
​
Make a donation​
2) How to load VievPagerIndicator to Your Project​
- Create a new Android Application Project:
- Give a name to your project (for example "ViewPagerTest"), like the picture below:
​
- Go next and click finish to create the project
​
- Now navigate to your project properties:
- Go to Android and Click "Add" to load the library into your project:
​
You will receive an error:
To fix this error you have two options:
- 1) delete the libs folder of your project:
- 2) [RECOMENDED]The best way is to copy the android-support-v4.jar from sdk/extras/android/support/v4 to your workspace/ViewPagerIndicator/libs folder, without deleting libs folder of your project!!!
If you have other errors like this:
go to ViewPagerIndicator properties and change the "Project Build Target". This must be equal to that of the ViewPagerTest project:
---------- Post added at 08:28 PM ---------- Previous post was at 08:27 PM ----------​
3) Create Layouts ​
Blue = Add
Red = Delete
- Now go to res > layout
and edit activity_main.xml deleting the entire code:
Code:
[COLOR="red"]<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>[/COLOR]
Copy & paste the code below to your activity_main.xml
Code:
[COLOR="Blue"]<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/indicator"
android:padding="10dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000000"
android:textColor="#2FB3E3"
app:footerColor="#2FB3E3"
app:footerLineHeight="1dp"
app:footerIndicatorHeight="3dp"
app:footerIndicatorStyle="underline"
app:selectedColor="#FFFFFF"
app:selectedBold="true"
/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>[/COLOR]
Now create new .xml files in your layout folder (I will create 3 layouts for example). Go to New > other
and select "Android XML file":
​
Give a name to your xml file (for example "layout1") and select linear layout, click finish. See the picture:
Create two other layouts and call them "layout2" and "layout3":
4)Implement ViewPager using fragments ​
Blue = Add
Red = Delete
Now go to src > com.example.viewpagertest and edit MainActivity.java
Delete the content marked in red:
Code:
[COLOR="Blue"]package com.example.viewpagertest;[/COLOR]
[COLOR="Red"]import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
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;
}
}[/COLOR]
and add the following code:
Code:
[COLOR="blue"]import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
[user=439709]@override[/user]
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;
}
}[/COLOR]
The result:
Code:
package com.example.viewpagertest;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
[user=439709]@override[/user]
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;
}
}
Now you have to create three fragments into src > com.example.viewpagertest folder:
- go to new > other:
and create three classes named "FirstActivity", "SecondActivity" and "ThirdActivity" like the picture below:
Now edit FirstActivity.java in src > com.example.viewpagertest folder and delete the red code:
Code:
[COLOR="Blue"]package com.example.viewpagertest;[/COLOR]
[COLOR="Red"]public class FragmentAdapter {
}[/COLOR]
and add the following code:
Code:
package com.example.viewpagertest;
[COLOR="Blue"]import com.example.viewpagertest.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstActivity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout1, null);
return v;
}
}
[/COLOR]
For the SecondActivity class:
Code:
package com.example.viewpagertest;
import com.example.viewpagertest.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SecondActivity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout2, null);
return v;
}
}
For the ThirdActivity class:
Code:
package com.example.viewpagertest;
import com.example.viewpagertest.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ThirdActivity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout3, null);
return v;
}
}
Now we need to create a new class called "FragmentAdapter.java" into src > com.example.viewpagertest folder:
- go to new > other:
and create a new class called "FragmentAdapter" like the pictures:
click finish.
Now edit the FragmentAdapter.java in src > com.example.viewpagertest folder and delete the red code:
Code:
[COLOR="Blue"]package com.example.viewpagertest;[/COLOR]
[COLOR="Red"]public class FragmentAdapter {
}[/COLOR]
and add the following code:
Code:
package com.example.viewpagertest;
[COLOR="blue"]import com.viewpagerindicator.IconPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatPagerAdapter;
public class FragmentAdapter extends FragmentStatPagerAdapter implements IconPagerAdapter{
public FragmentAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
[user=439709]@override[/user]
public int getIconResId(int index) {
// TODO Auto-generated method stub
return 0;
}
[user=439709]@override[/user]
public Fragment getItem(int position)
{
// TODO Auto-generated method stub
Fragment fragment = new FirstActivity();
switch(position){
case 0:
fragment = new FirstActivity();
break;
case 1:
fragment = new SecondActivity();
break;
case 2:
fragment = new ThirdActivity();
break;
}
return fragment;
}
[user=439709]@override[/user]
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
[user=439709]@override[/user]
public CharSequence getPageTitle(int position){
String title = "";
switch(position){
case 0:
title = "First";
break;
case 1:
title = "Second";
break;
case 2:
title = "Third";
break;
}
return title;
}
}[/COLOR]
Save the entire project! Enjoy your App!!!
SAMPLE APP:
>>>DOWNLOAD<<<​
JAKE WHARTON VIEW PAGER INDICATOR GITHUB:
https://github.com/JakeWharton/Android-ViewPagerIndicator​
CREDITS:
- me
- enricocid
- Jake Warthon
Thanks to Xda!
ivn888 said:
CREDITS:
- me
- enricocid
- Jake Warthon
Thanks to Xda!
Click to expand...
Click to collapse
grandi ,ottimo lavoro
Awesome!! I badly needed this.. Thanks for the guide
Suppose I want to add pics and some strings for each layout, how do I do that?? Can you give an example for this also..?? thanks
rakz992 said:
Awesome!! I badly needed this.. Thanks for the guide
Suppose I want to add pics and some strings for each layout, how do I do that?? Can you give an example for this also..?? thanks
Click to expand...
Click to collapse
You can use the ImageView to display images in your Application.There are many different configuration options and many screens from different devices that you should take into account. I write a little guide using my viewer app.
EXAMPLE:
First to use imageview you have to add resources, in Eclipse navigate to res/values/strings.xml.
Edit the strings.xml
This is the content of string.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ViewPagerTest</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
Add the following string:
Code:
[COLOR="Blue"]<string name="content">image</string>[/COLOR]
Like this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ViewPagerTest</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
[COLOR="blue"]<string name="content">image</string>[/COLOR]
</resources>
Now you have to add a picture in the appropriate project folder, as you would have noticed there are 5 folders that contain the image resources of the project :
res/drawable-hdpi
res/drawable-ldpi
res/drawable-mdpi
res/drawable-xhdpi
res/drawable-xxhdpi
You can copy the images you want to put in you’re application in any one of these folders. Android SDK will automatically recognize any images you put on any one of these folders as drawable resources. Refer to official Android’s Drawable Resource and Screen Support to understand of how image works in Android.
Inside these folder there are default project .pngs. Now i use them to show you on how to add pict. The pictures are named ic_launcher.png
Now open layout1.xml
This is the blank layout:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
and add the following code:
Code:
[COLOR="Blue"]<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />[/COLOR]
Like this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
[COLOR="blue"]<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />[/COLOR]
</LinearLayout>
Now you may open the Graphical layout editor to preview your UI:
--------------------------------------------------------------------------------------------------------------
1) Resources: string.xml, <string name="content">image</string>
2) Your_image
3) Use imageview to image to your layout:
<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/Your_image" />[/COLOR]
@ivn888: We cannot see your pictures. You ran out of bandwidth.
nikwen said:
@ivn888: We cannot see your pictures. You ran out of bandwidth.
Click to expand...
Click to collapse
we are working to fix this problem... thanks
bro another help here
i want to add Zoom-out page transformer animation for slide from one layout to other..
should i replace mAdapter with this
pager.setPageTransformer(true, new ZoomOutPageTransformer());
can you help me on how to do it ?
thank you
rakz992 said:
bro another help here
i want to add Zoom-out page transformer animation for slide from one layout to other..
should i replace mAdapter with this
pager.setPageTransformer(true, new ZoomOutPageTransformer());
can you help me on how to do it ?
thank you
Click to expand...
Click to collapse
Tomorrow i will release a short guide on how to add this animation...
ivn888 said:
Tomorrow i will release a short guide on how to add this animation...
Click to expand...
Click to collapse
:highfive:
ivn888 said:
Tomorrow i will release a short guide on how to add this animation...
Click to expand...
Click to collapse
Thanks a lot
Customize the Animation with PageTransformer - How to add Zoom-out page transformer
Reference here: http://developer.android.com/training/animation/screen-slide.html#pagetransformer
- What you need:
- NineOldAndroids library:
>>>Download here<<<
Site>>>http://nineoldandroids.com/<<<Site
- ZoomOutPageTransformer.java
>>>Download here<<<​
1) First you need to extract "library" folder from the zip and save it in your documents folder, like the picture below:
2) Now drag & drop "library" folder to your Documents directory,i will rename it "library_1":
3) Import downloaded NineOld Library to your workspace:
GO TO FILE > NEW > OTHER > ANDROID > ANDROID PROJECT FROM EXISTING CODE
4) Click next button and browse directory to select the downloaded Library:
(1) CLICK BROWSE...
(2) AND SELECT "LIBRARY" FOLDER, GO TO Libraries > My Documents > Library_1, click OK.
5) Now give a name to this project (for example "Library_1 or "NineOld") and check "Copy project into workspace"
follow the first post to understand "how import libs": http://forum.xda-developers.com/showpost.php?p=45742000&postcount=1
EXAMPLE APP:
Copy the ZoomOutPageTransformer.java to your src/com.example.viewpagertest/ folder or create a class named ZoomOutPageTransformer:
Code:
package com.example.viewpagertest;
import android.support.v4.view.ViewPager.PageTransformer;
import android.view.View;
[COLOR="green"]import com.nineoldandroids.view.ViewHelper;[/COLOR]
public class ZoomOutPageTransformer implements PageTransformer {
private static float MIN_SCALE = 0.85f;
private static float MIN_ALPHA = 0.5f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
[COLOR="green"]ViewHelper[/COLOR].setAlpha(view, 0);
} else if (position <= 1) { // [-1,1]
// Modify the default slide transition to shrink the page as well
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
[COLOR="green"]ViewHelper[/COLOR].setTranslationX(view, horzMargin - vertMargin / 2);
} else {
[COLOR="green"]ViewHelper[/COLOR].setTranslationX(view, -horzMargin + vertMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
[COLOR="green"]ViewHelper[/COLOR].setScaleX(view, scaleFactor);
[COLOR="green"]ViewHelper[/COLOR].setScaleY(view, scaleFactor);
// Fade the page relative to its size.
[COLOR="green"]ViewHelper[/COLOR].setAlpha(view, MIN_ALPHA +
(scaleFactor - MIN_SCALE) /
(1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
[COLOR="green"]ViewHelper[/COLOR].setAlpha(view, 0);
}
}
}
If you have deleted the "libs" folder of your project, go to workspace/ViewPagerTest/ make a new folder called "libs" and put the android-support-v4.jar (you will find it in sdk/extras/android/support/v4 folder), copy the same file (android-support-v4.jar) in workspace/ViewPagerIndicator/libs folder.
Now go to library_1 options and check the correct project build target and "Is library":
Load the library into your project.
THE CODE​
blue = add
red = delete
Now i will make an xml file called "colors" in res/values folder:
Code:
[COLOR="Blue"]<?xml version="1.0" encoding="UTF-8"?>
<resources>
<color name="red">#F75D59</color>
<color name="blue">#0000FF</color>
<color name="orange">#dc5a1e</color>
</resources>[/COLOR]
add the following code to layout1:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[COLOR="blue"]android:background="@color/red"[/COLOR]>
</LinearLayout>
layout2:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[COLOR="blue"]android:background="@color/blue" >[/COLOR]
</LinearLayout>
layout3:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[COLOR="blue"]android:background="@color/orange">[/COLOR]
</LinearLayout>
Now open the MainActivity.java:
Code:
package com.example.viewpagertest;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
[user=439709]@override[/user]
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;
}
}
and add the blue lines like this:
Code:
package com.example.viewpagertest;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
[COLOR="blue"]mPager.setPageTransformer(true, new ZoomOutPageTransformer ());[/COLOR]
}
[user=439709]@override[/user]
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;
}
}
ZoomOutPageTransformer example app - ViewPagerTest+zoomout.apk
>>>DOWNLOAD ZoomOutPageTransformer example app here <<<​​
If you wanna try other animations please go here: http://developer.android.com/training/animation/screen-slide.html
or use other libs like transitionviewpager and JazzyViewPager
Using DepthPageTransformer
Create a class called DepthPageTransformer in src/.../ folder and add the following:
Code:
package com.example.viewpagertest;
import android.support.v4.view.ViewPager.PageTransformer;
import android.view.View;
//import com.nineoldandroids.view.ViewHelper;
public class DepthPageTransformer implements PageTransformer {
private static float MIN_SCALE = 0.75f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
} else if (position <= 1) { // (0,1]
// Fade the page out.
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
// Scale the page down (between MIN_SCALE and 1)
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
In your MainActivity.java add the blue code:
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
[COLOR="Blue"] mPager.setPageTransformer(true, new DepthPageTransformer ());[/COLOR]
...
...
}
How to use addPreferencesFromResource(R.xml.preferences); in these fragments with action bar sherlock? I tried to make work, but... But implented ABS in my app.
ivn888 said:
4)Implement ViewPager using fragments code:
[package com.example.viewpagertest;
[import com.viewpagerindicator.IconPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatPagerAdapter;
public class FragmentAdapter extends FragmentStatPagerAdapter implements IconPagerAdapter{
Click to expand...
Click to collapse
its FragmentStatePagerAdapter (instead of FragmentStatPagerAdapter) and Override (instead of override)
i think u made these two small mistakes. bt the tutorial is awesome.. was looking for this

[GUIDE][NOOB Friendly][HOW-TO]Simple Calculator App

HOW-To Make A Simple Android Calculator​
How To Make A Simple Calculator
Step 1
. Select Create New Android Application
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Creating XML For Layout
To create a calculator first we need to create the layout of the calculator.
Layout is created using XML file given below
Copy This To Your “activity_main” (Note- If you named the layout activity main or something else please change it to activity_main or it will give a couple of errors)
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" >
<EditText
android:id="@+id/result_id"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
<Button
android:id="@+id/Btn7_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:text="7"
android:onClick="btn7Clicked"
/>
<Button
android:id="@+id/Btn8_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn7_id"
android:text="8"
android:onClick="btn8Clicked"
/>
<Button
android:id="@+id/Btn9_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn8_id"
android:text="9"
android:onClick="btn9Clicked"
/>
<Button
android:id="@+id/Btnclear_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn9_id"
android:text="clear"
android:onClick="btnclearClicked"
/>
<Button
android:id="@+id/Btn4_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn7_id"
android:text="4"
android:onClick="btn4Clicked"
/> <Button
android:id="@+id/Btn5_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn8_id"
android:layout_toRightOf="@id/Btn4_id"
android:text="5"
android:onClick="btn5Clicked"
/> <Button
android:id="@+id/Btn6_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn9_id"
android:layout_toRightOf="@id/Btn5_id"
android:text="6"
android:onClick="btn6Clicked"
/>
<Button
android:id="@+id/Btnplus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnclear_id"
android:layout_toRightOf="@id/Btn6_id"
android:text="+"
android:onClick="btnplusClicked"
/>
<Button
android:id="@+id/Btn1_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn4_id"
android:text="1"
android:onClick="btn1Clicked"
/>
<Button
android:id="@+id/Btn2_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn5_id"
android:layout_toRightOf="@id/Btn1_id"
android:text="2"
android:onClick="btn2Clicked"
/>
<Button
android:id="@+id/Btn3_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn6_id"
android:layout_toRightOf="@id/Btn2_id"
android:text="3"
android:onClick="btn3Clicked"
/>
<Button
android:id="@+id/Btnminus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnplus_id"
android:layout_toRightOf="@id/Btn3_id"
android:text="-"
android:onClick="btnminusClicked"
/>
<Button
android:id="@+id/Btnequal_id"
android:layout_width="110dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:text="="
android:onClick="btnequalClicked"
/>
<Button
android:id="@+id/Btndivide_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:layout_toRightOf="@id/Btnequal_id"
android:text="/"
android:onClick="btndivideClicked"
/>
<Button
android:id="@+id/Btnmulti_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnminus_id"
android:layout_toRightOf="@id/Btndivide_id"
android:text="*"
android:onClick="btnmultiClicked"
/>
</RelativeLayout>
The Graphical Layout Will look Like this
Then You have to Make The Buttons work and calculate your numbers
Simply find your MainActivity.java (It Is place under package name)
Copy This to your java file :
Code:
package com.dc.simplecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public String str ="";
Character op = 'q';
int i,num,numtemp;
EditText showResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showResult = (EditText)findViewById(R.id.result_id);
}
public void btn1Clicked(View v){
insert(1);
}
public void btn2Clicked(View v){
insert(2);
}
public void btn3Clicked(View v){
insert(3);
}
public void btn4Clicked(View v){
insert(4);
}
public void btn5Clicked(View v){
insert(5);
}
public void btn6Clicked(View v){
insert(6);
}
public void btn7Clicked(View v){
insert(7);
}
public void btn8Clicked(View v){
insert(8);
}
public void btn9Clicked(View v){
insert(9);
}
public void btnplusClicked(View v){
perform();
op = '+';
}
public void btnminusClicked(View v){
perform();
op = '-';
}
public void btndivideClicked(View v){
perform();
op = '/';
}
public void btnmultiClicked(View v){
perform();
op = '*';
}
public void btnequalClicked(View v){
calculate();
}
public void btnclearClicked(View v){
reset();
}
private void reset() {
// TODO Auto-generated method stub
str ="";
op ='q';
num = 0;
numtemp = 0;
showResult.setText("");
}
private void insert(int j) {
// TODO Auto-generated method stub
str = str+Integer.toString(j);
num = Integer.valueOf(str).intValue();
showResult.setText(str);
}
private void perform() {
// TODO Auto-generated method stub
str = "";
numtemp = num;
}
private void calculate() {
// TODO Auto-generated method stub
if(op == '+')
num = numtemp+num;
else if(op == '-')
num = numtemp-num;
else if(op == '/')
num = numtemp/num;
else if(op == '*')
num = numtemp*num;
showResult.setText(""+num);
}
}
Next Step!
Testing Your App, Fingers Crossed
Simply Click On Run>Run As Android Application
Congo! You Just Made A Simple Calc App……
Exporting Your App
Open Android Manifest.xml
Select use Export Wizard
That’s All….
If you have any queries post in this thread I will try my best to solve it…
Sucess!
Have A Good Day!
​
Reserved

[Q] Same shell command works from console and doesn't work from Activity

//sorry for my english, if any
Hi. I'm using AIDE right on my device (Xperia NeoV, 4.1.B.0.587, root)
And i'm trying to inject key events through the same shell command:
"input keyevent 25" via "su", both in AIDE Console and separated Activity.
//volume-down key is not my target, just good for tests. I've tried different keys, same result.
Part of the code:
Code:
try {
java.lang.Process p = Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("input keyevent 25\n");
dos.flush();
} catch (IOException ex) {
//log any errors
}
So, when it goes in AIDE ConsoleApp - it pushes down volume.
But when it executes from my Activity - nothing happens (no error messages in log, dos != null);
Maybe there should be some specific permission on manifest?
"android.permission.ACCESS_SUPERUSER" - no changes.
Maybe there should be some trick in code? Or(and?) i'm very stupid. Also, maybe somewhere a whole listing of _simple_ keyInjection project exists?
I managed to solve it already. I'm using this class now:
public void RunAsRoot(String[] cmds){
Process p = null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
try {
os.writeBytes(tmpCmd+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.writeBytes("exit\n");
} catch (IOException e) {
e.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Then simply call it via
String[] commands = {"command1", "command2", "command3", ...};
RunAsRoot(commands);
Click to expand...
Click to collapse
Thanks anyways!
Click to expand...
Click to collapse
Credits: @KrauseDroid
Our original thread i took it from:
http://forum.xda-developers.com/showthread.php?t=2725173
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
Credits: @KrauseDroid
Our original thread i took it from:
http://forum.xda-developers.com/showthread.php?t=2725173
Click to expand...
Click to collapse
I saw that thread before creating own, and tried solutions from it. They works same way - only from ConsoleApp in AIDE.
Also, last method is the same as I'm already using, but I've tried to copy code in project - no progress.
In addition:
- superuser rights granted to both.
- test "ls" command put into dos object gives me same list of current dir in both projects, so commands seems to run.
Listing:
MainActivity:
Code:
package com.tsk.mk;
import android.app.*;
import android.content.*;
import android.os.*;
import android.widget.*;
import java.io.*;
public class MainActivity extends Activity {
public static TextView logView;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
logView = (TextView) findViewById(R.id.log);
log("creating sercice");
final MainActivity me = this;
new Thread() {
[user=439709]@override[/user]
public void run() {
log("thread.run");
startService(new Intent(me, MissedKeysService.class));
log("thread: service shoul'd be created");
}
}.start();
log("end of MA.onCreate method");
}
static void log(String message) {
logView.setText(logView.getText() + "\n" + message);
}
}
MissedKeysService:
Code:
package com.tsk.mk;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import java.io.*;
public class MissedKeysService extends Service {
private WindowManager windowManager;
private MissedKeysView mkv;
private WindowManager.LayoutParams params;
private DataOutputStream dos;
[user=439709]@override[/user]
public IBinder onBind(Intent intent) {
MainActivity.log("onBind called o_o");
return null;
}
[user=439709]@override[/user]
public void onCreate() {
MainActivity.log("Service.onCreate");
super.onCreate();
try {
java.lang.Process p = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(p.getOutputStream());
} catch (IOException ex) {
MainActivity.log(ex.getMessage());
dos = null;
}
windowManager = (WindowManager)
getSystemService(WINDOW_SERVICE);
mkv = new MissedKeysView(this, this);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
params.width = MissedKeysView.keySize;
params.height = MissedKeysView.keySize;
windowManager.addView(mkv, params);
MainActivity.log("Service started");
}
[user=439709]@override[/user]
public void onDestroy () {
super.onDestroy ();
if (mkv != null) windowManager.removeView(mkv);
MainActivity.log("Ssrvice is ended");
}
public void extend(boolean state) {
params.height = mkv.keySize * (state ? MissedKeysView.keys : 1);
windowManager.updateViewLayout(mkv, params);
}
public void sendKey(int code) {
if (dos == null) MainActivity.log("dos is null");
try {
dos.writeBytes("input keyevent " + code + "\n");
dos.flush();
MainActivity.log("" + code);
} catch (IOException e) {
MainActivity.log("wtf?");
}
}
}
MissedKeysView:
Code:
package com.tsk.mk;
import android.content.*;
import android.graphics.*;
import android.view.*;
import android.view.View.*;
import java.io.*;
public class MissedKeysView extends View
implements OnTouchListener {
final static int keySize = 64;
final static String[] labels = {":", "+", "-", "^", "v", "o", "<", ">"};
final private int[] codes = {-1, 24, 25, 19, 20, 23, 21, 22};
final static int keys = 3; //max shown keys
MissedKeysService mks;
Paint bgP; //background
Paint hbgP; //highlighted bg
Paint tP; //text
int selected = -1; //active key
public MissedKeysView(Context context, MissedKeysService mks) {
super(context);
this.mks = mks;
bgP = new Paint();
bgP.setARGB(64, 128, 128, 128);
hbgP = new Paint();
hbgP.setARGB(64, 255, 128, 0);
tP = new Paint();
tP.setARGB(128, 255, 255, 255);
tP.setTextSize(keySize);
tP.setTextAlign(Paint.Align.CENTER);
setOnTouchListener(this);
}
[user=439709]@override[/user]
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(int i=0; i<getHeight()/keySize; i++) {
canvas.drawCircle(keySize/2,
keySize/2 + i*keySize, keySize/2,
(i == selected ? hbgP : bgP));
canvas.drawText(labels[i], keySize/2, i*keySize + keySize*3/4, tP);
}
}
[user=439709]@override[/user]
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
selected = (int) (event.getY()/keySize);
if (selected == 0) mks.extend((int) getHeight() <= keySize);
else mks.sendKey(codes[selected]);
break;
case MotionEvent.ACTION_UP:
selected =-1;
}
invalidate();
return super.onTouchEvent(event);
}
}
AndroidManifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsk.mk"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="11" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
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=".MissedKeysService"
android:exported="true" >
</service>
</application>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<uses-permission android:name="android.permission.INJECT_EVENTS" />
</manifest>
@Torsionick do you have the permission INJECT_EVENTS
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
@Torsionick do you have the permission INJECT_EVENTS
Click to expand...
Click to collapse
Thanks for participating in solving.
The reason was somewhere else - after executing "export LD_LIBRARY_PATH=/system/lib" all works fine. Thread is over.

[Tutorial] Learn to parse HTML Pages on Android with JSoup

Hello,
I create that thread to offer you a tutorial learning you to parse HTML pages on Android by using the JSoup Library. You can also discover this tutorial in video on Youtube :
When you make Android applications, you can have to parse HTML data or HTML pages got from the Web. One of the most known solution to make that in Java is to use JSoup Library. Like said on the official website of JSoup : "It is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods."
JSoup can be used in Android applications and we're going to study how to parse an HTML Page on Android with JSoup.
First, you need to add the JSoup dependency in your Gradle build file :
Code:
compile 'org.jsoup:jsoup:1.10.1'
For our example, we are going to download the content of the SSaurel's Blog and display all the links of the main page. To download the content of a website, JSoup offers the connect method and then a get method. This last method works synchronously. So, we should call these methods in a separated Thread. Our application will have just a simple layout with a Button to launch the download of the website and a TextView to display the links.
It will have the following form :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="com.ssaurel.jsouptut.MainActivity">
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get website"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result ..."
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:layout_below="@id/getBtn"
android:textSize="17sp"/>
</RelativeLayout>
In the main Activity of the application, we are going to get instances of the Button and the TextView from our layout. Then, we set a click listener on the Button to start the download of the website when the user will click it.
In the getWebsite() method, we create a new Thread to download the content of the website. We use the connect() method of the Jsoup object to connect the application to the website, then we call the get() method to download the content. These calls return a Document object instance. We have to call the select() method of this instance with the query to get all the links of the content. This query returns an Elements instance and finally, we have just to iterate on the elements contained in this object to display the content of each link to the screen.
At the end of our separated Thread, we refresh the UI with the links got from the website. This refresh is embedded inside a runOnUiThread call because it's forbidden to refresh the UI elements inside a separated thread.
The code of the MainActivity has the following form :
Code:
package com.ssaurel.jsouptut;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getWebsite();
}
});
}
private void getWebsite() {
new Thread(new Runnable() {
@Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
String title = doc.title();
Elements links = doc.select("a[href]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("href"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
}
Last step is to run the application and to enjoy the final result with all the links of the SSaurel's blog displayed on the screen :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Don't hesitate to try JSoup on your Android application and give me your feedbacks on this tutorial.
Thanks.
Sylvain

[Tutorial][APP] Split Shortcuts | How to Open Two Apps in Split Screen [API 24+]

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Split-Screen Or Multi-Window introduced on Android 7 (API 24) for All Android devices.
Samsung added new Software features on Galaxy Note 8 that allows users to select pair of apps to open in simultaneously in split screen. Check it out
This Tutorial is about How to create an app to open two apps in multi-window mode.
Click to expand...
Click to collapse
But If you want to configure your current app to support multi-window you need to read this documentation.
Android 7.0 adds support for displaying more than one app at the same time. On handheld devices, two apps can run side-by-side or one-above-the-other in split-screen mode. On TV devices, apps can use picture-in-picture mode to continue video playback while users are interacting with another app.
If your app targets Android 7.0 (API level 24) or higher, you can configure how your app handles multi-window display. For example, you can specify your activity's minimum allowable dimensions. You can also disable multi-window display for your app, ensuring that the system only shows your app in full-screen mode.
Read More
Click to expand...
Click to collapse
# Let Start #​
What do you need to get started...
- Know How to Create Hello World Project
- Basic Info about Android Apps Files (.Java, .xml)/Components (Activity, Service)
Click to expand...
Click to collapse
What will you learn...
- Create & Configure AccessibilityService
- Create with custom BroadcastReceiver
Click to expand...
Click to collapse
- Right Click on package name of app & Create a Java Class for AccessibilityService
Code:
public class [COLOR="royalblue"]SplitScreenService [/COLOR]extends [B]AccessibilityService [/B]{
@Override
protected void onServiceConnected() {
System.out.println("onServiceConnected");
//system will call this whenever you turn on Accessibility for this app
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
switch (event.getEventType()){
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
//this is a sample event that you can perform some action whenever it called
//and i will create split-screen here
[COLOR="DarkRed"]performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);[/COLOR]
//this is how you can enter split-screen mode
break;
}
}
@Override
public void onInterrupt() {
System.out.println(">>> onInterrupt");
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
}
@Override
public void onDestroy(){
super.onDestroy();
}
}
- Right Click on /res/... folder, create another folder and name it xml then you will have /res/xml/...
Then right click on /xml/... folder and create an xml file and choose a name (split.xml)
This xml file contains configuration of AccessibilityService.
Code:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="[COLOR="red"]typeAllMask[/COLOR]" // all mask means to get all event which most of time you don't need it.
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagRetrieveInteractiveWindows|flagDefault"
android:settingsActivity="com.example.android.globalactionbarservice"
android:description="@string/describe_what_will_you_do" //here you must describe to user what will you do with this special permission />
- Open AndroidManifest.xml to define AccessbilityService & Add required permissions
Inside <application/> tag add this.
Code:
<service
android:name="com.example.android.split.SplitScreenService" //change it to your package name and class
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/split"/> //add name of configuration file split.xml
</service>
Note that this app will only work when user enables Accessibility for it manually.
So first thing on Main Activity of the app must be to check this and redirect users to Accessibility Setting.
Open Main Activity of app and @oncreate() add this
Code:
final AccessibilityManager accessibilityManager = (AccessibilityManager)getSystemService(ACCESSIBILITY_SERVICE);
if([COLOR="Red"]!accessibilityManager.isEnabled()[/COLOR]){
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
return;
}
after this app should enter split-screen & try to open another apps inside split-screen.
that s why I set BroadcastReceiver to send proper action in right time after entering split-screen mode.
So to perform this app must have proper BroadcastReceiver & AccessibilityEvent listener.
//Custom BroadcastReceiver in activity
Code:
@Override
protected void onCreate(Bundle Saved){
super.onCreate(Saved);
final AccessibilityManager accessibilityManager = (AccessibilityManager)getSystemService(ACCESSIBILITY_SERVICE);
if(!accessibilityManager.isEnabled()){
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
return;
}
else {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("[B]open_split[/B]");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("open_split")){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent spliteOne = [COLOR="seagreen"]getPackageManager().getLaunchIntentForPackage[/COLOR]("com.whatsapp");// change to whatever you want
spliteOne.addCategory(Intent.CATEGORY_LAUNCHER);
spliteOne.setFlags(
Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
final Intent spliteTwo = [COLOR="SeaGreen"]getPackageManager().getLaunchIntentForPackage[/COLOR]("com.google.android.youtube");[B]3*[/B]// change to whatever you want
spliteTwo.addCategory(Intent.CATEGORY_LAUNCHER);
spliteTwo.setFlags(
Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | [B]1*[/B]
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(spliteOne);
new Handler().postDelayed(new Runnable() { [B]2*[/B]
@Override
public void run() {
startActivity(spliteTwo);
}
}, 200);
}
}, 500);
}
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
}
1* These are required flags to open an activity inside split-screen If the split screen already available.
Code:
.setFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
2* I set some delays for smoother performance of app and system & allow system to completely enter split-screen mode.
3* I set YouTube and WhatsApp for examples. you can set another apps or let users to select from a list. But there might be problem with some apps to enter split-screen mode cause they are not compatible. system will try to force them which is successful most of the time.
//AccessibilityEvent Listener in AccessibilityService
Code:
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
switch (event.getEventType()){
case AccessibilityEvent.[B]TYPE_WINDOW_STATE_CHANGED[/B]:
//system will call this event whenever something change open or close
//so app need to identify when to perform action to avoid lots of conflict
//event.getClassName() is name of the class that send this event which is OpenActivities for my app
if(event.getClassName().equals("com.example.android.split.OpenActivities")){
performGlobalAction([COLOR="RoyalBlue"]GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN[/COLOR]);[B]1*[/B]//this is the function to ask system to enter to split-screen
[B]sendBroadcast[/B](new Intent("[B]open_split[/B]"));[B]2*[/B]//to send action after asking system to enter split-screen
}
}
break;
}
}
1* System going to enter Split-Screen mode.
2* App will send action to activity to open other apps with proper Intent.Flags... in split-screen.
Download
Sample Source Code | Sample Apk File (WhatsApp & YouTube)
Oo. Download | Split Shortcuts .oO
Floating Shortcuts | Super Shortcut
Promo Code Available
Thanks for Support my Projects​Don't forget to Hit Thanks​
Reserved
Reserved
Please, send me a promo code
Open Pair of Apps Simultaneously from Floating Shortcuts
New Update | Floating Shortcuts​
Floating Shortcuts added Split Shortcuts for Android 7 & Higher
- Go to Floating Category
- Click on ( + )
- from apps of category, select Pair of Apps
.oO Download Oo.​Free Edition (Ads) | PRO Edition ($3.00)
Don't forget ti Hit Thanks​
Open Pair of Apps Simultaneously from Super Shortcuts
New Update | Super Shortcuts​
Super Shortcuts added Split Shortcuts for Android 7 & Higher
- Create Pair of Apps
- Select Apps Pair from list and Press Confirm Button
- Press and Hold to Add each Apps Pair to Home Screen
.oO Download Oo.​Free Edition (Ads) | PRO Edition ($1.50)​
Don't forget ti Hit Thanks​
Geeks Empire said:
Split-Screen Or Multi-Window introduced on Android 7 (API 24) for All Android devices.
Samsung added new Software features on Galaxy Note 8 that allows users to select pair of apps to open in simultaneously in split screen. Check it out
But If you want to configure your current app to support multi-window you need to read this documentation.
# Let Start #​
- Right Click on package name of app & Create a Java Class for AccessibilityService
Code:
public class [COLOR="royalblue"]SplitScreenService [/COLOR]extends [B]AccessibilityService [/B]{
@Override
protected void onServiceConnected() {
System.out.println("onServiceConnected");
//system will call this whenever you turn on Accessibility for this app
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
switch (event.getEventType()){
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
//this is a sample event that you can perform some action whenever it called
//and i will create split-screen here
[COLOR="DarkRed"]performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);[/COLOR]
//this is how you can enter split-screen mode
break;
}
}
@Override
public void onInterrupt() {
System.out.println(">>> onInterrupt");
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
}
@Override
public void onDestroy(){
super.onDestroy();
}
}
- Right Click on /res/... folder, create another folder and name it xml then you will have /res/xml/...
Then right click on /xml/... folder and create an xml file and choose a name (split.xml)
This xml file contains configuration of AccessibilityService.
Code:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="[COLOR="red"]typeAllMask[/COLOR]" // all mask means to get all event which most of time you don't need it.
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagRetrieveInteractiveWindows|flagDefault"
android:settingsActivity="com.example.android.globalactionbarservice"
android:description="@string/describe_what_will_you_do" //here you must describe to user what will you do with this special permission />
- Open AndroidManifest.xml to define AccessbilityService & Add required permissions
Inside <application/> tag add this.
Code:
<service
android:name="com.example.android.split.SplitScreenService" //change it to your package name and class
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/split"/> //add name of configuration file split.xml
</service>
Note that this app will only work when user enables Accessibility for it manually.
So first thing on Main Activity of the app must be to check this and redirect users to Accessibility Setting.
Open Main Activity of app and @oncreate() add this
Code:
final AccessibilityManager accessibilityManager = (AccessibilityManager)getSystemService(ACCESSIBILITY_SERVICE);
if([COLOR="Red"]!accessibilityManager.isEnabled()[/COLOR]){
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
return;
}
after this app should enter split-screen & try to open another apps inside split-screen.
that s why I set BroadcastReceiver to send proper action in right time after entering split-screen mode.
So to perform this app must have proper BroadcastReceiver & AccessibilityEvent listener.
//Custom BroadcastReceiver in activity
Code:
@Override
protected void onCreate(Bundle Saved){
super.onCreate(Saved);
final AccessibilityManager accessibilityManager = (AccessibilityManager)getSystemService(ACCESSIBILITY_SERVICE);
if(!accessibilityManager.isEnabled()){
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
return;
}
else {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("[B]open_split[/B]");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("open_split")){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent spliteOne = [COLOR="seagreen"]getPackageManager().getLaunchIntentForPackage[/COLOR]("com.whatsapp");// change to whatever you want
spliteOne.addCategory(Intent.CATEGORY_LAUNCHER);
spliteOne.setFlags(
Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
final Intent spliteTwo = [COLOR="SeaGreen"]getPackageManager().getLaunchIntentForPackage[/COLOR]("com.google.android.youtube");[B]3*[/B]// change to whatever you want
spliteTwo.addCategory(Intent.CATEGORY_LAUNCHER);
spliteTwo.setFlags(
Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | [B]1*[/B]
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(spliteOne);
new Handler().postDelayed(new Runnable() { [B]2*[/B]
@Override
public void run() {
startActivity(spliteTwo);
}
}, 200);
}
}, 500);
}
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
}
1* These are required flags to open an activity inside split-screen If the split screen already available.
Code:
.setFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
2* I set some delays for smoother performance of app and system & allow system to completely enter split-screen mode.
3* I set YouTube and WhatsApp for examples. you can set another apps or let users to select from a list. But there might be problem with some apps to enter split-screen mode cause they are not compatible. system will try to force them which is successful most of the time.
//AccessibilityEvent Listener in AccessibilityService
Code:
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
switch (event.getEventType()){
case AccessibilityEvent.[B]TYPE_WINDOW_STATE_CHANGED[/B]:
//system will call this event whenever something change open or close
//so app need to identify when to perform action to avoid lots of conflict
//event.getClassName() is name of the class that send this event which is OpenActivities for my app
if(event.getClassName().equals("com.example.android.split.OpenActivities")){
performGlobalAction([COLOR="RoyalBlue"]GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN[/COLOR]);[B]1*[/B]//this is the function to ask system to enter to split-screen
[B]sendBroadcast[/B](new Intent("[B]open_split[/B]"));[B]2*[/B]//to send action after asking system to enter split-screen
}
}
break;
}
}
1* System going to enter Split-Screen mode.
2* App will send action to activity to open other apps with proper Intent.Flags... in split-screen.
Download
Sample Source Code | Sample Apk File (WhatsApp & YouTube)
Oo. Download | Split Shortcuts .oO
Floating Shortcuts | Super Shortcut
Promo Code Available
Thanks for Support my Projects​Don't forget to Hit Thanks​
Click to expand...
Click to collapse
Dear,
Can you share please the code?
Thank you.
lebossejames said:
Dear,
Can you share please the code?
Thank you.
Click to expand...
Click to collapse
You can find it on Github https://github.com/GeeksEmpireOfficial/SuperShortcutsFree

Categories

Resources