Related
I am using and android 2.2 phone for testing and getting an error which is driving me crazy
07-27 01:24:55.692: W/System.err(14319): java.lang.ClassNotFoundException: com.shoaib.AndroidCCL.MyClass in loader [email protected]
Can someone help me what to do now..i have tried various suggested solutions on different posts
First I wrote the following class:
Code:
package org.shoaib.androidccl;
import android.util.Log;
public class MyClass {
public MyClass() {
Log.d(MyClass.class.getName(), "MyClass: constructor called.");
}
public void doSomething() {
Log.d(MyClass.class.getName(), "MyClass: doSomething() called.");
}
}
And I packaged it in a DEX file that I saved on my device's SD card as `/sdcard/testdex.jar`.
Then I wrote the program below, after having removed `MyClass` from my Eclipse project and cleaned it:
Code:
public class Main extends Activity {
[user=1299008]@supp[/user]ressWarnings("unchecked")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
final String libPath = Environment.getExternalStorageDirectory() + "/testdex.jar";
final File tmpDir = getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("org.shoaib.androidccl.MyClass");
final Object myInstance = classToLoad.newInstance();
final Method doSomething = classToLoad.getMethod("doSomething");
doSomething.invoke(myInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
}
As far as I know you can't load external dex classes (and certainly not a jar file), the only ones that can be loaded are the ones packaged in the classes.dex file inside the APK and protected by its signature and certificate.
This would be quite a security flaw if your app could be "clean" at install but then download malicious classes and execute them.
hello friends i'm new here and sorry for my question i'm big beginner and an autolearner.
i'm doing an app for android basicaly mock up. and i created a projectwith drawer menu and menu item are stocked in string not in array.
when i run it if i click on an item the number of row of the item appear in the mainactivity.xml what i realy want is to start a new activity here is my code i hope i can get help here,
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
canempire said:
hello friends i'm new here and sorry for my question i'm big beginner and an autolearner.
i'm doing an app for android basicaly mock up. and i created a projectwith drawer menu and menu item are stocked in string not in array.
when i run it if i click on an item the number of row of the item appear in the mainactivity.xml what i realy want is to start a new activity here is my code i hope i can get help here,
Click to expand...
Click to collapse
Modify your onNavigationDrawerItemSelected method as follows
PHP:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
Fragment yourfragment = new Yourfragment();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
,beginTransaction();
fragmentTransaction.replace(R.id.container, yourfragment );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,destination.class);
startActivity(intent);
break;
case 2:
//To do something else like a dialog or a toast
Toast.maketext(context,"Sample Toast",Tosat.LENGTH_LONG).show();
break;
}
}
hello friend thank you very much for your response i edited my code like this
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
FragmentVue1 FragmentVue1 = new FragmentVue1();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fragmentTransaction = fragmentManager;
beginTransaction();
fragmentTransaction.replace(R.id.container, FragmentVue1 );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity.intent();
break;
FragmentVue1 is the name of my activity 1 and the activity load the layout, the code i posted up is little edited than than that you gave me on up reply, because eclipse stress it that suggested me some code to change for exemple
HTML:
Fragment Frgment1 = new FragmentVue1();
raplace in this code is still empty and eclipse ask me to Add cast method receiver
HTML:
fragmentTransaction.replace(R.id.container, FragmentVue1 );
and in this code too fro commit
HTML:
fragmentTransaction.commit();
for this code
HTML:
startActivity.intent();
eclipse is asking me to crete local variable startActivity, create field starActivity,create parameter startActivity create class, and constant .
i'm sorry if i bring to difficult place i really need it to change layout(fragment) to start it just for show a mock up
canempire said:
hello friend thank you very much for your response i edited my code like this
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
FragmentVue1 FragmentVue1 = new FragmentVue1();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fragmentTransaction = fragmentManager;
beginTransaction();
fragmentTransaction.replace(R.id.container, FragmentVue1 );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity.intent();
break;
FragmentVue1 is the name of my activity 1 and the activity load the layout, the code i posted up is little edited than than that you gave me on up reply, because eclipse stress it that suggested me some code to change for exemple
HTML:
Fragment Frgment1 = new FragmentVue1();
raplace in this code is still empty and eclipse ask me to Add cast method receiver
HTML:
fragmentTransaction.replace(R.id.container, FragmentVue1 );
and in this code too fro commit
HTML:
fragmentTransaction.commit();
for this code
HTML:
startActivity.intent();
eclipse is asking me to crete local variable startActivity, create field starActivity,create parameter startActivity create class, and constant .
i'm sorry if i bring to difficult place i really need it to change layout(fragment) to start it just for show a mock up
Click to expand...
Click to collapse
I guess using
"startActivity(intent);"
instead of
"startActivity.intent();" will please eclipse
and not to mention will solve the issue
I bet u didn google that
Sent from my GT-S5302 using Tapatalk 2
canempire said:
hello friend thank you very much for your response i edited my code like this
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
//For loading a fragment
FragmentVue1 FragmentVue1 = new FragmentVue1();
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fragmentTransaction = fragmentManager;
beginTransaction();
fragmentTransaction.replace(R.id.container, FragmentVue1 );
onSectionAttached(0);
fragmentTransaction.commit();
break;
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity.intent();
break;
FragmentVue1 is the name of my activity 1 and the activity load the layout, the code i posted up is little edited than than that you gave me on up reply, because eclipse stress it that suggested me some code to change for exemple
HTML:
Fragment Frgment1 = new FragmentVue1();
raplace in this code is still empty and eclipse ask me to Add cast method receiver
HTML:
fragmentTransaction.replace(R.id.container, FragmentVue1 );
and in this code too fro commit
HTML:
fragmentTransaction.commit();
for this code
HTML:
startActivity.intent();
eclipse is asking me to crete local variable startActivity, create field starActivity,create parameter startActivity create class, and constant .
i'm sorry if i bring to difficult place i really need it to change layout(fragment) to start it just for show a mock up
Click to expand...
Click to collapse
you don't need to use any code present in case 0 if you are not loading a fragment. I just wrote that to make sure you know the difference between starting an activity and a fragment.
If you just want too start an activity just use what is inside case 1.
and as @sak-venom1997 said it should be startActivity(intent) instead of startActivity.intent(). My bad (i am a confused person )
so suppose FragmentVue1 is your activity's name and you want to open it on clicking nth item of navigation drawer use
PHP:
case n:
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
gh0stslayer said:
you don't need to use any code present in case 0 if you are not loading a fragment. I just wrote that to make sure you know the difference between starting an activity and a fragment.
If you just want too start an activity just use what is inside case 1.
and as @sak-venom1997 said it should be startActivity(intent) instead of startActivity.intent(). My bad (i am a confused person )
so suppose FragmentVue1 is your activity's name and you want to open it on clicking nth item of navigation drawer use
PHP:
case n:
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
Click to expand...
Click to collapse
thank you very much for yours reply both are usefully @sak-venom1997
yes FragmentVue1 is my activity it load a layout the reality is i know difference between Activity and Layout but no the both with Fragment.
now it working but the MainActivity is empty when i start the app and i find a warning in code below case 1 break i copied the warning in message in the below code in the line of warning
PHP:
private void onSectionAttached(int i) {
// TODO Auto-generated method stub
}
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}
canempire said:
thank you very much for yours reply both are usefully @sak-venom1997
yes FragmentVue1 is my activity it load a layout the reality is i know difference between Activity and Layout but no the both with Fragment.
now it working but the MainActivity is empty when i start the app and i find a warning in code below case 1 break i copied the warning in message in the below code in the line of warning
PHP:
private void onSectionAttached(int i) {
// TODO Auto-generated method stub
}
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}
Click to expand...
Click to collapse
If i understand you the right way, you are extending Fragment. In this case you are overriding some methods, but dont modify them. How did you get the code? Via the eclipse menu saying "override/implement methods"? Or did you copy the code from somewhere? If you really need to keep the code, i think you have to call super in the method.
Gesendet von meinem SM-N9005 mit Tapatalk
GalaxyInABox said:
If i understand you the right way, you are extending Fragment. In this case you are overriding some methods, but dont modify them. How did you get the code? Via the eclipse menu saying "override/implement methods"? Or did you copy the code from somewhere? If you really need to keep the code, i think you have to call super in the method.
Gesendet von meinem SM-N9005 mit Tapatalk
Click to expand...
Click to collapse
the code is generated when i created the project it is a part of MainActivity.java code it didn't have warning message before i add
PHP:
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
but why the main activity (fragment) is empty?? now :crying:
can someone help me please???
FragmentVue1 isi an Activity it is FragmentVue1.java and the code is
PHP:
package com.projectmockup.cypruscityguide;
import com.projectmockup.cypruscityguide.R;
import android.app.Activity;
import android.os.Bundle;
public class FragmentVue1 extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel);
}
}
please help when i start the application the Fragment_main.xml is empty but before i use this code in MainActivity
PHP:
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
the content of Fragment_main.xml was visible
i check below in the MainActivity and i found this code with alert
PHP:
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}
canempire said:
FragmentVue1 isi an Activity it is FragmentVue1.java and the code is
PHP:
package com.projectmockup.cypruscityguide;
import com.projectmockup.cypruscityguide.R;
import android.app.Activity;
import android.os.Bundle;
public class FragmentVue1 extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel);
}
}
please help when i start the application the Fragment_main.xml is empty but before i use this code in MainActivity
PHP:
case 1:
//To start a new activity
Intent intent = new Intent(this,FragmentVue1.class);
startActivity(intent);
break;
the content of Fragment_main.xml was visible
i check below in the MainActivity and i found this code with alert
PHP:
private void beginTransaction() { // WARNING: The method beginTransaction() from the type MainActivity is never used locally
// TODO Auto-generated method stub
}
private FragmentManager getSupportFragmentManager() {//WARNING:The method getSupportFragmentManager() from the type MainActivity is never used locally
// TODO Auto-generated method stub
return null;
}
Click to expand...
Click to collapse
You don't need to add these lines, they are for opening a fragment. I just provided them to help you know how to open a fragment from navigation drawer.
i am trying to list files of root folders using roottools libary .here is the code
Code:
public ArrayList<File> listFiles(final Context c,final String path) {
final ArrayList<File> a=new ArrayList<File>();
Command command = new Command(0, "ls "+path)
{
@Override
public void commandOutput(int i, String s) {
File f=new File(path+"/"+s);
a.add(f);}
@Override
public void commandTerminated(int i, String s) {
}
@Override
public void commandCompleted(int i, int i2) {
//want to arraylist return from here
}
};
try {
RootTools.getShell(true).add(command);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
now problem is that if i return arraylist<file> from the end of method,its size is zero,to solve it i must return the arraylist from commandCompleted
method.but i am not able to accomplish that.So please solve my problem
Maybee arraylist as static outside your function? So on top of source file? Not sure but maybee
{
"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 this Tutorial I try to explain general aspects of Cloud Computing & Cloud Concepts & Authentication You will learn What is Cloud & If already know basics of Android Programming, you will be able to develop your Cloud Base App after reading carefully this guide.
Featured By XDA
Aamir Siddiqui | May 19, 2016
XDA Senior Member Geeks Empire has posted an extensive tutorial on developing a cloud based app.
The tutorial teaches users how to make use of Google Cloud and Firebase to achieve their goals.
Click to expand...
Click to collapse
Why are so many businesses moving to the cloud? It’s because cloud computing increases efficiency, helps improve cash flow and offers many more benefits…Here's ten of the best.
1. Flexibility
2. Disaster recovery
3. Automatic software updates
4. Capital-expenditure Free
5. Increased collaboration
6. Work from anywhere
7. Document control
8. Security
9. Competitiveness
10. Environmentally friendly
READ MORE
Click to expand...
Click to collapse
If you want to design & develop cloud service for your business it is better to understand What you Know & Need.
Cloud Services categorized into 3 basic models:
- Infrastructure-as-a-Service (IaaS)
- Platform-as-a-Service (PaaS)
- Software-as-a-Service (SaaS)
Click to expand...
Click to collapse
Try to read again carefully All descriptions & Link above to get reach knowledge of Cloud.
In This Tutorial I used All Alphabet Services. Google Cloud, Firebase, Google Play Services & etc.
I prefer Alphabet cause It is Google
“Firebase — a powerful platform for building iOS, Android, and web-based apps, offering real-time data storage and synchronization, user authentication, and more.”
Click to expand...
Click to collapse
INDEX
* Data Transferring *
- FireBase Cloud Service
* Authentication *
- Google Account By GoogleSignIn API
- Twitter By Fabric API
- Email/Pass By Firebase API
# Let Start #
What you Need to Continue is;
1. Google Account
2. Ability to Create Hello World! Project in Android Studio
Click to expand...
Click to collapse
* Application Configuration
Run Android Studio & Create New Project with Blank Activity. (Set Proper AppName & Package)
After Gradle Building finished go to File > Project Structure > Cloud & Enable Firebase.
Go to Manifest > Add Get_Account & Internet Permissions above the <application />
Code:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
then Inside Application tag add Google_Play_Service <meta-data />
Code:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
Then Open build.gradle (Module: App) & Add these excludes to prevent errors during test process inside android{}
Code:
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
Also Add this library for auth-process into dependencies{}
Code:
compile 'com.google.android.gms:play-services-auth:8.4.0'
Now your App is Ready to Add Codes for Cloud API But your Need to Configure Cloud Side too.
* Google Cloud & Firebase Configuration
Here some parts doesn't need for beginning Android Coding But It can be tricky & easy for you to do everything on Browser for Google Section and then Focus on Coding. At End you can Review All Parts & Test it by yourself. I will explain more about each part.
Generate your Sign APK to Get SHA-1 Key
Code:
keytool -list -v -keystore '/PATH/TO/kEY_STORE'
To Transfer Data to Cloud you need to Have a Cloud Service. Here I am using Firebase.
Go to www.Firebase.com & Login with your Google Account.
Firebase will automatically Create a Project for you named 'MY FIRST APP' that you can delete or modify it.
Firebase has Free Plan for Small Business, Testing & etc. So after you learn more about cloud you can upgrade your plan for existing projects.
The URL of Firebase for your Project is Like this
HTML:
https://YOUR_APP_NAME.firebaseio.com/
Every task with Firebase API needs this URL.
Go to https://Console.Gloud.Google.com Sign-Up & Get 60 Days Trial Period & 300$ to spend on Google Cloud Platform.
So Feel Free to Create Projects & Enabling APIs.
After Creating Google Cloud Project go to Project Dashboard & from Left Panel navigate to API Manager > Credentials. Click on Create Credential & Select OAuth client ID After Loading New Page Select Android Then Create. Now Set Carefully your SHA-1 key & Android App PackageName then Save.
Go to https://Developers.Google.com/ First of All If you are new to Developing Spend some times in this page & Enjoy All Google Services for Everything. :good:
Then Navigate to Google Service for Mobile > Android > Sign-In with Google > Click Get Start > Scroll Down > Click Get Configuration File.
Again Type your Android App PackageName then Click Continue & Type SHA-1 Key & Click ENABLE GOOGLE SIGN-IN after that Scroll Down and Click on Generate Configuration File and Download the File.
Copy google-service.json File & Paste it to App Level Project.
Code:
To do this Now Open Android Studio Change View of Project Explorer from Android View to Project View.
Expand Project and Paste JSON file under the APP Level.
http://dl-1.va.us.xda-developers.co....jpg?key=fJhht_mZE9VqhL4UuJvbow&ts=1464144452
Now you are ready to use Firebase Services & Login with Google.
Next Post is About Working with Firebase Send/Receive Data.
Oo. DOWNLOAD .oO
SOURCE.CODE
APK.FILE
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
Google Cloud & Firebase [Data Transferring]
Now It is time to Focus on Coding. It is not difficult to understand Firebase API But Using URL carefully to Create New User, Data, Section & etc is important.
Open MainActivity.Java
At First the Class must extended from Fragment that required for Firebase API (& later for Google Sign-In). In this case I use AppCompatActivity.
Code:
public class MainActivity extends AppCompatActivity{}
To work with Firebase API you have to define it like other objects.
You can do it when you need it Or define it at first part of app onCreate(Bundle){}
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
[B]Firebase.setAndroidContext(getApplicationContext());[/B]
After that you need to declare instance of your views. For Example I declare ListView that will use for showing loaded Data.
Code:
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
//built-in adaptor
listView.setAdapter(adapter);
NOTE: Save your Firebase URL to <resource> <string /></resource> Or Save it as Universal String Object inside Class.
For Example Before onCreate(Bundle)
Code:
String FirebaseLink = "https://[B]YOUR_APP_NAME[/B].firebaseio.com/";
String FirebaseTitle = "GeeksEmpire";
String FirebaseSub = "gX";
To Get Data from User you should define input method like <EditText/>
With This methods you can Save Data Locally in Application Private Storage on System
Code:
//Save Content
try {
FileOutputStream fOut = openFileOutput(NAME, MODE_PRIVATE);
fOut.write((DATA).getBytes());
//Always Close All Streams
fOut.close();
fOut.flush();
}
catch (Exception e) {
System.out.println(e);
} finally {}
Code:
//Read-File
public String READ(String S, Context context){
File Fav = new File(S);
String Read = null;
FileInputStream fin;
BufferedReader br = null;
try{
fin = new FileInputStream(Fav);
br = new BufferedReader(new InputStreamReader(fin, "UTF-8"), 1024);
System.out.println(br);
int c;
String temp = "";
while( (c = br.read()) != -1){temp = temp + Character.toString((char)c);}
Read = temp;}
catch(Exception e)
{System.out.println(e);}
finally{try {br.close();} catch (IOException e) {e.printStackTrace();}}
return Read;
}
But to Store Data on Firebase Server you should declare instance of Firebase API, Push & setValue(DATA)
Code:
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String DATA = editText.getText().toString();//"[COLOR=Red][I]GeeksEmpire DataBase on FireBase[/I][/COLOR]"
new Firebase([B]FirebaseLink[/B]/*[COLOR=Red][I]https://YOUR_APP_NAME.firebaseio.com[/I]/[/COLOR]*/ + FirebaseTitle/*[COLOR=Red][I]GeeksEmpire[/I][/COLOR]*/)
.push()
.child(FirebaseSub/*[COLOR=Red][I]gX[/I][/COLOR]*/)
.setValue(DATA);
}
});
Compare red texts with image. Firebase URL is submitted but you can Modify both FirebaseTitle & FirebaseSub.
In this Case I used GeeksEmpire as Title & gX as SubTitle & then Data.
It is depend on your design.
you can set GeeksEmpire as User & gX as Title OR Whatever you need.
Data Uploaded to Server & Now you should make an option to Download them. I created function to gather all components.
Code:
public void SetUpCloudContent(){
Firebase.setAndroidContext(this);
new Firebase(FirebaseLink/*[COLOR=Red]https://YOUR_APP_NAME.firebaseio.com/[/COLOR]*/ + FirebaseTitle/*[COLOR=Red]GeeksEmpire[/COLOR]*/).addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
adapter.add((String)dataSnapshot.child(FirebaseSub/*[COLOR=Red]gX[/COLOR]*/).getValue());//add each value to ListView
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
adapter.remove((String)dataSnapshot.child(FirebaseSub).getValue());
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
public void onCancelled(FirebaseError firebaseError) { }
});
}
To Change Data Just Use ID you got to User (For Example GeeksEmpire > gX) and OverWrite Data.
But here is a method to Delete Data.
// Delete items when clicked
Code:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new Firebase([COLOR=Red]FirebaseLink [/COLOR]+ [COLOR=Red]FirebaseTitle[/COLOR])
.orderByChild([COLOR=Red]FirebaseSub[/COLOR])
.equalTo((String) listView.getItemAtPosition(position)/*[I]get data from ListView[/I]*/)
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
firstChild.getRef().removeValue();
}
}
public void onCancelled(FirebaseError firebaseError) { }
});
return false;
}
});
Sending & Receiving Data to Firebase Cloud Service is Done.
Again It depends on you How to define Users & Create Individual ID for each one.
Next Posts Will Show How to Create Sign-In Options for your App. That Also Help a lot to create Individual ID.
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
Google Account [Authentication]
I used Google API for Google Account Auth cause you can get more info about Google Account to use and customize your App. Info that you cannot retrieve by Firebase.Auth("google"). For Example Account Pic to Use inside your app for user.
(Set Google Account Pic as Pic of Account on your App)
In First Post Google Sign-In Setup Completed.
Sign-In API Enabled & Configuration file add to Project.
Another modification needed to apply on build.gradle (Module: App)
Add this plugin at end of your gradle file.
Code:
apply plugin: 'com.google.gms.google-services'
& Also for build.gradle (Project)
Add this classpath under dependencies {}
Code:
classpath 'com.google.gms:google-services:2.0.0-alpha5'
You should Implement you class to GoogleApiClient.ConnectionCallbacks & GoogleApiClient.OnConnectionFailedListener.
& Add required methods.
Code:
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}
@Override
public void onConnected(@Nullable Bundle bundle) {}
@Override
public void onConnectionSuspended(int i) {}
Define GoogleApiClient as universal variable (Outside of any Function).
Get instance of GoogleApiClient & GoogleSignInOptions onCreate(Bundle).
Code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)//FragmentActivity
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
To perform Sign Action normally button used If you don't want to do it at start up of app.
For this Google Service has its own button design that used in sample. However you can design your own view.
Code:
<com.google.android.gms.common.SignInButton />
Like other Android system function calling we should use Intent to Invoke Google Account Chooser and Get Result on CallBack.
Code:
google.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, [COLOR=Red]7[/COLOR]);
}
});
On result CallBack you should declare GoogleSignResult
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == [COLOR=Red]7[/COLOR]){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess()){
//[B]Handle Security Inside App[/B]
GoogleSignInAccount acct = result.getSignInAccount();
Toast.makeText(getApplicationContext(), "getEmail >> " + [B]acct.getEmail()[/B], Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "getDisplayName >> " + [B]acct.getDisplayName()[/B], Toast.LENGTH_LONG).show();
//Can get more Info by using GoogleSignInAccount
}
}
NOTE: You can use Google Account as UserName for your Users on Firebase & By Calling Sign-In Process at App Start Provide Security for your App.
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
Twitter Account [Authentication]
Authentication by Twitter has Complex aspect.
First you should Create Twitter Account, Then Create Web App through www.twitter.com (to get Public & Secret Key), Enable Twitter on Firebase (Not Required But I recommend it) & Install 3rd-Party Plugin on Android Studio (Fabric API).
Go to https://twitter.com/ & Sign Up then go to https://apps.twitter.com/ & Create App.
Name the App & Write Description & WebSite.
In App Page > Keys & Access Token
. Consumer Key (API Key) = XXXXX
. Consumer Secret (API Secret) = XXXXX
Save these value to resources of your app. res > values > string
Code:
</resources>
<string name="twitter_consumer_key">[B]API Key[/B]</string>
<string name="twitter_consumer_secret">[B]API Secret[/B]</string>
</resources>
- Go to Login & Auth on Firebase Select Twitter & Paste API Key + API Secret.
On Android Studio navigate to File > Setting > Plugin& Search for Fabric (Click Browse)
After Plugin Downloaded It will ask for Restart to Complete Installation.
Then Fabric Plugin icon will appear on toolbar & maybe Right-Panel.
Click on Plugin & Sign Up. Then you will see your current project on Fabric list. Select it & click Next.
From List of All Kits select Twitter & click Install. It will ask for API Key + API Secret
Fabric will Apply All Modification it needs to your project & after that you project will be ready for Twitter Auth.
But for Developer It is always important points to understand every part of tools and apps.
* Fabric Inside build.grade (Module: App)
before Android Plugin
Code:
apply plugin: 'com.android.application'
Add this Script
Code:
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
after Android Plugin set up fabric plugin
Code:
apply plugin: 'io.fabric'
after android{} functions add Fabric Repositories
Code:
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
& Inside dependencies{} add
Code:
compile('com.twitter.sdk.android:twitter:[email protected]') {
transitive = true;
}
* Fabric Inside Manifest
in <application/> add
Code:
<meta-data
android:name="io.fabric.ApiKey"
android:value="API_KEY" />
* Fabric Inside MainActivity Class
before setContentView(VIEW) under onCreate(Bundle)
Code:
TwitterAuthConfig authConfig = new TwitterAuthConfig([COLOR=Red]API_KEY[/COLOR], [COLOR=Red]API_SECRET[/COLOR]);
Fabric.with(this, new Twitter(authConfig));
Fabric Also provides Button design for Twitter with custom features to handle Auth CallBack.
Code:
<com.twitter.sdk.android.core.identity.TwitterLoginButton/>
You define it in layout.xml & then Declare it like normal views on activity.
But performing action is different.
Code:
/*TWITTER Sign-In*/
twitterButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
Toast.makeText(getApplicationContext(), [COLOR=Red][B]result[/B][/COLOR].data.getUserName(), Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {}
});
without any extra Intent it will redirect you to Twitter Auth Page.
Also By using this button you can handle CallBack Result.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
twitterButton.onActivityResult(requestCode, resultCode, [COLOR=Red][B]data[/B][/COLOR]);
}
Also I used Fabric for Twitter Auth cause I can retrieve more Info than Firebase.Auth("twitter").
Fabric Plugin Developed by Twitter Developers So It really works smoothly & really best way to Auth with Twitter Account.
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
Email/Password Account [Authentication]
Auth with Email/Password Using Firebase API is so simple.
Go to Firebase Project Dashboard > Login & Auth & Enable Email & Password Authentication
Define 2 <EditText /> for Email & Password in layout.xml Don't forget to set inputType
Code:
[CENTER][LEFT]Email
<EditText
android:id="@+id/email"
android:inputType="textEmailAddress" />
[/LEFT]
[/CENTER]
Password
<EditText
android:id="@+id/password"
android:inputType="textPassword" />
Declare Firebase & then Set Auth method.
Code:
//Remember from first post
Firebase ref = new Firebase(FirebaseLink/*[COLOR=Red]https://FIREBASE_PROJECT_NAME.firebaseio.com/[/COLOR]*/);
Define Login/SignUp Button and onClick setup Email/Pass Auth
Code:
//E-MAIL SignUp
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "User Created", Toast.LENGTH_LONG).show();
String email = user.getText().toString();
String pass = password.getText().toString();
Firebase ref = new Firebase([COLOR=Red]FirebaseLink[/COLOR]);
ref.createUser([COLOR=Red][B]email[/B][/COLOR], [COLOR=Red][B]pass[/B][/COLOR], new Firebase.ValueResultHandler<Map<String, Object>>() {
@Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
}
@Override
public void onError(FirebaseError firebaseError) {
// there was an error
}
});
}
});
Code:
//E-MAIL Login
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = user.getText().toString();
String pass = password.getText().toString();
Firebase ref = new Firebase([COLOR=Red]FirebaseLink[/COLOR]);
ref.authWithPassword([COLOR=Red][B]email[/B][/COLOR], [COLOR=Red][B]pass[/B][/COLOR], new Firebase.AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Toast.makeText(getApplicationContext(), "User Authenticated", Toast.LENGTH_LONG).show();
}
@Override
public void onAuthenticationError(FirebaseError firebaseError) {}});
}}
});
For this everything provided simply by Firebase API. You completely Handle all process.
Here are more helpful Functions.
Code:
public void [B]ResetPassword[/B](String [COLOR=Red]E_MAIL_ADDRESS[/COLOR]){
Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
ref.resetPassword([COLOR=Red]E_MAIL_ADDRESS[/COLOR], new Firebase.ResultHandler() {
@Override
public void onSuccess() {
// password reset email sent
}
@Override
public void onError(FirebaseError firebaseError) {
// error encountered
}
});
}
Code:
public void [B]ChangePassword[/B](String [COLOR=Red]E_MAIL[/COLOR], String [COLOR=Red]oldPass[/COLOR], String [COLOR=Red]newPass[/COLOR]){
Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
ref.changePassword([COLOR=Red]E_MAIL[/COLOR], [COLOR=Red]oldPass[/COLOR], [COLOR=Red]newPass[/COLOR], new Firebase.ResultHandler() {
@Override
public void onSuccess() {
// password changed
}
@Override
public void onError(FirebaseError firebaseError) {
// error encountered
}
});
}
Code:
public void [B]RemoveAccount[/B](String [COLOR=Red]E_MAIL[/COLOR], String [COLOR=Red]Password[/COLOR]){
Firebase ref = new Firebase("https://[COLOR=Red]<YOUR-FIREBASE-APP>[/COLOR].firebaseio.com");
ref.removeUser([COLOR=Red]E_MAIL[/COLOR], [COLOR=Red]Password[/COLOR], new Firebase.ResultHandler() {
@Override
public void onSuccess() {
// user removed
}
@Override
public void onError(FirebaseError firebaseError) {
// error encountered
}
});
}
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
Info
If you find any mistake Or issue in my codes Please inform me.
Click to expand...
Click to collapse
I will try to Keep this Tutorials Up-to-Date.
Also Add Guide for Other Cloud Services.
Check Out my Open Source Android Applications & Tutorials in my Signature. :good:
Google Firebase.Storage
It s time to do something important with Cloud Service; Upload & Download File.
Google Cloud Service (Firebase) has lots of Useful Features + Really Straight & Manageable API.
First Read Preface Post & Firebase Basics to Prepare your Project for Cloud Services.
Now you will Understand upcoming codes.
Inside build.gradle of AppLevel declare Firebase.Storage SDK in dependencies
Code:
compile 'com.google.firebase:firebase-[B]storage[/B]:9.0.2'
compile 'com.google.firebase:firebase-[B]auth[/B]:9.0.2'
In update Sample Code I created new activity to handle Files. You can do whatever you like.
NOTE: You have to Authenticate Users with Firebase Services to Perform any Server action. For example Uploading File. check out SourceCode
In activity onCreate() declare instance of Firebase.Storage & Firebase.Auth
Code:
firebaseStorage = [B]FirebaseStorage[/B].getInstance();
firebaseAuth = [B]FirebaseAuth[/B].getInstance();
To Perform Both Upload & Download Task you need to create a Reference.
There is different method for creating StorageReference that I chose:
Code:
getReferenceFromUrl() for Uploading
& getFile() for Downloading.
Before anything do Auth Process. As Public APP I used Anonymously option & call the function when Activity Start.
Code:
private void signInAnonymously() {
mAuth.signInAnonymously().addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {}
}).addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {}
});
}
Now you can Add StorageReference & Perform Actions
UPLOAD Function check out SourceCode
Code:
private void uploadFromUri(InputStream fileUri) {
StorageReference mStorageRef = storage.getReferenceFromUrl("gs://[I][COLOR=Red][B][YOUR_FIREBASE_PROJECT_LINK][/B][/COLOR][/I]/");
StorageReference photoRef = mStorageRef.child("Dir").child("File");
UploadTask uploadTask = photoRef.putStream(fileUri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("DONE!");
//Get Download Address for Future
Uri dl = taskSnapshot.getMetadata().getDownloadUrl();
//Save Download Address in App Dir
SharedPreferences sharedpreferences = getSharedPreferences("Info", Context.MODE_PRIVATE);
SharedPreferences.Editor dlLink = sharedpreferences.edit();
dlLink.putString("path", String.valueOf(dl));
dlLink.apply();
infoFile.append("\n" + dl.getPath());
System.out.println("Download >> " + dl);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
System.out.println("!Damn!");
}
});
}
DOWNLOAD Function check out SourceCode
Code:
public void downloadFromUri(StorageReference storageRef) throws Exception {
//Create File
final File localFile = new File(Environment.getExternalStorageDirectory().getPath() + "/CloudAppTest_GeeksEmpire.jpg");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
System.out.println("DONE!");
//Using Downloaded File
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath()); System.out.println("Downloaded >> " + localFile.getAbsolutePath());
imageFile.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}
For Deleting & any Modification you Just Need to Declare StorageReference & Call Functions. check out SourceCode
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
Firebase.RemoteConfiguration
The Most Interesting Features from Google Firebase is Remote Configuration.
It is not difficult to Apply & Super Helpful.
By Adding this Feature to your App you can Remotely Change Value of Defined Variable.
It can be String of InApp Texts Or Integer of InApp Color. Whatever you decide to remotely Config.
And Also Conditional Value. For Example Specific Price Tag for a Region Or even a Single User.
Google Cloud Service (Firebase) has lots of Useful Features + Really Straight & Manageable API.
Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update...
Click to expand...
Click to collapse
First Read Preface Post & Firebase Basics to Prepare your Project for Cloud Services.
Now you will Understand upcoming codes.
Inside build.gradle of AppLevel declare Firebase.Storage SDK in dependencies.
Code:
compile 'com.google.firebase:firebase-config:9.0.2'
Create xml folder into the res directory res/xml.
Now create remote_config_default.xml file to define all default Value & KEY for remote configuration.
For Example: check out SourceCode
Code:
<?xml version="1.0" encoding="utf-8"?>
<!-- START xml_defaults -->
<defaultsMap>
<entry>
[B]<key>[COLOR=Red]KeyToChange[/COLOR]</key>
<value>[COLOR=Red]Content To Change[/COLOR]</value>[/B]
</entry>
</defaultsMap>
<!-- END xml_defaults -->
You Should go to Firebase Console & you Project Dir & Select Remote Config from Left Panel.
Set <key>KeyToChange</key>& Create New Content.
Now go to your Activity Class that want to Handle these changes from cloud & declare FirebaseRemoteConfig & Set Default Value that defined in XML file. check out SourceCode
Code:
firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
firebaseRemoteConfig.setDefaults(R.xml.remote_config_default);
after that you can perform to check If there is New Content & Apply it to your App. check out SourceCode
Code:
public void GetNewContent(){
mFirebaseRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("", "Fetch Succeeded");
// Once the config is successfully fetched it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
} else {
Log.d("", "Fetch failed");
}
[B]//Handle New Content[/B]
textView.setText([B]firebaseRemoteConfig.getString([COLOR=Red]KeyToChange[/COLOR]_String)[/B]);
}
});
}
Thanks for Supporting GeeksEmpire projects
Don't Forget To Hit Thanks
RESERVED 9th
RESERVED 10th
Needed
This tutorial is awesome!
complete and easy to understand
there is few guide about using cloud services
really appreciate :good:
getapp said:
This tutorial is awesome!
complete and easy to understand
there is few guide about using cloud services
really appreciate :good:
Click to expand...
Click to collapse
Thanks for Rating & Review
I am waiting for FeedBackof all users/devs
:good:
Info
James5712 said:
Really good
Click to expand...
Click to collapse
Thanks for Rating & Review :good:
I am waiting for FeedBack of all Users/Devs
Info
Featured By XDA
Top Forum Discussions
Aamir Siddiqui | May 19, 2016
XDA Senior Member Geeks Empire has posted an extensive tutorial on developing a cloud based app.
The tutorial teaches users how to make use of Google Cloud and Firebase to achieve their goals.
Click to expand...
Click to collapse
Thanks for Support XDA-Developer :good:
I am waiting for FeedBack of all Users/Devs
Thanks for your effort :good:
I'm newbie in android programming, but i find this tutorial is usefull :good:
Info
iprabu said:
Thanks for your effort :good:
I'm newbie in android programming, but i find this tutorial is usefull :good:
Click to expand...
Click to collapse
Thanks for Rating & Review
+ There is lots of Android Programming Tutorial by GeeksEmpire
you can find all off them in my signature Or Geeky Tutorial
Also Almost All GeeksEmpire Apps on Google Play Store is OpenSource with Full Code Comments
So you can Check them to learn more
you can find all off them in my signature Or Geeky Open Source Project
Don't Forget to hit Thanks :good:
I am waiting for FeedBack of all Users/Devs
thank you
thank you
black_host said:
thank you
Click to expand...
Click to collapse
Your Welcome.
Remember There is more to come to cover all aspect of Cloud Base Developing
+ Don't Forget to hit Thanks
I am waiting for FeedBack of all Users/Devs
Nice Tutorial will definitely recommend to new devs
Info
AonSyed said:
Nice Tutorial will definitely recommend to new devs
Click to expand...
Click to collapse
Thanks for Rating & Review :good:
These Tutorials are beginning of great lesson for Cloud Base App
I am waiting for FeedBack of all Users/Devs
{
"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 ProjectsDon'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 ProjectsDon'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