I have made a WebView app and deep linking works on it. Whenever someone clicks a link to my website (on any other app) then my app opens but, the homepage loads up instead of the URL clicked. I want the exact URL of my website to open whenever the link is clicked instead of the homepage.
MainActivity.java
package com.yoalfaaz.yoalfaaz;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.support.v4.view.MenuItemCompat;
public class MainActivity extends AppCompatActivity {
private WebView YoWeb;
private ShareActionProvider mShareActionProvider;
SwipeRefreshLayout swipe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
YoWeb = (WebView)findViewById(R.id.webview); // Move your declaration up here
swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb(YoWeb.getUrl()); // Pass in the current url to refresh
}
});
LoadWeb("https://www.yoalfaaz.com"); // load the home page only once
}
public void LoadWeb(String url) // Pass in URL you want to load
{
WebSettings webSettings = YoWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
YoWeb.loadUrl(url); // Load the URL passed into the method
swipe.setRefreshing(true);
YoWeb.setWebViewClient(new WebViewClient() {
//onPageFinished Method
public void onPageFinished(WebView view, String url) {
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
#Override
public void onBackPressed() {
if (YoWeb.canGoBack()) {
YoWeb.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
//private Intent setShareIntent() {
// Intent shareIntent = new Intent();
// shareIntent.setAction(Intent.ACTION_SEND);
// shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
// shareIntent.setType("text/plain");
// startActivity(shareIntent);
// return shareIntent;
//}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yoalfaaz.yoalfaaz">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter >
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:host="www.yoalfaaz.com" android:scheme="https"/>
</intent-filter>
</activity>
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
How to make it work as it works with most other apps? Like if we click on a YouTube link in WhatsApp then that particular video opens in YouTube app instead of YouTube homepage.
LoadWeb("https://www.yoalfaaz.com"); // load the home page only once
Instead of hardcoding the URL, use getIntent().getData().toString() to get the URL(as a string) that is clicked from the other apps and use this URL to load web view.
Have a null check and load default URL if there is no URL received from getData().
Hope this helps.
========= EDITED to show the code as you have asked =====================
In your code, you are loading web view with this line.
LoadWeb("https://www.yoalfaaz.com"); // load the home page only once
Modify this line like below.
String url = "https://www.yoalfaaz.com";
if(null != getIntent().getData()){
url = getIntent().getData().toString();
}
LoadWeb(url);
Related
Iam new to the android programming environment and am creating my first app. I am trying to get webview to open google maps when a google maps link is clicked within webview. Am I missing something as to why this is still opening the link in webview and not executing google maps instead? And when it is opening in webview it shows the destination fine but it does not show my location and states it is unable to determine my location on the bottom of the page being displayed
Here is the MainActivity
package com.example.micha.myapplication;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
/**
* WebViewClient subclass loads all hyperlinks in the existing WebView
*/
public class GeoWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
}
/**
* WebChromeClient subclass handles UI-related calls
* Note: think chrome as in decoration, not the Chrome browser
*/
public class GeoWebChromeClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Always grant permission since the app itself requires location
// permission and the user has therefore already granted it
callback.invoke(origin, true, false);
}
}
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = findViewById(R.id.webView);
WebView myWebView = findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
myWebView.setWebViewClient(new GeoWebViewClient());
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setGeolocationEnabled(true);
CookieManager.getInstance().setAcceptCookie(true);
//webSettings.setDomStorageEnabled(true);
myWebView.clearHistory();
myWebView.clearFormData();
myWebView.clearCache(true);
myWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
if(url.contains("https://www.google.com/maps/"))
{
Uri gmmIntentUri = Uri.parse(url);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
return true;
}
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
return true;
}
});
myWebView.loadUrl("http://www.example.com");
//THIS IS TO DOWNLOAD THE PDF FILES OR OTHER DOWNLOAD LINKS
myWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
return;
}
super.onBackPressed();
}
}
Here is the AndroidManifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.micha.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACTION_DIAL"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_principal"
android:label="Admin Tools"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Found the problem.
if( url.startsWith("http:") || url.startsWith("https:") ) {
was preventing google maps from opening as it was forcing any url with https to stay within the webview. modified it to
if( url.startsWith("http:")) {
and all is good now.
I have done on app convert my website to app with webview
i want to Upload an Image from camera or gallery
i want to add to for example if i want to share on facebook it need to open facebook app or if i click links it need to ask me to go outside
what should i change or add?
Thank you!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
webView();
}
//Metodo llamar el webview
private void webView() {
//Habilitar JavaScript (Videos youtube)
webview.getSettings().setJavaScriptEnabled(true);
//Handling Page Navigation
webview.setWebViewClient(new WebViewClient());
//Load a URL on WebView
webview.loadUrl("http://www.nehmen-geben.com/");
}
// Metodo Navigating web page history
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Try to use the "WebClientListener" and override the "shouldOverrideUrlLoading".
webView.setWebViewClient(new WebClientListener());
and private class WebClientListener extends WebViewClient {
//other callback......
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Intercept the url you specified in this method.
//e.g. Define a specified url like "http://yourhost.com/shareToFacebook"
//in your html and when you cathch this url, use the facebook's sdk to share,
//and return "true" to tell the webview to handle such url yourself.
//
//If you want to open the browser outside,you can use:
//Uri uri = Uri.parse(url);
//Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//startActivity(intent);
}
}
If you just want to upload the file like photo in webview, you can try
webView.setWebChromeClient(new WebChromeClient());
override the onShowFileChooser(after lollipop) and openFileChooser(prelolipop) of the interface.
Aim
To login to my Admin.xml via AdminLogin.xml
Flow of Classes
AdminLoginActivity ---> AdminActivity
AdminLoginActivityClass
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLoginActivity extends AppCompatActivity {
private Toolbar jAdminToolbar;
private EditText jAdminID;
private EditText jAdminPassword;
private Button jAdminLoginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
jAdminToolbar = (Toolbar) findViewById(R.id.adminLoginToolbar);
setSupportActionBar(jAdminToolbar);
getSupportActionBar().setTitle("Admin Login");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
jAdminID = (EditText) findViewById(R.id.adminLoginName);
jAdminPassword = (EditText) findViewById(R.id.adminLoginPassword);
jAdminLoginBtn = (Button) findViewById(R.id.adminLoginBtn);
jAdminLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String adminLoginID = jAdminID.getText().toString();
String adminLoginPassword = jAdminPassword.getText().toString();
if(adminLoginID.equals("admin")&& adminLoginPassword.equals("admin")){
Intent intentAdmin = new Intent(AdminLoginActivity.this, AdminActivity.class);
intentAdmin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentAdmin);
finish();
}else{
Toast.makeText(AdminLoginActivity.this, "Failed Login", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
AdminActivityClass
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class AdminActivity extends AppCompatActivity {
private FirebaseAuth mAdminAuth;
private Toolbar jAdminToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
mAdminAuth = FirebaseAuth.getInstance();
jAdminToolbar = (Toolbar) findViewById(R.id.adminToolbar);
setSupportActionBar(jAdminToolbar);
getSupportActionBar().setTitle("Administrator");
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAdminAuth.getCurrentUser();
if(currentUser == null){
sendUserToStartPage();
}
}
private void sendUserToStartPage(){
Intent intentStart = new Intent(AdminActivity.this, StartActivity.class);
startActivity(intentStart);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_admin_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.mainSignOutBtn){
FirebaseAuth.getInstance().signOut();
sendUserToStartPage();
}
if(item.getItemId() == R.id.mainViewContactsBtn){
Intent intentViewContacts = new Intent(AdminActivity.this, AllUsersActivity.class);
startActivity(intentViewContacts);
}
return true;
}
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".SecurityApp"
android:allowBackup="true"
android:icon="#mipmap/appiconone"
android:label="#string/app_name"
android:roundIcon="#mipmap/appiconone"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StartActivity" />
<activity
android:name=".ResidentRegistrationActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".AdminLoginActivity"
android:parentActivityName=".LoginActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.lenovo.securityapp.LoginActivity" />
</activity>
<activity
android:name=".LoginActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MainActivity" />
<activity
android:name=".DetailsActivity"
android:parentActivityName=".SettingsActivity" />
<activity
android:name=".AllUsersActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".UserProfileActivity" />
<activity
android:name=".HelpInformationActivity"
android:parentActivityName=".StartActivity" />
<activity android:name=".AdminActivity" />
</application>
Problem
ToolBar on AdminLogin does not allow me to return to LoginActivity when I select the back Button
Admin Login does not work despite entering the hardcoded input for the Admin Name and Password. After clicking on the Login button, the app prompts out a White layout for a few seconds I am brought back to the StartActivity and the Toast message does not show "Failed Login".
SOLUTION
The problem was because the "AdminActivityClass" had
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAdminAuth.getCurrentUser();
if(currentUser == null){
sendUserToStartPage();
}
}
private void sendUserToStartPage(){
Intent intentStart = new Intent(AdminActivity.this, StartActivity.class);
startActivity(intentStart);
finish();
}
Since the Admin login was hardcoded, the currentUser within the FirebaseUser currentUser = mAdminAuth.getCurrentUser(); was set to null. This caused the activity to be sent back to the start page (sendUserToStartPage();)
After posting your full set of code, you should be doing the following.
comment out the sendUserToStartPage(); inside of the currentuser == null and then try.
why? Because the user IS null. why? because you hard coded it into the code. The user admin with password admin does not exist in your Firebase (and if it does, you never checked it prior) so when you sign in, you do not create a session for admin, therefore the current user is null.
try doing this
if ("admin".equals(adminLoginID)) {
if ("admin".equals(adminLoginPassword)) {
//goto activity
}
} else {
//not admin
}
this might be better actually
if (("admin".equals(adminLoginID)) && ("admin".equals(adminLoginPassword))) {
//goto activity
} else {
//not admin
}
or even this....
if (("admin".equals(jAdminID.getText().toString().trim())) && ("admin".equals(jAdminPassword.getText().toString().trim()))) {
//goto activity
} else {
//not admin
}
Try this example in the manifest.
Youre manifest for the activities are missing a theme.
Also, its missed the meta-data.
<activity
android:name=".Leagues.CreateLeague"
android:label="Create League"
android:parentActivityName=".MainActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme2">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.aaa.bbb.MainActivity" />
</activity>
Try like this smartly
take a String variable globally and declare and intialise them
in next step you need to add validations
String str_admin="admin";
if ((str_admin.equals(adminLoginID)) && (str_admin.equals(adminLoginPassword))) {
//pass reference of activity which you want to open it
} else {
//not admin
}
Happy to help yoh
My app is unable to move to the 2nd activity that's StartingPoint after successfully launching the splash activity. App closes saying "unfortunately theNewBoston has stopped working."
I am attaching the relevant files. hope someone can help me with this.
StartingPoint.java
package com.example.thenewboston;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class StartingPoint extends Activity {
int counter;
Button add,sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
counter=0;
add=(Button)findViewById(R.id.addButton);
sub=(Button)findViewById(R.id.subButton);
display=(TextView) findViewById(R.id.display);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is = " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is = " + counter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.starting_point, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Splash.java
package com.example.thenewboston;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity{
#Override
public void onCreate(Bundle TV) {
// TODO Auto-generated method stub
super.onCreate(TV);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openStatingPoint= new Intent("com.thenewboston.StartingPoint");
startActivity(openStatingPoint);
}
}
};
timer.start();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.thenewboston"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="23"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".StartingPoint"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.thenewboston.StartingPoint" />
<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>
Try to change your code as below:
Intent openStatingPoint= new Intent(Splash.this,StartingPoint.class);
startActivity(openStatingPoint);
Explanation:
The constructor used here takes two parameters:
A Context as its first parameter (Splash.this is used because the Activity class is a subclass of Context)
The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started, here is StartingPoint.class)
See more Build an Intent
Thread class doesn't work on UI Thread so that instead of using Thread class use Handler class as follows -
Splash.java
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent openStatingPoint= new Intent(Splash.this,StartingPoint.class); // Use Explicit Intents
startActivity(openStatingPoint);
finish();
}
}, 5000); //time in milliseconds
check your logcat for the exception stack trace, it could be many reasons.
and
So I just started working on this project and part of it is sending packages of information from an app in Java to another Unity app.
I have been trying to follow this tutorial but I have problems getting it to work and even somewhat understanding it a bit since I have not worked with Java before.
Here is the current code I have so far.
Main Activity Class
package com.example.service3;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
startService(new Intent(this, MyService.class));
}
#Override
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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Sender class
package com.example.service3;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class MyService extends Service
{
private final Handler handler = new Handler();
private int numIntent;
// It's the code we want our Handler to execute to send data
private Runnable sendData = new Runnable() {
// the specific method which will be executed by the handler
public void run() {
numIntent++;
// sendIntent is the object that will be broadcast outside our app
Intent sendIntent = new Intent();
// We add flags for example to work from background
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_INCLUDE_STOPPED_PACKAGES );
// SetAction uses a string which is an important name as it identifies the sender of the itent and that we will give to the receiver to know what to listen.
// By convention, it's suggested to use the current package name
sendIntent.setAction("com.example.service3");
// Here we fill the Intent with our data, here just a string with an incremented number in it.
sendIntent.putExtra(Intent.EXTRA_TEXT, "Intent "+numIntent);
// And here it goes ! our message is send to any other app that want to listen to it.
sendBroadcast(sendIntent);
// In our case we run this method each second with postDelayed
handler.removeCallbacks(this);
handler.postDelayed(this, 1000);
}
};
#Override
public void onStart(Intent intent, int startid) {
numIntent = 0;
// We first start the Handler
handler.removeCallbacks(sendData);
handler.postDelayed(sendData, 1000);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
XML for Sender
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.service3.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:enabled="true" android:name="com.example.service3.MyService" />
</application>
Receiver Class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Receiver extends BroadcastReceiver
{
private static Receiver instance;
public static String text ="1";
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
String sentIntent = intent.getStringExtra(Intent.EXTRA_TEXT);
text = "-1";
}
public static void createInstance()
{
if(instance == null)
{
instance = new Receiver();
}
}
}
Unity Android Manifest
<application android:theme="#android:style/Theme.NoTitleBar.Fullscreen" android:icon="#drawable/app_icon" android:label="#string/app_name" android:debuggable="false" android:isGame="true" android:banner="#drawable/app_banner">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="#string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<receiver android:name="com.example.receiver3.MyReceiver" >
<intent-filter>
<action android:name="com.example.receiver3" ></action>
</intent-filter>
</receiver>
</application>
I realise this is a massively large post but I simply do not know what to do at this point and am somewhat considering backing out of the project for the fact that I have no idea how to get Java to communicate with Unity.
Thanks in advance.