Professional Android WebView Application With Splash Screen and Share Button.
Code is necessary for the implementation which can be copied from here and watch the video below for the detail explanation of the implementation.
If you had not installed a plugin on your computer...Visit this link:Click Here.
Video Updated..[PART 1]
If you had not installed a plugin on your computer...Visit this link:Click Here.
Features:
Having Splash Screen
Loading Animation before Website Loads into App
Share Button on The Action Bar
.
Requirements:
Windows or Mac Computer With
Android Studio & JDK 7 Installed
No need of Knowledge of Coding.
NOTE: In this guide i will be asking you to copy and paste code into your file. That indicates you first remove complete code particular file and paste my code.
Steps :
Open Android Studio and Select File=>New Project.
Follow Screens.....
{
"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"
}
Set Application Name and package name what ever you want.
Select Target SDK as per your Needs
Don't change these details
Now Navigate to MainActivity.java and double click on it.
Now Copy and Paste below Code into MainActivity.java file. Replace my project name with your's in 1st line of code. In Line No 27 replace "http://androidtechfreakat.blogspot.in/" with your url. Don't use www. prfix. paste in same same format you are looking. Next Change custom share data in red color with lines you want to sown share message in line numbers 71 & 72 and give your website url in line 27th Line.
package com.androidwebviewapp.advait;
Code:
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://androidtechfreakat.blogspot.in/");
mWebView.setWebViewClient(new MyAppWebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
@Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist https://androidtechfrakat.blogspot.in if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MainActivity.java hosted with by GitHub view raw
Now Right Click on your Project name udnder java folder and select create New Class and Name it Splash and copy and paste below code into Splash.java file. Replace my project name with your's in 1st line of code.
Code:
package com.androidwebviewapp.advait;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
@SuppressLint("NewApi")
public class Splash extends Activity {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ActionBar actionBar = getActionBar();
actionBar.hide();
Thread t =new Thread(){
public void run(){
try{
sleep(10000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent i =new Intent(Splash.this,MainActivity.class);
startActivity(i);
}
}
};
t.start();
}
@Override
public void onPause(){
super.onPause();
finish();
}
}
/**
* Created by Advait T on 05-Jul-15.
*/
Splash.java hosted with by GitHub view raw
Now Create one more java class file like above and name it asMyAppWebViewClientow copy and paste below code into MyAppWebViewClient.java file. And give your website url without any www or http prefixes as i gave there in line number 15 Replace my project name with your's in 1st line of code.
Code:
package com.androidwebviewapp.advait;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* Created by Advait's on 19/5/2015.
*/
public class MyAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("androidtechfreakat.blogspot.in")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
MyAppWebViewClient.java hosted with by GitHub view raw
Now we are done with Java Files. If android studio shows any errors ignore them. All errors will be gone by the end of this tutorial.
Now Copy Below Code into activity_main.xml.
Code:
<LinearLayout 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"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:indeterminate="false"
android:layout_gravity="center" />
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
</LinearLayout>
activity_main.xml hosted with by GitHub view raw
Now We Will Create new layout under folder layouts. For that Right Click on Layout and select new Xml File as shown in below figure. Name Layout as activity_splash.
Now Copy and Paste Below Code into activity_splash.xml.
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/vert_loading"
tools:context=".Splash" >
</RelativeLayout>
activity_splash.xml hosted with by GitHub view raw
Now open menu_main.xml in menu folder and paste below code into it.
Code:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item
android:id="@+id/share"
android:title="@string/share"
android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider"/>
</menu>
menu_main.xml hosted with by GitHub view raw
Now Open AndroidManifest.xml file From manifests folder and copy below code into it. replace project name with your project name in the 3rd line.
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidwebviewapp.advait" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Splash"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
AndroidManifest.xml hosted with by GitHub view raw
Now Finally Open Values Folder and place below code in strings.xml and change app_name string value to yours in line number two.
Code:
<resources>
<string name="app_name">Android WebView App</string>
<string name="hello_world">Hello world!</string>
<string name="share">Share</string>
<string name="action_websearch">Web search</string>
</resources>
strings.xml hosted with by GitHub view raw
By this we had finished all coding Part.
Now open computer and navigate to your Project folder YourProjectNameappsrcmainres, there will be four folders with name mipmap change ic_launcher.png with your icon but don't change name and only png format are supported. And place an image file with name vert_loading.png in all folders. vert_loading.png will be your Startup screen.
At last our Project structure looks like below image...
Now go to buil in top menu of Android Studio and select Generate signed Apk and epxort your Application. After Succesfull export copy it to your phone and install. Or Upload to play store.
Thanks to Karthik M
Pls hit the thanks button if i helped you:angel:
XDA:DevDB Information
[GUIDE]Professional Android WebView Application With Splash Screen and Share Button. , App for all devices (see above for details)
Contributors
AdvaitT17, Karthik M
Source Code: https://github.com/andriodwebviewapplication/Professional-Android-WebView-Application-With-Splash-Screen-and-Share-Button.
Version Information
Status: Stable
Created 2016-03-12
Last Updated 2016-05-02
Will try it.... But I don't have android studio right now could you please make one for me...
My website's URL is : theroyalseeker.github.io
Anyways thanks in advance @AdvaitT17..
ok i will do it... but send me a photo of splash background which u will have when u will open ur app
@TheRoyalSeeker your app is made...work done
If anyone wants me to make me app like this...contact me : [email protected] or PM me on Xda with app details.
Soon i will be uploading how to make an animated splash screen for android webview app or any other app
i am using android studio latest version.
and i have completed all coding and approx my app is done. but there is problem after opening the app when we touch or any click on website page. its send to us to other browser of our phone.
and i thing this is problem of "MyAppWebViewclient.java" because there is in code which contant "shouldOverrideUrlLoading" is crossed by a strength line. and when we cursor moves on that show this error
mention below:
"Overrides deprecated method in 'android.webkit.WebViewClient' less... (Ctrl+F1)
This inspection reports where deprecated code is used in the specified inspection scope."
please help me.
[email protected]
Hallo there...anyone who found the solution to the browser loading after trying to click on anything in the app
i will really appreaciate urgently needed...
Related
I hope someone can help.
I have an application that I am building that currently has 3 main Layouts. All String-Arrays are in XML. First Screen Shows, Breakfast, Lunch & Dinner. Now depending on which Button is selected, Example "Lunch" a 2nd Layout comes up Showing the Lunch Menu items, such as Cheeseburger, Hamburger, Hot Dog, French Fries, Onion Rings... Let's say I select "Cheeseburger", the Item is Added to the 3rd Layout. When I click the Back button on the phone and select a new item such as "Onion Rings" that item replaces the Cheeseburger. I need it to ADD it to the List, not replace it. Can someone please tell me where my code is wrong?
Summary, I need the list to get appended with the items selected, not replaced by the selected item.
Here is my lunchActivity.java
Code:
package com.mycompany.foodmenu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class lunchActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lunchmain);
final ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.lunch_menu,android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
String item=lv.getItemAtPosition(arg2).toString();
String itemordered;
itemordered = item + " added to list";
Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_LONG).show();
// Launching new Activity on selecting List Item
Intent i = new Intent(getApplicationContext(), ListItem.class);
// sending data to new activity
i.putExtra("item", item);
startActivity(i);
}
});
}
}
Here is the lunch.xml menu file that read by the lunchActivity to create the first ListView
Code:
<resources>
<string-array name="lunch_menu">
<item>Cheeseburger</item>
<item>Hamburger</item>
<item>Bacon Cheeseburger</item>
<item>Hot Dog</item>
<item>French Fries</item>
<item>Onion Rings</item>
</string-array>
</resources>
Here is the listItem.java
Code:
package com.mycompany.foodmenu;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class listItem extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.selecteditems);
Intent i = getIntent();
ArrayList<String> myNewList = new ArrayList<String>();
String item = i.getStringExtra("item");
myNewList.add(item);
ListView selecteditems = (ListView) findViewById(R.id.listitems);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItem.this, android.R.layout.simple_list_item_1, myNewList);
selecteditems.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
}
BTW. I have tried changing
Code:
myNewList.add(item);
to
Code:
myNewList.addAll(item);
and it just creates new problems. I have also tried adding
Code:
adapter.notifyDataSetChanged();
to the end and it makes no difference.
And here is the selectedItems.xml file that is suppose to get populated with the Selected Items from the Lunch Menu
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/main_background"
android:paddingLeft="10.0dip"
android:paddingTop="0.0dip"
android:paddingRight="10.0dip"
android:paddingBottom="10.0dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/listitems"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
Any help would be greatly appreciated!!
Please... Anybody got any ideas on what I am doing wrong?
StEVO_M said:
Please... Anybody got any ideas on what I am doing wrong?
Click to expand...
Click to collapse
post on stack overflow or join us on irc at #android-dev
f2prateek said:
post on stack overflow or join us on irc at #android-dev
Click to expand...
Click to collapse
I've posted on Stack Overflow and unless you get an answer within a few mins your post gets buried pretty quick.
I;ve never used irc so I'm not sure how to use it.
Sent from my Transformer Prime using Tapatalk 2
Disclaimer
I am not the developer of this tool. I am just sharing how to test your apps' functionality via Robotium.
This tutorial assumes that you have the SDK and Eclipse all set up perfectly. Setting these up will not be covered in this tutorial.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Setting up a sample project:
Although source codes are available, it is recommended to do this manually.
Create a new android project by going to File> New> Android Application Project.
Fill in the following information until you have the project set up.
{
"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"
}
So your project is now set up. Its a simple calculator just for testing.
Type this in your main.xml;
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtSpace"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtFirstNumber"
/>
<EditText
android:inputType="numberDecimal"
android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtSpace"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtSecondNumber"
/>
<EditText
android:inputType="numberDecimal"
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtSpace"
/>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/txtSpace"
/>
<Button
android:text="Multiply"
android:id="@+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
This in your strings.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Enter two values and click on Calculate to multiply them.</string>
<string name="app_name">AndroidCalculator</string>
<string name="txtFirstNumber">Enter First Number</string>
<string name="txtSecondNumber">Enter Second Number</string>
<string name="txtSpace"></string>
</resources>
This in your Main.java :
Code:
package com.calculator;
import com.calculator.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.text.Editable;
public class Main extends Activity {
EditText FirstValue;
EditText SecondValue;
TextView Result;
Button Calculate;
float num1 , num2;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FirstValue = (EditText) findViewById(R.id.EditText01);
SecondValue = (EditText) findViewById(R.id.EditText02);
Result = (TextView) findViewById(R.id.TextView01);
Result.setText("0.00");
Calculate = (Button) findViewById(R.id.Button01);
//Adding listener to button
Calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Getting first & second values and passing to show result
showResult(FirstValue.getText(), SecondValue.getText());
}
});
}
//Showing multiply results
protected void showResult(Editable first, Editable second)
{
float num1 = Float.parseFloat(first.toString());
float num2 = Float.parseFloat(second.toString());
float result = num1 * num2;
Result.setText(String.valueOf(result));
}
}
Your basic calculator app is now ready. This is just for testing purposes so we will not be focusing on the layout too much.
Launch your app in emulator. It will look like this :
Now we will create a test android project.
Go to File> New> Project and follow like its given below :
This is also done.
Now right click on the Test project and go to New> JUnit Test Case and setup the following:
A new java file will now bee created.
Now right click on the Test Project again and go to Build Path> Configure Build Path and setup the following again:
Here Click Add External Jars and browse to the Robotium jar file. You can download it here. Choose the latest one to download.
Note: Not javadoc.jar Only Jar file.
Go to Order and Export and check the jar file and click OK.
Now type this in the TestMain.java :
Code:
package com.calculator.test;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.EditText;
import android.widget.TextView;
import com.calculator.Main;
import com.calculator.R;
import com.jayway.android.robotium.solo.Solo;
public class TestMain extends ActivityInstrumentationTestCase2<Main> {
private Solo solo;
public TestMain() {
super(Main.class);
}
[user=439709]@override[/user]
protected void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
}
public void testDisplayBlackBox() {
//Enter 10 in first edit-field
solo.enterText(0, "10");
//Enter 20 in first edit-field
solo.enterText(1, "20");
//Click on Multiply button
solo.clickOnButton("Multiply");
//Verify that resultant of 10 x 20
assertTrue(solo.searchText("200"));
}
public void testDisplayWhiteBox() {
//Defining our own values to multiply
float firstNumber = 10;
float secondNumber = 20;
float resutl = firstNumber * secondNumber ;
//Access First value (edit-filed) and putting firstNumber value in it
EditText FirsteditText = (EditText) solo.getView(R.id.EditText01);
solo.enterText(FirsteditText, String.valueOf(firstNumber));
//Access Second value (edit-filed) and putting SecondNumber value in it
EditText SecondeditText = (EditText) solo.getView(R.id.EditText02);
solo.enterText(SecondeditText, String.valueOf(secondNumber));
//Click on Multiply button
solo.clickOnButton("Multiply");
assertTrue(solo.searchText(String.valueOf(resutl)));
TextView outputField = (TextView) solo.getView(R.id.TextView01);
//Assert to verify result with visible value
assertEquals(String.valueOf(resutl), outputField.getText().toString());
}
[user=439709]@override[/user]
protected void tearDown() throws Exception{
solo.finishOpenedActivities();
}
}
That's it. Your test project is also done.
Now right click on the TestMain.java in Eclipse and run it as an Android JUnit Test Case:
Project will now load up in the emulator and auto testing will begin as provided in TestMain.java:
Finally your results will be shown in the JUnit panel. Which shouldn't have any errors of course.
That's it! You have just tested your app without even really testing it!! :good:
Using Robotium to test apk file
This tutorial is for testing an apk file if you dont have the source.
Follow this first if app is not yours and is signed by someone else.
1. Open the apk file with 7zip or any other alternative.
2. Delete the Meta-inf folder.
3. Resign the apk again in debug mode.
If the app is yours.
Export the app in any location signed in debug mode.
Install the apk onto the emulator.
Now again create a test project like in the 1st post.
Make sure you click the radio button for ''This Project''.
From now, its similar to the first post.
First right click on the package and go to New> Package and give the package as com.testcalculator .
Create a new Class by right clicking on the Test Project and name it as TestApk.
Again add the Robotium jar file that you downloaded earlier. Follow first post on how to do it.
Finally right-click the project and run it as Android JUnit Test.
That's it. Emulator will load it and test it the same way as in Post 1.
Note:
1. Make sure your Manifest is correct because most probably Eclipse will make the package as com.calculator.test . You can keep it the same way but to differentiate it from the 1st post, we will keep it as com.testcalculator .
2. Whatever your package name is, make sure to keep it correct in the java class in src folder.
3. You can keep the java file same as in post 1 keeping in mind the above point.
Featured on the Portal here:
http://www.xda-developers.com/android/auto-test-your-android-apps-with-robotium
Again here:
www.xda-developers.com/android/robotium-guide-updated-for-testing-apps-without-source
And on XDA TV here:
http://www.xda-developers.com/andro...g-android-apps-with-robotium-xda-developer-tv
Robotium
Robotium is an Android test automation framework
that has full support for native and hybrid
applications. Robotium makes it easy to write
powerful and robust automatic black-box test
cases. With the support of Robotium, test case
developers can write function, system and acceptance test scenarios, spanning multiple
Android activities.
Click to expand...
Click to collapse
Sources And Links
Robotium Project Home.
Download Page.
Tutorials Page.
Sources
The source code of the sample apps can be downloaded through the Tutorials link given.
{
"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"
}
In previous two articles I covered development environment setup and anatomy of SmartWatch. This article will contain deep dive into coding with simple Hello Word example.
http://forum.xda-developers.com/smartwatch/sony/tut-introduction-smart-watch-t2807896
http://forum.xda-developers.com/smartwatch/sony/tut-smartwatch-app-development-part-2-t2807954
This demo will cover Notification API only. We will develop a single Android project named "Hello SmartWatch" which acts as a Host application and Extension application both. It means I will use single codebase for both things. Hello SmartWatch project has an Activity to send and clear notification to SmartWatch.
I assume that you have already imported SmartExtensionAPI and SmartExtensionUtils libraries in workspace.
Let's jump to the code.
List of Classes and purpose
MainActivity.java: It is use to generate and clear notification.
HelloExtensionReceiver.java: It receives input event generated by SmartWatch and forward control to the Extension Service.
HelloExtensionService.java: core logic of Host application needs to be written in ExtensionService. It is also responsible to register a host application to SmartWatch.
HelloRegistrationInformation.java: It provides essential information to register host application and API requirement.
This demo application contains only above four classes but actual application may have more classes. In above classes MainActivity acts as a Smart Extension application and rest of classes acts as a Host application.
Step 1: Create new Android project in eclipse named "HelloSmartWatch".
Step 2: Let's create UI first. Open activity_main.xml and put two EditText box for Title and Message respectively and two buttons for Send and Clear notification respectively.
Code:
<LinearLayout 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:orientation="vertical"
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:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Send Notification"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/etTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Title" >
</EditText>
<EditText
android:id="@+id/etMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Message" >
</EditText>
<Button
android:id="@+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonClicked"
android:text="Send Notification" />
<Button
android:id="@+id/btnClearn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonClicked"
android:text="Clear Notification" />
</LinearLayout>
Step 3: Let's make button alive by writing action in MainActivity.java. I am using onClick property of buttons, so I don't require to find object of button and setOnClickListener. I can write code in "buttonClicked" method which is defined. When a user click on "Send Notification" button I am simply firing ExtensionService with INTENT_ACTION_ADD action and other required data and same for "Clear Notification" but with INTENT_ACTION_CLEAR action.
Code:
package com.kpbird.hellosmartwatch;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonClicked(View v){
if(v.getId() == R.id.btnSend){
Intent serviceIntent = new Intent(this, HelloExtensionService.class);
serviceIntent.setAction(HelloExtensionService.INTENT_ACTION_ADD);
EditText etName = (EditText) findViewById(R.id.etTitle);
EditText etMsg = (EditText) findViewById(R.id.etMessage);
serviceIntent.putExtra("name", etName.getText().toString());
serviceIntent.putExtra("message", etMsg.getText().toString());
startService(serviceIntent);
}
else if(v.getId() == R.id.btnClearn){
Intent serviceIntent = new Intent(this, HelloExtensionService.class);
serviceIntent.setAction(HelloExtensionService.INTENT_ACTION_CLEAR);
startService(serviceIntent);
}
}
}
Step 4: Create HelloExtensionReceiver.java, It extends BroadcastReceiver. It works as bridge between SmartWatch and Host application, It will receive event generated in SmartWatch and forward it to HelloExtensionService.java
Code:
package com.kpbird.hellosmartwatch;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class HelloExtensionReceiver extends BroadcastReceiver{
private String TAG = this.getClass().getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "HelloExtensionReceiver onReceiver: " + intent.getAction());
intent.setClass(context, HelloExtensionService.class);
context.startService(intent);
}
}
Step 5: Create HelloRegistrationInformation.java and extends with RegistrationInformation class. As the name suggests, It will use to register host application in Smart Connect. It has six methods that we need to override, among these four methods are used to declare required APIs and two methods used for extension registration and source registration. You can have multiple sources in a host application.
Code:
package com.kpbird.hellosmartwatch;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import com.sonyericsson.extras.liveware.aef.notification.Notification;
import com.sonyericsson.extras.liveware.aef.registration.Registration;
import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils;
import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation;
public class HelloRegistrationInformation extends RegistrationInformation{
private Context mContext;
public HelloRegistrationInformation(Context ctx){
if (ctx == null) {
throw new IllegalArgumentException("context == null");
}
mContext = ctx;
}
@Override
public int getRequiredNotificationApiVersion() {
return 1;
}
@Override
public int getRequiredWidgetApiVersion() {
return 0;
}
@Override
public int getRequiredControlApiVersion() {
return 0;
}
@Override
public int getRequiredSensorApiVersion() {
return 0;
}
@Override
public ContentValues getExtensionRegistrationConfiguration() {
String extensionIcon = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher);
String iconHostapp = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher);
String extensionIcon48 = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_48);
String configurationText = "Hello SmartWatch";
String extensionName = "Hello SmartWatch";
ContentValues values = new ContentValues();
values.put(Registration.ExtensionColumns.CONFIGURATION_ACTIVITY,MainActivity.class.getName());
values.put(Registration.ExtensionColumns.CONFIGURATION_TEXT, configurationText);
values.put(Registration.ExtensionColumns.EXTENSION_ICON_URI, extensionIcon);
values.put(Registration.ExtensionColumns.EXTENSION_48PX_ICON_URI, extensionIcon48);
values.put(Registration.ExtensionColumns.EXTENSION_KEY,HelloExtensionService.EXTENSION_KEY);
values.put(Registration.ExtensionColumns.HOST_APP_ICON_URI, iconHostapp);
values.put(Registration.ExtensionColumns.NAME, extensionName);
values.put(Registration.ExtensionColumns.NOTIFICATION_API_VERSION,getRequiredNotificationApiVersion());
values.put(Registration.ExtensionColumns.PACKAGE_NAME, mContext.getPackageName());
return values;
}
@Override
public ContentValues[] getSourceRegistrationConfigurations() {
ContentValues sourceValues = null;
String iconSource1 = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_30);
String iconSource2 = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_18);
String iconBw = ExtensionUtils.getUriString(mContext,R.drawable.ic_launcher_18_bw);
String textToSpeech = "Notification from Hello SmartWatch Application";
sourceValues = new ContentValues();
sourceValues.put(Notification.SourceColumns.ENABLED, true);
sourceValues.put(Notification.SourceColumns.ICON_URI_1, iconSource1);
sourceValues.put(Notification.SourceColumns.ICON_URI_2, iconSource2);
sourceValues.put(Notification.SourceColumns.ICON_URI_BLACK_WHITE, iconBw);
sourceValues.put(Notification.SourceColumns.UPDATE_TIME, System.currentTimeMillis());
sourceValues.put(Notification.SourceColumns.NAME, mContext.getString(R.string.app_name));
sourceValues.put(Notification.SourceColumns.EXTENSION_SPECIFIC_ID, HelloExtensionService.EXTENSION_SPECIFIC_ID);
sourceValues.put(Notification.SourceColumns.PACKAGE_NAME, mContext.getPackageName());
sourceValues.put(Notification.SourceColumns.TEXT_TO_SPEECH, textToSpeech);
sourceValues.put(Notification.SourceColumns.ACTION_1,"Hello");
sourceValues.put(Notification.SourceColumns.ACTION_ICON_1,ExtensionUtils.getUriString(mContext, R.drawable.ic_launcher));
List<ContentValues> bulkValues = new ArrayList<ContentValues>();
bulkValues.add(sourceValues);
return bulkValues.toArray(new ContentValues[bulkValues.size()]);
}
}
Step 6: Create HelloExtensionService.java and extends with ExtensionService. It will contain main logic of SmartWatch host application. We need to implement two abstract methods named "getRegistrationInformation()", which sends object of HelloRegistrationInformation class and "keepRunningWhenConnected()",return true if you want to keep ExtensionService running as long as SmartWatch is connected with Smart Phone. For notification example we need to create two methods named "addData" and "clearData". It will generate and clear notification in SmartWatch respectively. We also need to implement onStartCommand to interact with Service.
Code:
package com.kpbird.hellosmartwatch;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.widget.Toast;
import com.sonyericsson.extras.liveware.aef.notification.Notification;
import com.sonyericsson.extras.liveware.aef.registration.Registration;
import com.sonyericsson.extras.liveware.extension.util.ExtensionService;
import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils;
import com.sonyericsson.extras.liveware.extension.util.notification.NotificationUtil;
import com.sonyericsson.extras.liveware.extension.util.registration.DeviceInfoHelper;
import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation;
public class HelloExtensionService extends ExtensionService {
public static final String EXTENSION_SPECIFIC_ID = "EXTENSION_SPECIFIC_ID_HELLO_NOTIFICATION";
public static final String EXTENSION_KEY = "com.kpbird.hellosmartwatch.key";
public static final String INTENT_ACTION_ADD = "com.kpbird.hellosmartwatch.action.add";
public static final String INTENT_ACTION_CLEAR = "com.kpbird.hellosmartwatch.action.clear";
private String TAG = this.getClass().getSimpleName();
public HelloExtensionService() {
super(EXTENSION_KEY);
Log.i(TAG, "Constructor");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int retVal = super.onStartCommand(intent, flags, startId);
if (intent != null) {
if (INTENT_ACTION_CLEAR.equals(intent.getAction())) {
Log.d(TAG, "onStart action: INTENT_ACTION_CLEAR");
clearData(intent);
stopSelfCheck();
} else if (INTENT_ACTION_ADD.equals(intent.getAction())) {
Log.d(TAG, "onStart action: INTENT_ACTION_ADD");
addData(intent);
stopSelfCheck();
}
}
return retVal;
}
@Override
protected RegistrationInformation getRegistrationInformation() {
return new HelloRegistrationInformation(this);
}
@Override
protected boolean keepRunningWhenConnected() {
return false;
}
private void clearData(Intent intent) {
NotificationUtil.deleteAllEvents(this);
}
private void addData(Intent intent) {
String name = "Name";
String message = "Message";
if (intent.getExtras().containsKey("name"))
name = intent.getExtras().getString("name");
if (intent.getExtras().containsKey("message"))
message = intent.getExtras().getString("message");
long time = System.currentTimeMillis();
long sourceId = NotificationUtil.getSourceId(this,
EXTENSION_SPECIFIC_ID);
Log.i(TAG, "Source ID :" + sourceId);
if (sourceId == NotificationUtil.INVALID_ID) {
Log.e(TAG, "Failed to insert data");
return;
}
String profileImage = ExtensionUtils.getUriString(this,R.drawable.ic_launcher);
ContentValues eventValues = new ContentValues();
eventValues.put(Notification.EventColumns.EVENT_READ_STATUS, false);
eventValues.put(Notification.EventColumns.DISPLAY_NAME, name);
eventValues.put(Notification.EventColumns.MESSAGE, message);
eventValues.put(Notification.EventColumns.PERSONAL, 1);
eventValues.put(Notification.EventColumns.PROFILE_IMAGE_URI,profileImage);
eventValues.put(Notification.EventColumns.PUBLISHED_TIME, time);
eventValues.put(Notification.EventColumns.SOURCE_ID, sourceId);
try {
getContentResolver().insert(Notification.Event.URI, eventValues);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Failed to insert event", e);
} catch (SecurityException e) {
Log.e(TAG,
"Failed to insert event, is Live Ware Manager installed?",
e);
} catch (SQLException e) {
Log.e(TAG, "Failed to insert event", e);
}
}
@Override
protected void onViewEvent(Intent intent) {
String action = intent.getStringExtra(Notification.Intents.EXTRA_ACTION);
Log.i(TAG, "Action : " + action);
String hostAppPackageName = intent.getStringExtra(Registration.Intents.EXTRA_AHA_PACKAGE_NAME);
Log.i(TAG, "HostAppPackageName: " + hostAppPackageName);
boolean advancedFeaturesSupported = DeviceInfoHelper.isSmartWatch2ApiAndScreenDetected(this, hostAppPackageName);
Log.i(TAG, "Advanced Features Supported: " + advancedFeaturesSupported);
int eventId = intent.getIntExtra(Notification.Intents.EXTRA_EVENT_ID,-1);
try {
Cursor cursor = getContentResolver().query(Notification.Event.URI,null, Notification.EventColumns._ID + " = " + eventId,null, null);
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex(Notification.EventColumns.DISPLAY_NAME));
String message = cursor.getString(cursor.getColumnIndex(Notification.EventColumns.MESSAGE));
Toast.makeText(this,"Notification: Name: " + name + " Message: " + message,Toast.LENGTH_LONG).show();
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Message: "+ message);
}
cursor.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void onRegisterResult(boolean success) {
super.onRegisterResult(success);
Log.d(TAG, "onRegisterResult :" + success);
}
}
Step 7: Finally we need to register HelloExtensionReceiver and HelloExtensionService in AndroidManifest.xml like following. We also need to provide user permission "EXTENSION_PERMISSION".
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kpbird.hellosmartwatch"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<uses-permission android:name="com.sonyericsson.extras.liveware.aef.EXTENSION_PERMISSION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.kpbird.hellosmartwatch.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".HelloExtensionService" />
<receiver
android:name=".HelloExtensionReceiver"
android:permission="com.sonyericsson.extras.liveware.aef.HOSTAPP_PERMISSION" >
<intent-filter>
<!-- Generic extension intents. -->
<action android:name="com.sonyericsson.extras.liveware.aef.registration.EXTENSION_REGISTER_REQUEST" />
<action android:name="com.sonyericsson.extras.liveware.aef.registration.ACCESSORY_CONNECTION" />
<action android:name="android.intent.action.LOCALE_CHANGED" />
<!-- Notification intents -->
<action android:name="com.sonyericsson.extras.liveware.aef.notification.VIEW_EVENT_DETAIL" />
<action android:name="com.sonyericsson.extras.liveware.aef.notification.REFRESH_REQUEST" />
<!-- Widget intents -->
<action android:name="com.sonyericsson.extras.aef.widget.START_REFRESH_IMAGE_REQUEST" />
<action android:name="com.sonyericsson.extras.aef.widget.STOP_REFRESH_IMAGE_REQUEST" />
<action android:name="com.sonyericsson.extras.aef.widget.ONTOUCH" />
<action android:name="com.sonyericsson.extras.liveware.extension.util.widget.scheduled.refresh" />
<!-- Control intents -->
<action android:name="com.sonyericsson.extras.aef.control.START" />
<action android:name="com.sonyericsson.extras.aef.control.STOP" />
<action android:name="com.sonyericsson.extras.aef.control.PAUSE" />
<action android:name="com.sonyericsson.extras.aef.control.RESUME" />
<action android:name="com.sonyericsson.extras.aef.control.ERROR" />
<action android:name="com.sonyericsson.extras.aef.control.KEY_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.TOUCH_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.SWIPE_EVENT" />
</intent-filter>
</receiver>
</application>
</manifest>
Step 8: Connect your SmartPhone and run this example. It will display MainActivity. Before jumping to "Send Notification", open Accessory Emulator and select Extension to verify that our HelloExtension is installed or not. Click on extension menu and it will display the registration details. If extension gets registered successfully then you can go back to Hello SmartWatch application and play with Send and Clear Notification functionality.
Screen Shots
Download Source CodeNote: 1. Import project in eclipse 2. Make sure that you change SmartExtensionUtils and SmartExtensionAPI path from project properties.
guys please help i have stucked in this problem for a long time.
Code:
public class Activity_Calculator extends StandOutWindow {
@Override
public String getAppName() {
return "test";
}
@Override
public int getAppIcon() {
return android.R.drawable.ic_menu_close_clear_cancel;
}
@Override
public void createAndAttachView(int id, FrameLayout frame) {
// create a new layout from body.xml
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View child= inflater.inflate(R.layout.activity_activity__calculator, frame, true);
WebView myWebView = (WebView)child.findViewById(R.id.webView1);
EditText field = (EditText)child.findViewById(R.id.urlField);
//myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyBrowser());
//myWebView.getSettings().setJavaScriptEnabled(true);
//myWebView.getSettings().setPluginsEnabled(true);
//myWebView.getSettings().setDomStorageEnabled(true);
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
// the window will be centered
@Override
public StandOutLayoutParams getParams(int id, Window window) {
return new StandOutLayoutParams(id, 500, 600,
StandOutLayoutParams.CENTER, StandOutLayoutParams.CENTER);
}
// move the window by dragging the view
@Override
public int getFlags(int id) {
return StandOutFlags.FLAG_DECORATION_SYSTEM
| StandOutFlags.FLAG_BODY_MOVE_ENABLE
| StandOutFlags.FLAG_WINDOW_HIDE_ENABLE
| StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP
| StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE
| StandOutFlags.FLAG_WINDOW_PINCH_RESIZE_ENABLE;
}
@Override
public String getPersistentNotificationMessage(int id) {
return "Click to close the SimpleWindow";
}
@Override
public Intent getPersistentNotificationIntent(int id) {
return StandOutWindow.getCloseIntent(this, Activity_Calculator.class, id);
}
}
xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=
xmlns: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=".Activity_Calculator" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/urlField"
android:layout_centerHorizontal="true"
android:onClick="open"
/>
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentBottom="true"
android:layout_below="@+id/button1" />
</RelativeLayout>
the webview does not respond and the apps force closed, the attachment below is the logcat,guys please help
Introduction
1. Easy integration: You only need two file transmission APIs to integrate Nearby Service, and it doesn't require any complex network protocols.
2. Ultra-fast transmission: It achieves file transmission rate of up to 60 MB/s, so transmitting a 1 GB file takes only 20 seconds.
3. Offline transmission: Nearby Service doesn't require routers or any other network devices. Data is transmitted through Bluetooth and Wi-Fi, so it doesn't consume the user's mobile data.
4. Platform support: The service supports all Android platforms, and will work with other platforms soon.
Demo (NearbyFileTransfer)
Here, take NearbyFileTransfer as an example. You can see how NearbyFileTransfer uses QR codes to transmit files between devices. NearbyFileTransfer has integrated with Nearby Service and Scan Kit.
NearbyTransfer Development
You can find the open source code for NearbyFileTransferon GitHub.
Now, I'll show you how to create the demo based on the source code, so that you can better understand the implementation process.
Preparations
Tools
Two Huawei phones (recommended).
Android Studio (3.X or later).
Register as a Developer
Register as a Huawei developer.
Create an App
Create an app on Huawei AppGallery. For details, please refer to Nearby Service Getting Started Tutorial.
Create a Demo
Download the agconnect-services.json file from AppGallery Connect, and put it into the the app directory (\app) of the demo project.
Sync and build the demo project.
Run the Demo
3. Install the demo on test devices A and B.
4. Tap Send File on device A and select the file you want to transmit. A QR code will be generated.
5. Tap Receive File on device B.
6. Wait until the file transmission is complete.
Code Development
Add Huawei Maven Repository to the Project-Level build.gradle File of Your Project
Add the following Maven address to the build.gradle file in the root directory of
the demo project:
Code:
buildscript {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
} }allprojects {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
}}
Add SDK Dependencies to the App-Level build.gradle File
Code:
dependencies {
implementation 'com.huawei.hms:nearby:5.0.2.300'
implementation 'com.huawei.hms:scan:1.2.3.300'
}
Please always use the newest version of Nearby Service listed on the version change history page.
Declare the System Permission in the AndroidManifest.xml File
This demo needs Bluetooth, Wi-Fi, storage, and location permission to transfer files, and needs camera permission to scan QR codes.
Code:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--Camera permission-->
<uses-permission android:name="android.permission.CAMERA" />
1. Sending a file.
The sender selects a file and calls nearbyAgent.sendFile to send the file.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the URI of the selected file.
Uri uri = data.getData();
nearbyAgent.sendFile(new File(uri.getPath()));
}
break;
case NearbyAgent.REQUEST_CODE_SCAN_ONE:
nearbyAgent.onScanResult(data);
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
2. Receiving a file.
The receiver calls nearbyAgent.onScanResult(data) to receive a file.
Code:
recvBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nearbyAgent.receiveFile();
}
});
References
Our official website
Development Guide
Reddit to join our developer discussion
GitHub to download demos and sample codes
Stack Overflow to solve any integration problems
For more information like this, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0201386494098350507
Hello i have entered google picxel 5 contest
I'm from Zambia, I just entered the pixel 5 contest
Entered the giveaway , I hope I can win.
Hi. Hope I entered too.
Sane as google nearby share
Wow awsome
Amazing
Helpful nearby built in android
XDARoni said:
Introduction
1. Easy integration: You only need two file transmission APIs to integrate Nearby Service, and it doesn't require any complex network protocols.
2. Ultra-fast transmission: It achieves file transmission rate of up to 60 MB/s, so transmitting a 1 GB file takes only 20 seconds.
3. Offline transmission: Nearby Service doesn't require routers or any other network devices. Data is transmitted through Bluetooth and Wi-Fi, so it doesn't consume the user's mobile data.
4. Platform support: The service supports all Android platforms, and will work with other platforms soon.
Demo (NearbyFileTransfer)
Here, take NearbyFileTransfer as an example. You can see how NearbyFileTransfer uses QR codes to transmit files between devices. NearbyFileTransfer has integrated with Nearby Service and Scan Kit.
NearbyTransfer Development
You can find the open source code for NearbyFileTransferon GitHub.
Now, I'll show you how to create the demo based on the source code, so that you can better understand the implementation process.
Preparations
Tools
Two Huawei phones (recommended).
Android Studio (3.X or later).
Register as a Developer
Register as a Huawei developer.
Create an App
Create an app on Huawei AppGallery. For details, please refer to Nearby Service Getting Started Tutorial.
Create a Demo
Download the agconnect-services.json file from AppGallery Connect, and put it into the the app directory (\app) of the demo project.
Sync and build the demo project.
Run the Demo
3. Install the demo on test devices A and B.
4. Tap Send File on device A and select the file you want to transmit. A QR code will be generated.
5. Tap Receive File on device B.
6. Wait until the file transmission is complete.
Code Development
Add Huawei Maven Repository to the Project-Level build.gradle File of Your Project
Add the following Maven address to the build.gradle file in the root directory of
the demo project:
Code:
buildscript {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
} }allprojects {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
}}
Add SDK Dependencies to the App-Level build.gradle File
Code:
dependencies {
implementation 'com.huawei.hms:nearby:5.0.2.300'
implementation 'com.huawei.hms:scan:1.2.3.300'
}
Please always use the newest version of Nearby Service listed on the version change history page.
Declare the System Permission in the AndroidManifest.xml File
This demo needs Bluetooth, Wi-Fi, storage, and location permission to transfer files, and needs camera permission to scan QR codes.
Code:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--Camera permission-->
<uses-permission android:name="android.permission.CAMERA" />
1. Sending a file.
The sender selects a file and calls nearbyAgent.sendFile to send the file.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the URI of the selected file.
Uri uri = data.getData();
nearbyAgent.sendFile(new File(uri.getPath()));
}
break;
case NearbyAgent.REQUEST_CODE_SCAN_ONE:
nearbyAgent.onScanResult(data);
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
2. Receiving a file.
The receiver calls nearbyAgent.onScanResult(data) to receive a file.
Code:
recvBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nearbyAgent.receiveFile();
}
});
References
Our official website
Development Guide
Reddit to join our developer discussion
GitHub to download demos and sample codes
Stack Overflow to solve any integration problems
For more information like this, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0201386494098350507
Click to expand...
Click to collapse
Dope
Dope
I have the dedication
But i dont have the tech
One day i will be a developer
Very interesting.