Sie sind auf Seite 1von 10

package com.digipodium.ava.

eva;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuAdapter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.gson.JsonElement;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ArrayList;
import java.util.Locale;
import ai.api.model.Result;
import ai.api.AIDataService;
import ai.api.AIListener;
import ai.api.android.AIConfiguration;
import ai.api.android.AIService;
import ai.api.model.AIError;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.AIServiceException;
import pub.devrel.easypermissions.EasyPermissions;

import static android.Manifest.permission.CAMERA;


import static android.Manifest.permission.INTERNET;
import static android.Manifest.permission.READ_CALENDAR;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.SEND_SMS;
import static android.Manifest.permission.SET_ALARM;

public class HomePage extends AppCompatActivity implements RemoveClickListner,AIListener,


PopupMenu.OnMenuItemClickListener {

private static final int REQ_CODE_SPEECH_INPUT = 100;


private FirebaseAuth mAuth;
private RecyclerView mMyRecyclerView;
private RecyclerAdapter mRecyclerAdapter;
private TextToSpeech mTextToSpeech;
ArrayList<MessageModel>mArrayList=new ArrayList<>();
private AIService mAiService;
private AIDataService mAiDataService;
private AIRequest mAiRequest;
private FloatingActionButton mFab;
private SharedPreferences mSettings;
private float mRate;
private float mPitch;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);

mFab = findViewById( R.id.fab );


mFab.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
showPopup(v);
}
} );

String[] perms = new String[]{SET_ALARM, RECORD_AUDIO, INTERNET,SEND_SMS,READ_CALENDAR,CAMERA };


mAuth = FirebaseAuth.getInstance();
mMyRecyclerView = findViewById(R.id.myRecyclerView);
final LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mMyRecyclerView.setLayoutManager(linearLayoutManager);
Button mAskButton=findViewById(R.id.askButton);
mRecyclerAdapter = new RecyclerAdapter(mArrayList,this);
if (!EasyPermissions.hasPermissions(this, perms)) {
EasyPermissions.requestPermissions(this, "Permission Granted", 5, perms);

}
mMyRecyclerView.setAdapter(mRecyclerAdapter);

mAskButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAiService.startListening();
speakout();
}
});

//text to speeech
mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
mTextToSpeech.setLanguage(Locale.US);
mTextToSpeech.setPitch( mPitch );
mTextToSpeech.setSpeechRate( mRate );
}else {
Toast.makeText(HomePage.this, "Language Not Supported", Toast.LENGTH_SHORT).show();
}
}
});//b2feb3c3826449aeaff4f5def4107c3b
//97adf74e53334d2f8b628847e064ca9e
//AIListener
final AIConfiguration config= new AIConfiguration("97adf74e53334d2f8b628847e064ca9e",
AIConfiguration.SupportedLanguages.English,AIConfiguration.RecognitionEngine.System);
mAiDataService = new AIDataService(config);
mAiRequest = new AIRequest();
mAiService = AIService.getService( this,config );
mAiService.setListener( this );
mSettings = getSharedPreferences( "settings", MODE_PRIVATE );
mRate = mSettings.getFloat( "rate", 1f );
mPitch = mSettings.getFloat( "pitch", 1f );
}

private void showPopup(View view) {


PopupMenu popupMenu=new PopupMenu( this,view );
MenuInflater menuInflater=popupMenu.getMenuInflater();
menuInflater.inflate( R.menu.main_menu,popupMenu.getMenu() );
popupMenu.setOnMenuItemClickListener( this );
popupMenu.show();
}

private void speakout() {


Intent intent=new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH );
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault() );
intent.putExtra( RecognizerIntent.EXTRA_PROMPT,"Hi Ask Something" );

try{
startActivityForResult( intent,REQ_CODE_SPEECH_INPUT );
}
catch (ActivityNotFoundException e){
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQ_CODE_SPEECH_INPUT:
if(resultCode==RESULT_OK && data !=null){
MessageModel model = new MessageModel();
final ArrayList<String> res=data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS );
model.setInput(res.get(0));
mArrayList.add( model);

final String messageIn=String.valueOf(res);


if(!messageIn.equals("")){
mAiRequest.setQuery(messageIn);
new AsyncTask<AIRequest,Void,AIResponse>(){

@Override
protected AIResponse doInBackground(AIRequest... aiRequests) {
final AIRequest request=aiRequests[0];
try{ final AIResponse response=mAiDataService.request( mAiRequest );
return response;

} catch (AIServiceException e){

return null;
}

@Override
protected void onPostExecute(AIResponse aiResponse) {
if(aiResponse!=null){
if (aiResponse!=null){
Result result=aiResponse.getResult();
String action = result.getAction();
handleAction( action,result );
String reply = result.getFulfillment().getSpeech();
if(!reply.equals( "" )){
mTextToSpeech.speak(reply,TextToSpeech.QUEUE_FLUSH,null);
}
MessageModel messageModel=new MessageModel( );
messageModel.setInput(reply);
mArrayList.add( messageModel );

runOnUiThread(new Runnable() {
@Override
public void run() {
mRecyclerAdapter.notifyDataSetChanged();
if(mRecyclerAdapter.getItemCount()>1){
mMyRecyclerView.getLayoutManager()

.smoothScrollToPosition(mMyRecyclerView,null,mRecyclerAdapter.getItemCount()-1);

}
}

});
}
}
}
}.execute(mAiRequest);
}else {
mAiService.startListening();
}

}break;
}}
private void handleAction(String action, Result result) {
HashMap<String, JsonElement> map = result.getParameters();
switch (action) {
//1.
case "input.send.messages":
String message=null;
Intent messageIntent=new Intent(Intent.ACTION_SEND);
messageIntent.setType("text/plain");
messageIntent.putExtra("sms_body",message);
startActivity(messageIntent);

break;
//2.
case"input.search.on":
String searchOn="";
try{
JsonElement query=map.get("Query");
searchOn=query.getAsJsonPrimitive().getAsString();
}catch (Exception e){

}
Intent intentSearch=new Intent( Intent.ACTION_VIEW,
Uri.parse( "https://www.google.co.in/search?q=<searchOn> ") );
startActivity(intentSearch);

break;
//3.
case"input.calendar":
String title=null;
long begin=0;
long end=0;
Intent calender=new Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.Events.TITLE,title)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,begin)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,end);
startActivity(calender);
break;
case "open.gmail":
Intent intentGmail = getPackageManager()
.getLaunchIntentForPackage("com.google.android.gm");
startActivity(intentGmail);
break;
//4.
case "input.send.email":
String[] addresses={};
String subject=null;
String messagesBody=null;
Intent emailsend=new Intent(Intent.ACTION_SEND);
emailsend.setType("*/*");
emailsend.putExtra(Intent.EXTRA_EMAIL,addresses);
emailsend.putExtra(Intent.EXTRA_SUBJECT,subject);
emailsend.putExtra(Intent.EXTRA_TEXT,messagesBody);
startActivity(emailsend);

break;//5
case "open.whatsapp":
Intent intentWhat=getPackageManager()
.getLaunchIntentForPackage( "com.whatsapp" );
startActivity(intentWhat);
break;
case "open paytm":
Intent intentpay=getPackageManager()
.getLaunchIntentForPackage( "com.paytm");
startActivity(intentpay);
break;
case "input.Messenger":
Intent intentMess=getPackageManager()
.getLaunchIntentForPackage( "com.facebook.orca" );
startActivity(intentMess);
break;
//5.//com.google.android.apps.docs
case "input.drive.app":
Intent intentcale=getPackageManager()
.getLaunchIntentForPackage( "com.google.android.apps.docs" );
startActivity(intentcale);
break;
case "input.calender.app":
Intent intentcalender=getPackageManager()
.getLaunchIntentForPackage( "com.android.calendar" );
startActivity(intentcalender);
break;
case "input.open.youtube":

Intent appIntent = new Intent(Intent.ACTION_VIEW)


.setPackage("com.google.android.youtube");

Intent webIntent = new Intent(Intent.ACTION_VIEW,


Uri.parse("http://www.youtube.com"));
try {
startActivity(appIntent);
} catch (ActivityNotFoundException ex) {
startActivity(webIntent);
}
break;
//6.
case "web.search":
Uri uriUrl = Uri.parse( "http://www.google.com/" );
Intent web = new Intent( Intent.ACTION_VIEW, uriUrl );
startActivity( web );

break;
//7.
case "playmusic":
if (map != null) {
Toast.makeText( this, "music", Toast.LENGTH_SHORT ).show();
}
Intent intent = Intent.makeMainSelectorActivity( Intent.ACTION_MAIN,
Intent.CATEGORY_APP_MUSIC );
startActivity( intent );
break;
//8.
case "capture.video":
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivity(takeVideoIntent);
break;
//9.
case "record.audio":
Intent recordingIntent =
new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivity(recordingIntent);
break;
//10.
case "edit.contact":
Intent intentInsertEdit = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intentInsertEdit.setType( ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivity(intentInsertEdit);
break;
//11.rong
case "input.open.calculator":
Intent intentCal = new Intent()
.setAction(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_APP_CALCULATOR)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentCal);
break;
//12.rong
/*case "open.app":
String appName="";
try{
JsonElement appJ=map.get( "name" );
appName=appJ.getAsJsonObject().toString();
}catch(Exception e){

}
Intent openIntent= new Intent(Intent.ACTION_VIEW)
.setPackage("com.google.android"+appName);
startActivity(openIntent);
break;*/
//13.
case "show.places":
String loc = "";
try {
JsonElement placeJ = map.get( "location" );
loc = placeJ.getAsJsonObject().get( "business-name" ).toString().replaceAll( "\"",
"" );
} catch (Exception e) {

}
Intent placesIntent = new Intent( Intent.ACTION_VIEW, Uri.parse( "geo:0,0?q=" + loc ) );
placesIntent.setPackage( "com.google.android.apps.maps" );
startActivity( placesIntent );
break;
//14.
case "input.camera":
Intent cam = new Intent( MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA );
startActivity( cam );
break;
//15.wrong
case "input.phone":
int phonenumber = 0;
try {

JsonElement numJ = map.get( "number" );


String number = numJ.getAsJsonPrimitive().getAsString();
phonenumber = Integer.parseInt( number );
} catch (Exception e) {

}
Intent phonedialer = new Intent( Intent.ACTION_CALL)
.setData( Uri.parse( "tel:" + phonenumber ) );
startActivity( phonedialer );
break;
//16.wrong
case "make.call":

String name = "";

try{
JsonElement nameJ=map.get( "name" );
name=nameJ.getAsJsonPrimitive().getAsString();
if(name!=null){
Uri conatactUri= Uri.parse( name );
String[] pro=new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor=getContentResolver()
.query( conatactUri,pro, null,null,null);

if(cursor!=null && cursor.moveToFirst()){


int numIndex=cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER );
String num1=cursor.getString( numIndex );

}
}
}catch (Exception e){

Intent intent1=new Intent( Intent.ACTION_PICK ,Uri.parse("tel:"+name))


.setType( ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE );
startActivity(intent1);

break;

//17.

case "input.alarm":
int hour = 0;
int min = 0;
int sec = 0;
try {
JsonElement timeJ = map.get("time");
String time = timeJ.getAsJsonPrimitive().getAsString();
String[] alarmtime = time.split(":");
hour = Integer.parseInt(alarmtime[0]);
min = Integer.parseInt(alarmtime[1]);
sec = Integer.parseInt(alarmtime[2]);
} catch (Exception e) {
//default time using Calendar
Calendar currentTime=Calendar.getInstance();
currentTime.set(Calendar.HOUR,hour);
currentTime.set(Calendar.MINUTE,min);
currentTime.set(Calendar.SECOND,sec);

Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);


i.putExtra(AlarmClock.EXTRA_MESSAGE, "New Alarm");
i.putExtra(AlarmClock.EXTRA_HOUR, hour);
i.putExtra(AlarmClock.EXTRA_MINUTES, min);
startActivity(i);

break;
//18.
case "open.playstore":
try {
startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse(
"market://details?id=PackageName" ) ) );
}catch(Exception e){
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=PackageName")));
}

break;
case "open.wikipedia":
Intent wiki= new Intent( Intent.ACTION_VIEW, Uri.parse( "https://www.wikipedia.org/" )
);
startActivity( wiki);
break;

case "input.facebook":

Intent faceBook=new Intent( Intent.ACTION_VIEW,Uri.parse(


"https://www.facebook.com/" ) );
Intent facebookApp=getPackageManager()
.getLaunchIntentForPackage( "com.facebook.katana" );
try{
startActivity(facebookApp);
}
catch (Exception e){
startActivity(faceBook);
}
break;

}
}

@Override
public void OnRemoveclick(int index) {

@Override
public void onResult(AIResponse result) {
Result response = result.getResult();

// Get parameters
MessageModel model=new MessageModel( );
model.setInput("Query:"+response.getResolvedQuery()+"\nAction:"+ response.getAction());
mArrayList.add( model );

@Override
public void onError(AIError error) {

@Override
public void onAudioLevel(float level) {

@Override
public void onListeningStarted() {

@Override
public void onListeningCanceled() {

@Override
public void onListeningFinished() {

@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.aboutbtn:
AlertDialog.Builder builder=new AlertDialog.Builder( this );
LayoutInflater layoutInflater = getLayoutInflater();
View inflate = layoutInflater.inflate( R.layout.about_dialog_box, null );
builder.setView( inflate );
AlertDialog dialog=builder.create();
dialog.show();
return true;

case R.id.settingBtn:
startActivity(new Intent( this ,SettingActivity.class ));
return true;

case R.id.etProfile:
gotoProfile();
return true;
case R.id.feedBackBtn:
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{
getString(R.string.mail_feedback_email) });
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.mail_feedback_subject));
intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.mail_feedback_message));
startActivity(Intent.createChooser(intent, getString(R.string.title_send_feedback)));
return true;
case R.id.ratingBtn:
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=PackageName")));
return true;
case R.id.btnSignout:
signOutFunc();
return true;

}
return false;
}

private void gotoProfile() {


startActivity(new Intent(this,ProfileActivity.class ));
}

private void signOutFunc() {


mAuth.signOut();
startActivity(new Intent( this,MainActivity.class ));
finish();
}

@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomePage.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();

Das könnte Ihnen auch gefallen