Android Studio functions of alert dialog in another java class - java

In my MainActivity.Java, I have an onClickListener in a button that will show an Alert Dialog when it's clicked
scanbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View scanPopup = getLayoutInflater().inflate(R.layout.scan_tab, null);
forScan.setView(scanPopup);
dialog = forScan.create();
dialog.show();
}
});
This is is the ScanTab.Java wherein the AlertDialog will have its functions
package com.example.AppDraft1.activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.AppDraft1.MainActivity;
import com.example.AppDraft1.R;
import com.example.AppDraft1.parser.NdefMessageParser;
import com.example.AppDraft1.record.ParsedNdefRecord;
import java.util.List;
public class ScanTab extends AppCompatActivity {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private TextView text;
private String first, surname, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_tab);
text = (TextView) findViewById(R.id.text);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, this.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
#Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
if (!nfcAdapter.isEnabled())
showWirelessSettings();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null){
nfcAdapter.disableForegroundDispatch(this);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
resolveIntent(intent);
}
private void resolveIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
} else {
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
displayMsgs(msgs);
}
}
private void displayMsgs(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0)
return;
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
text.setText(builder.toString());
Toast.makeText(this, "NFC Tag Detected", Toast.LENGTH_SHORT).show();
sndData();
}
public void sndData(){
String theText = text.getText().toString();
//split data
String[] split = theText.split("/",3);
first = split[0]; //first name
surname = split[1]; //surname
id = split[2]; //id number
Intent intent = new Intent(ScanTab.this, MainActivity.class);
intent.putExtra("FName", first);
intent.putExtra("SName", surname);
intent.putExtra("ID", id);
startActivity(intent);
}
private void showWirelessSettings() {
Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
private String dumpTagData(Tag tag) {
StringBuilder sb = new StringBuilder();
byte[] id = tag.getId();
sb.append("ID (hex): ").append(toHex(id)).append('\n');
sb.append("ID (reversed hex): ").append(toReversedHex(id)).append('\n');
sb.append("ID (dec): ").append(toDec(id)).append('\n');
sb.append("ID (reversed dec): ").append(toReversedDec(id)).append('\n');
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech : tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech : tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
String type = "Unknown";
try {
MifareClassic mifareTag = MifareClassic.get(tag);
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
} catch (Exception e) {
sb.append("Mifare classic error: " + e.getMessage());
}
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
return sb.toString();
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private String toReversedHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
private long toDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private long toReversedDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = bytes.length - 1; i >= 0; --i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
}
When I tested it, the view is working but the functions are absent. How do I embed or make the functions work in the AlertDialog?

Alert Dialogs are meant to 'alert' the user of something, or run code based on input from user in case of input dialog.
If you want to run code in the alert dialog, you can run it before setView of dialog.
Additionally it is not recommended to block user from interacting with app using an Alert Dialog.
If you want to run code from one activity in another, in your case run code in ScanActivity from MainActivity the best way I can think of is Activity RESULTS API which replaced StartActivityForResult [read here]
But I would just recommended you start ScanActivity and show the dialog from there, then you can easily call all methods of ScanActivity.

Related

How to send image as auto reply to Whatsapp in background?

I developed an android app for auto replying to Whatsapp. My app is perfect working for replying with text. But I am unable to send images in auto reply in background.
This activity is for managing notifications.
NotificationService.java
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.SpannableString;
import android.util.Log;
import android.widget.TextView;
import androidx.core.app.NotificationCompat;
import com.templatemela.whatsbot.model.Action;
import com.templatemela.whatsbot.model.AutoReply;
import com.templatemela.whatsbot.model.StatisticsReplyMsgListModel;
import com.templatemela.whatsbot.utilities.Const;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class NotificationService extends NotificationListenerService {
public static final String TAG = "Auto Reply";
private String autoReplyText;
private List<String> cntList;
private String contactType;
private long count = 0;
private List<String> getUserList;
private String headerText;
private String noMatch = "";
private SharedPreference preference;
private int replyTime;
private String sendMessage;
private TextView text;
private Uri string;
private Bitmap bitmap;
#Override
public void onListenerConnected() {
super.onListenerConnected();
Log.e(TAG, "Notification Listener Connected");
}
#Override
public void onCreate() {
super.onCreate();
preference = new SharedPreference(this);
count = preference.getFromPref_Long("Counter");
getUserList = new ArrayList();
cntList = new ArrayList();
Const.staticsReplyList = new ArrayList();
Const.contactList = new ArrayList();
}
#Override
public int onStartCommand(Intent intent, int i, int i2) {
Log.e("Service Class", "Service is started-----");
return Service.START_STICKY;
}
#Override
public void onNotificationRemoved(StatusBarNotification statusBarNotification) {
super.onNotificationRemoved(statusBarNotification);
Log.e("AUTO REPLY", "Notificationremoved");
}
#Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
if (preference.getFromPref_Boolean("CheckedState")) {
boolean fromPref_Boolean = preference.getFromPref_Boolean("ScheduleTime");
Log.e("scheduleTime", fromPref_Boolean + ":::");
contactType = preference.getFromPref_String("ContactType");
Const.contactList = preference.getContactList("ContactList");
try {
if (Const.contactList.isEmpty()) {
Const.contactList = new ArrayList();
}
} catch (Exception unused) {
Const.contactList = new ArrayList();
}
Const.replyList = preference.getList("MessageList");
try {
if (Const.replyList.isEmpty()) {
Const.replyList = new ArrayList();
}
} catch (Exception unused2) {
Const.replyList = new ArrayList();
}
Const.staticsReplyList = preference.getReplyList("StaticsReplyList");
try {
if (Const.staticsReplyList.isEmpty()) {
Const.staticsReplyList = new ArrayList();
}
} catch (Exception e) {
Const.staticsReplyList = new ArrayList();
Log.e("StaticsList", e.getMessage());
}
String fromPref_String = preference.getFromPref_String("BoldHeaderText");
if (fromPref_String.isEmpty()) {
headerText = "*Auto Reply*\n\n";
} else if (fromPref_String.equals(" ")) {
headerText = fromPref_String;
} else {
headerText = "*" + fromPref_String + "*\n\n";
}
autoReplyText = headerText + preference.getFromPref_String("autoReplyText");
if (isScheduleTime(fromPref_Boolean)) {
Log.e("IS SCHEDULE TIME", isScheduleTime(fromPref_Boolean) + "::::");
cancelNotification(statusBarNotification.getKey());
final Action quickReplyAction = NotificationUtils.getQuickReplyAction(statusBarNotification.getNotification(), getPackageName());
Log.e("Action", quickReplyAction + "::Action:");
if (quickReplyAction == null) {
return;
}
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp")||statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp.w4b"))
{
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp")&&preference.getFromPref_Boolean("WAState") ){
final String string = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TITLE);
Log.e("USERNAME", string + ":::");
final String string2 = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TEXT);
if (EveryOne(contactType) || ContactList(contactType, string) || ExceptContactList(contactType, string) || ExceptPhoneList(contactType, string)) {
Log.e("CONTACT TYPE", contactType + "::::");
if (string2 != null && !string2.equalsIgnoreCase("📷 Photo") && isGroupMessageAndReplyAllowed(statusBarNotification) && NotificationUtils.isNewNotification(statusBarNotification) && selfName(statusBarNotification)) {
if (preference.getFromPref_Boolean("Immediately")) {
Log.e("Immediately", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
} else if (preference.getFromPref_Boolean("Time")) {
Log.e("Time", "True");
String fromPref_String2 = preference.getFromPref_String("TimeofMsg");
String fromPref_String3 = preference.getFromPref_String("SpinTime");
if (fromPref_String3.equals("Minutes")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000 * 60;
} else if (fromPref_String3.equals("Seconds")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000;
}
Log.e("REPLY TIME", replyTime + ":::::");
new Handler().postDelayed(new Runnable() {
public void run() {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}, (long) replyTime);
} else if (preference.getFromPref_Boolean("Once")) {
Log.e("Once", "True");
List<String> userList = preference.getUserList("UserList");
getUserList = userList;
try {
if (userList.isEmpty()) {
getUserList = new ArrayList();
}
} catch (Exception e2) {
Log.e("ONCE", e2.getMessage());
getUserList = new ArrayList();
}
if (getUserList.contains(string)) {
stopService(new Intent(getApplicationContext(), getClass()));
} else {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
} else {
Log.e("ELse", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}
}
}
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp.w4b")&&preference.getFromPref_Boolean("WBState")){
final String string = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TITLE);
Log.e("USERNAME", string + ":::");
final String string2 = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TEXT);
if (EveryOne(contactType) || ContactList(contactType, string) || ExceptContactList(contactType, string) || ExceptPhoneList(contactType, string)) {
Log.e("CONTACT TYPE", contactType + "::::");
if (string2 != null && !string2.equalsIgnoreCase("📷 Photo") && isGroupMessageAndReplyAllowed(statusBarNotification) && NotificationUtils.isNewNotification(statusBarNotification) && selfName(statusBarNotification)) {
if (preference.getFromPref_Boolean("Immediately")) {
Log.e("Immediately", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
} else if (preference.getFromPref_Boolean("Time")) {
Log.e("Time", "True");
String fromPref_String2 = preference.getFromPref_String("TimeofMsg");
String fromPref_String3 = preference.getFromPref_String("SpinTime");
if (fromPref_String3.equals("Minutes")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000 * 60;
} else if (fromPref_String3.equals("Seconds")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000;
}
Log.e("REPLY TIME", replyTime + ":::::");
new Handler().postDelayed(new Runnable() {
public void run() {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}, (long) replyTime);
} else if (preference.getFromPref_Boolean("Once")) {
Log.e("Once", "True");
List<String> userList = preference.getUserList("UserList");
getUserList = userList;
try {
if (userList.isEmpty()) {
getUserList = new ArrayList();
}
} catch (Exception e2) {
Log.e("ONCE", e2.getMessage());
getUserList = new ArrayList();
}
if (getUserList.contains(string)) {
stopService(new Intent(getApplicationContext(), getClass()));
} else {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
} else {
Log.e("ELse", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}
}
}
}
else {
Log.e(TAG, "not success");
}
}
}
}
#Override
public void onTaskRemoved(Intent intent) {
super.onTaskRemoved(intent);
Intent intent2 = new Intent(getApplicationContext(), getClass());
intent2.setPackage(getPackageName());
startService(intent2);
}
public void sendMsg(Action action, String str, String str2, String tetStr, Bitmap image4) {
String str3;
String str4;
Intent phonebookIntent = new Intent();
image4 = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
boolean z;
try {
Log.e("RECEIVE MSG", str);
Const.replyList.isEmpty();
boolean z2 = false;
boolean isContain=preference.getFromPref_Boolean("contain");
boolean isExtra=preference.getFromPref_Boolean("exact");
Log.e("rules","contain=="+String.valueOf(isContain)+" "+"exact==="+String.valueOf(isExtra));
boolean fromPref_Boolean = preference.getFromPref_Boolean("customAutoReplySwitch");
Log.e("CustomReply", fromPref_Boolean + ":::");
Iterator<AutoReply> it = Const.replyList.iterator();
while (true) {
if (!it.hasNext()) {
str3 = "autoReplyText";
str4 = "Counter";
z = true;
break;
}
AutoReply next = it.next();
if (isContain?next.getReceiveMsg().equalsIgnoreCase(str)||str.contains(next.getReceiveMsg()):next.getReceiveMsg().equalsIgnoreCase(str)) {
if (fromPref_Boolean) {
long currentTimeMillis = System.currentTimeMillis();
Context applicationContext = getApplicationContext();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
action.sendReply(applicationContext, headerText + next.getSendMsg(), "okay kar", bitmap);
stopService(new Intent(getApplicationContext(), getClass()));
long j = count + 1;
count = j;
preference .addToPref_Long("Counter", j);
sendMessage = next.getSendMsg();
List<StatisticsReplyMsgListModel> list = Const.staticsReplyList;
str3 = "autoReplyText";
str4 = "Counter";
z = true;
StatisticsReplyMsgListModel statisticsReplyMsgListModel = new StatisticsReplyMsgListModel((int) count, next.getSendMsg(), str2, currentTimeMillis);
list.add(statisticsReplyMsgListModel);
preference.setReplyList("StaticsReplyList", Const.staticsReplyList);
if (preference.getFromPref_Boolean("Once") && !Const.userList.contains(str2)) {
Const.userList.add(str2);
preference.setUserList("UserList", Const.userList);
}
} else {
str3 = "autoReplyText";
str4 = "Counter";
z = true;
stopService(new Intent(getApplicationContext(), getClass()));
}
z2 = true;
}
}
if (!z2 && preference.getFromPref_Boolean("autoReplyTextSwitch") == z) {
Log.e(TAG, "Else");
if (autoReplyText.equals(str)) {
Log.e("Equal", "Message");
stopService(new Intent(getApplicationContext(), getClass()));
}
long currentTimeMillis2 = System.currentTimeMillis();
action.sendReply(getApplicationContext(), autoReplyText, "okay kar bhai", bitmap );
stopService(new Intent(getApplicationContext(), getClass()));
String str7 = str3;
sendMessage = preference.getFromPref_String(str7);
long j2 = count + 1;
count = j2;
preference.addToPref_Long(str4, j2);
Const.staticsReplyList.add(new StatisticsReplyMsgListModel((int) count, preference.getFromPref_String(str7), str2, currentTimeMillis2));
preference.setReplyList("StaticsReplyList", Const.staticsReplyList);
if (preference.getFromPref_Boolean("Once") == z && !Const.userList.contains(str2)) {
Const.userList.add(str2);
preference.setUserList("UserList", Const.userList);
}
}
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
Log.e("Replied Message Error", e.getMessage());
}
}
private Intent getIntent() {
return null;
}
private boolean selfName(StatusBarNotification statusBarNotification) {
String title = NotificationUtils.getTitle(statusBarNotification);
return title == null || !title.equalsIgnoreCase(statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_SELF_DISPLAY_NAME));
}
private boolean isGroupMessageAndReplyAllowed(StatusBarNotification statusBarNotification) {
String titleRaw = NotificationUtils.getTitleRaw(statusBarNotification);
SpannableString valueOf = SpannableString.valueOf("" + statusBarNotification.getNotification().extras.get(NotificationCompat.EXTRA_TEXT));
boolean z = titleRaw != null && (": ".contains(titleRaw) || "# ".contains(titleRaw)) && valueOf != null && valueOf.toString().contains("📷");
if (!statusBarNotification.getNotification().extras.getBoolean(NotificationCompat.EXTRA_IS_GROUP_CONVERSATION)) {
return !z;
}
boolean fromPref_Boolean = preference.getFromPref_Boolean("GroupEnable");
Log.e("Group Message", "Return" + fromPref_Boolean);
return fromPref_Boolean;
}
private boolean EveryOne(String str) {
return str.equals("Everyone") || str.equals("");
}
private boolean ContactList(String str, String str2) {
return str.equals("ContactList") && Const.contactList.contains(str2);
}
private boolean ExceptContactList(String str, String str2) {
return str.equals("ExceptContList") && !Const.contactList.contains(str2);
}
#SuppressLint("Range")
private boolean ExceptPhoneList(String str, String str2) {
if (!str.equals("ExceptPhoneList")) {
return false;
}
Cursor query = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, (String[]) null, (String) null, (String[]) null, "display_name ASC");
while (query.moveToNext()) {
cntList.add(query.getString(query.getColumnIndex("display_name")));
}
query.close();
return !cntList.contains(str2);
}
private boolean isScheduleTime(boolean z) {
if (z) {
try {
Calendar instance = Calendar.getInstance();
String fromPref_String = preference.getFromPref_String("StartTime");
String fromPref_String2 = preference.getFromPref_String("EndTime");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
Date parse = simpleDateFormat.parse(simpleDateFormat.format(instance.getTime()));
Date parse2 = simpleDateFormat.parse(fromPref_String);
Date parse3 = simpleDateFormat.parse(fromPref_String2);
if (!parse.after(parse2) || !parse.before(parse3)) {
return false;
}
return true;
} catch (ParseException e) {
e.printStackTrace();
Log.e("CURRENTTIME", e.getMessage());
}
}
return true;
}
}
This is action activity that is sending reply in background.
Action.java
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
import com.templatemela.whatsbot.NotificationService;
import com.templatemela.whatsbot.R;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Iterator;
public class Action implements Parcelable {
public static final Creator CREATOR = new Creator() {
public Action createFromParcel(Parcel parcel) {
return new Action(parcel);
}
public Action[] newArray(int i) {
return new Action[i];
}
};
private final boolean isQuickReply;
private final PendingIntent p;
private final String packageName;
private final ArrayList<RemoteInputParcel> remoteInputs;
private final String text;
private final Uri imageUri = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/AwakiFolder/" + "aifile" + ".jpeg");
public int describeContents() {
return 0;
}
public Action(Parcel parcel) {
ArrayList<RemoteInputParcel> arrayList = new ArrayList<>();
remoteInputs = arrayList;
text = parcel.readString();
packageName = parcel.readString();
p = (PendingIntent) parcel.readParcelable(PendingIntent.class.getClassLoader());
isQuickReply = parcel.readByte() != 0;
parcel.readTypedList(arrayList, RemoteInputParcel.CREATOR);
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(text);
parcel.writeString(packageName);
parcel.writeParcelable(p, i);
parcel.writeByte(isQuickReply ? (byte) 1 : 0);
parcel.writeTypedList(remoteInputs);
}
public Action(String str, String str2, PendingIntent pendingIntent, RemoteInput remoteInput, boolean z) {
ArrayList<RemoteInputParcel> arrayList = new ArrayList<>();
remoteInputs = arrayList;
text = str;
packageName = str2;
p = pendingIntent;
isQuickReply = z;
arrayList.add(new RemoteInputParcel(remoteInput));
}
public Action(NotificationCompat.Action action, String str, boolean z) {
remoteInputs = new ArrayList<>();
text = action.title.toString();
packageName = str;
p = action.actionIntent;
if (action.getRemoteInputs() != null) {
for (RemoteInput remoteInputParcel : action.getRemoteInputs()) {
remoteInputs.add(new RemoteInputParcel(remoteInputParcel));
}
}
isQuickReply = z;
}
public void sendReply(Context context, String str, String tetStr, Bitmap bitmap) throws PendingIntent.CanceledException {
Log.e("AutoReply", "inside sendReply");
Intent intent = new Intent();
Bundle bundle = new Bundle();
Bitmap image4 = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
bundle.putParcelable( "image/png", image4);
String both = imageUri+ str + tetStr;
ArrayList arrayList = new ArrayList();
Iterator<RemoteInputParcel> it = remoteInputs.iterator();
while (it.hasNext()) {
RemoteInputParcel next = it.next();
Log.e("", "RemoteInput: " + next.getLabel());
intent.setAction(Intent.ACTION_SEND);
intent.setPackage("com.whatsapp");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
bundle.putCharSequence(next.getResultKey(), both);
RemoteInput.Builder builder = new RemoteInput.Builder(next.getResultKey());
builder.setLabel(next.getLabel());
builder.setChoices(next.getChoices());
builder.setAllowFreeFormInput(next.isAllowFreeFormInput());
builder.addExtras(next.getExtras());
arrayList.add(builder.build());
}
RemoteInput.addResultsToIntent((RemoteInput[]) arrayList.toArray(new RemoteInput[arrayList.size()]), intent, bundle);
p.send(context, 0, intent);
context.stopService(new Intent(context, NotificationService.class));
}
private Resources getResources() {
return null;
}
public ArrayList<RemoteInputParcel> getRemoteInputs() {
return remoteInputs;
}
public boolean isQuickReply() {
return isQuickReply;
}
public String getText() {
return text;
}
public PendingIntent getQuickReplyIntent() {
if (isQuickReply) {
return p;
}
return null;
}
public String getPackageName() {
return packageName;
}
}

I want to stop the my background service. When i open my application again

Here is my activity. I am started the service i.e SeviceToStartBackgroundService.class from HomeActivity . Here i want to check whether services are running or not if running then i want to stop the services.
package com.example.tracker.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.tracker.R;
import com.example.tracker.service.BLEService;
import com.example.tracker.service.BackgroundService;
import com.example.tracker.service.BluetoothLeService;
import com.example.tracker.service.SeviceToStartBackgroundService;
public class HomeScreenActivity extends AppCompatActivity {
String TAG="HomeScreenActivity";
public static Intent intent,intent2;
private Intent bluetoothIntent;
int i=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
}
#Override
protected void onResume() {
super.onResume();
stopServiceMethod();
startService(new Intent(getApplicationContext(),SeviceToStartBackgroundService.class));
}
public void stopServiceMethod(){
Log.e(TAG,"stopServiceMethod()");
stopService(new Intent(this, BackgroundService.class));
stopService(new Intent(this, SeviceToStartBackgroundService.class));
stopService(new Intent(this, BluetoothLeService.class));
stopService(new Intent(this, BLEService.class));
}
}
Here is my SeviceToStartBackgroundService.class . When i removed the app from recent apps then the onTaskRemoved(Intent rootIntent) method gets called. And one more service gets started i.e BackgroundService.class.
package com.example.tracker.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class SeviceToStartBackgroundService extends Service {
String TAG="SeviceToStartBService";
private BluetoothLeService mBluetoothLeService;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e(getClass().getName(), "App just got removed from Recents!");
startService(new Intent(getApplicationContext(),BackgroundService.class));
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Here is my BackgroundService.class . I want to stop this service when app comes in user interaction (front end) .
package com.example.tracker.service;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.example.tracker.R;
import com.example.tracker.utils.SampleGattAttributes;
import com.example.tracker.utils.SharedPreferencesUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static android.R.attr.delay;
import static com.shalaka.tracker.constant.SharedFreferencesConstant.KEY_SP_MOBILE_NUMBER;
/**
* Created by greenlantern on 12/9/17.
*/
public class BackgroundService extends Service{
Handler handlerScan=new Handler();
private int scanPeriod;
Context context;
public static String TAG="BackgroundService";
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler = new Handler();
public String[] advDataTypes = new String[256];
ArrayList<BluetoothDevice> bluetoothDeviceArrayList=new ArrayList<>();
ArrayList<BluetoothDevice> bluetoothDeviceArrayListTwo=new ArrayList<>();
private static final int REQUEST_ENABLE_BT = 1;
/*--------------Connect to BLE-----------------------------------------------*/
BluetoothGattService gattService4;
public static ArrayList<BluetoothGattCharacteristic> lastCharacteristic;
// AlertDialog.Builder alertDialog;
private float avgRssi = 0.0f;
// private Dialog dialog;
public static BluetoothLeService mBluetoothLeService;
private boolean mConnected = false;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList();
//service and char uuid
private static final int TRACKER_ON_OFF = 2;
private static final UUID TRACER_TRIPPLE_PRESS_SERVICE=UUID.fromString("edfec62e-9910-0bac-5241-d8bda6932a2f");
private static final UUID TRACKER_TRIPPLE_PRESS_CHAR=UUID.fromString("772ae377-b3d2-4f8e-4042-5481d1e0098c");
private static final UUID IMMEDIATE_ALERT_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
private static final UUID ALERT_LEVEL_UUID = UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb");
public static String connectionStatus;
/*-------------------------------------------------------------------------------*/
public static final String PREFS_NAME = "PreferencesFile";
public String[] mData = new String[400];
/*--------for > 21--------------*/
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
public BackgroundService() {
}
public BackgroundService(Context context) {
this.context = context;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int delay = 10000;
// getting systems default ringtone
handlerScan.postDelayed(new Runnable() {
#Override
public void run() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_RSSI_UPDATE);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_WRITE_FAILED);
Log.e(TAG,"OnResume()");
getApplicationContext().registerReceiver(mGattUpdateReceiver, intentFilter);
getApplicationContext().bindService(new Intent(getApplicationContext(), BluetoothLeService.class), mServiceConnection, 1);
Toast.makeText(getApplicationContext(),"CALL YOUR METHOD",Toast.LENGTH_LONG).show();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(context, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(context, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < 256; i += REQUEST_ENABLE_BT) {
advDataTypes[i] = "Unknown Data Type";
}
advDataTypes[REQUEST_ENABLE_BT] = "Flags";
advDataTypes[2] = "Incomplete List of 16-bit Service Class UUIDs";
advDataTypes[3] = "Complete List of 16-bit Service Class UUIDs";
advDataTypes[4] = "Incomplete List of 32-bit Service Class UUIDs";
advDataTypes[5] = "Complete List of 32-bit Service Class UUIDs";
advDataTypes[6] = "Incomplete List of 128-bit Service Class UUIDs";
advDataTypes[7] = "Complete List of 128-bit Service Class UUIDs";
advDataTypes[8] = "Shortened Local Name";
advDataTypes[9] = "Complete Local Name";
advDataTypes[10] = "Tx Power Level";
advDataTypes[13] = "Class of LocalDevice";
advDataTypes[14] = "Simple Pairing Hash";
advDataTypes[15] = "Simple Pairing Randomizer R";
advDataTypes[16] = "LocalDevice ID";
advDataTypes[17] = "Security Manager Out of Band Flags";
advDataTypes[18] = "Slave Connection Interval Range";
advDataTypes[20] = "List of 16-bit Solicitaion UUIDs";
advDataTypes[21] = "List of 128-bit Solicitaion UUIDs";
advDataTypes[22] = "Service Data";
advDataTypes[23] = "Public Target Address";
advDataTypes[24] = "Random Target Address";
advDataTypes[25] = "Appearance";
advDataTypes[26] = "Advertising Interval";
advDataTypes[61] = "3D Information Data";
advDataTypes[255] = "Manufacturer Specific Data";
scanPeriod = getApplicationContext().getSharedPreferences(PREFS_NAME, 0).getInt("scan_interval", 2000);
scanLeDevice(true);
}
// unRegisterReceicerAndService();
}, 1000);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
// -------------------Connect Ble--------------------------------------
}
private void scanLeDevice(final boolean enable) {
Log.e(TAG,"scanTrackerDevices");
bluetoothDeviceArrayList.clear();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
int arraySize=bluetoothDeviceArrayListTwo.size();
Log.e(TAG,"bluetoothDeviceArrayListTwo Size in scan :"+arraySize);
for (int i=0;i<bluetoothDeviceArrayListTwo.size();i++){
BluetoothDevice bluetoothDevice=bluetoothDeviceArrayListTwo.get(i);
Log.e(TAG,"Device Name in scan :"+bluetoothDevice.getName());
Log.e(TAG,"Device Address in scan :"+bluetoothDevice.getAddress());
if (i==0){
mBluetoothLeService.connect(bluetoothDevice.getAddress());
}
}
}
}, scanPeriod);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
String d = "";
String rd = "";
String h = "0123456789ABCDEF";
int ln = 0;
int i = 0;
while (i < scanRecord.length) {
int x = scanRecord[i] & 255;
rd = new StringBuilder(String.valueOf(rd)).append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) +REQUEST_ENABLE_BT)).toString();
if (i == ln) {
ln = (i + x) + REQUEST_ENABLE_BT;
if (x == 0) {
break;
}
d = new StringBuilder(String.valueOf(d)).append("\r\n Length: ").append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) +REQUEST_ENABLE_BT)).toString();
i += REQUEST_ENABLE_BT;
x = scanRecord[i] & 255;
d = new StringBuilder(String.valueOf(d)).append(", Type :").append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) + REQUEST_ENABLE_BT)).append(" = ").append(advDataTypes[x]).append(", Value: ").toString();
rd = new StringBuilder(String.valueOf(rd)).append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) + REQUEST_ENABLE_BT)).toString();
} else {
d = new StringBuilder(String.valueOf(d)).append(" ").append(h.substring(x / 16, (x / 16) + REQUEST_ENABLE_BT)).append(h.substring(x % 16, (x % 16) +REQUEST_ENABLE_BT)).toString();
}
i += REQUEST_ENABLE_BT;
}
Log.e(TAG,"UUID : "+device.getUuids());
String[] arrayDeviceName=String.valueOf(device.getName()).split(" ");
String deviceName0=arrayDeviceName[0];
// String deviceName1=arrayDeviceName[1];
if (deviceName0.equals("EUROtronic")){
Log.e(TAG,"Device Name :"+device.getName());
bluetoothDeviceArrayListTwo.add(device);
// Log.e(TAG,"Device Address :"+deviceName0);
}
}
};
/*-------------------Connect BLE---------------------------------------------*/
private Handler mHandler2=new Handler();;
public final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action))
{
numberOfRssi = 0;
avgRssi = 0.0f;
mConnected = true;
mHandler2.postDelayed(startRssi, 300);
Log.e(TAG,"ACTION_GATT_CONNECTED");
}
else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
Log.e(TAG,"ACTION_GATT_DISCONNECTED");
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
displayGattServicesForDimmer(mBluetoothLeService.getSupportedGattServices());
Log.e(TAG,"ACTION_GATT_SERVICES_DISCOVERED");
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
Log.e(TAG,"ACTION_DATA_AVAILABLE");
String unknownServiceString = context.getResources().getString(R.string.unknown_service);
displayDimmer2(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
} else if (BluetoothLeService.ACTION_GATT_RSSI_UPDATE.equals(action)) {
} else if (BluetoothLeService.ACTION_GATT_WRITE_FAILED.equals(action)) {
Log.e(TAG,"ACTION_GATT_WRITE_FAILED");
}
}
};
private BluetoothGattCharacteristic mNotifyCharacteristic;
public static ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
// getActivity().finish();
}
// mBluetoothLeService.connect(mDeviceAddress);
}
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private boolean notificationActive = true;
private int numberOfRssi = 0;
private Runnable startRssi = new Runnable() {
public void run() {
if (mConnected) {
mBluetoothLeService.readRemoteRssi();
mHandler2.postDelayed(startRssi, 200);
}
}
};
public BluetoothGatt getmGatt() {
return mGatt;
}
private void displayDimmer2(String data){
if (data!=null){
Log.e(TAG,"display Dimmer2"+data);
String sosString = data.substring(0, Math.min(data.length(), 3));
Log.e(TAG,"SOS String :"+sosString);
if (sosString.equals("SOS")){
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ SharedPreferencesUtils.getStringFromSharedPreferences(KEY_SP_MOBILE_NUMBER,getApplicationContext())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(callIntent);
}
}
}
/*-------------------------disaplay gatt service for dimmer----------------------*/
private void displayGattServicesForDimmer(List<BluetoothGattService> gattServices) {
if (gattServices != null) {
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList();
this.mGattCharacteristics = new ArrayList();
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap();
String uuid = gattService.getUuid().toString();
currentServiceData.put("NAME", SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put("UUID", uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList();
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas = new ArrayList();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put("NAME", "\t\t\t<<" + SampleGattAttributes.lookup(uuid, unknownCharaString) + ">>");
currentCharaData.put("UUID", "\t\t\tUUID: 0x" + uuid.substring(4, 8) + ", Properties: " + translateProperties(gattCharacteristic.getProperties()));
gattCharacteristicGroupData.add(currentCharaData);
Log.i(TAG,"CUrrent CHARACTERISTIC DATA"+currentCharaData);
Log.i(TAG,"UUID : "+uuid.substring(4, 8));
Log.i(TAG,"Proprties : "+gattCharacteristic.getProperties());
Log.i(TAG,"Translate Proprties : "+translateProperties(gattCharacteristic.getProperties()));
Log.i(TAG,"char list"+gattCharacteristicData.toString());
}
gattService4=gattService;
this.mGattCharacteristics.add(charas);
}
if (mGattCharacteristics.get(3)!=null) {
lastCharacteristic = new ArrayList<>(mGattCharacteristics.get(3));
enableNotifyOfCharcteristicForDimmer(lastCharacteristic);
}
}
}
private String translateProperties(int properties) {
String s = "";
if ((properties & 1) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Broadcast").toString();
}
if ((properties & 2) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Read").toString();
}
if ((properties & 4) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/WriteWithoutResponse").toString();
}
if ((properties & 8) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Write").toString();
}
if ((properties & 16) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Notify").toString();
}
if ((properties & 32) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/Indicate").toString();
}
if ((properties & 64) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/SignedWrite").toString();
}
if ((properties & 128) > 0) {
s = new StringBuilder(String.valueOf(s)).append("/ExtendedProperties").toString();
}
if (s.length() > 1) {
return s.substring(1);
}
return s;
}
// Enable Characteristic for dimmer
public void enableNotifyOfCharcteristicForDimmer(ArrayList<BluetoothGattCharacteristic> lastCharacteristic){
if(mGattCharacteristics!=null) {
checkCharacteristicPresent(lastCharacteristic.get(0));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(0), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+0+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 0 +" :" +lastCharacteristic.get(0).toString());
checkCharacteristicPresent(lastCharacteristic.get(1));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(1), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+1+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 1 +" :" +lastCharacteristic.get(1).toString());
checkCharacteristicPresent(lastCharacteristic.get(2));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(2), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+2+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 2 +" :" +lastCharacteristic.get(2).toString());
checkCharacteristicPresent(lastCharacteristic.get(3));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(3), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+3+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 3 +" :" +lastCharacteristic.get(3).toString());
checkCharacteristicPresent(lastCharacteristic.get(4));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(4), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+4+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 4 +" :" +lastCharacteristic.get(4).toString());
checkCharacteristicPresent(lastCharacteristic.get(5));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(5), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+5+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 5 +" :" +lastCharacteristic.get(5).toString());
checkCharacteristicPresent(lastCharacteristic.get(2));
mBluetoothLeService.setCharacteristicNotification(lastCharacteristic.get(2), true);
notificationActive = true;
Log.e(TAG,"Characteristic index : "+2+":\nM GATT CHARACTERISTIC AT "+"Service 4 : CHAR"+ 2 +" :" +lastCharacteristic.get(2).toString());
}
}
// Check the type of characteristic i.e READ/WRITE/NOTIFY
public void checkCharacteristicPresent(BluetoothGattCharacteristic characteristic) {
int charaProp = characteristic.getProperties();
Log.e(TAG, "checkCharacteristicPresent Prop : " + charaProp);
mBluetoothLeService.setCurrentCharacteristic(characteristic);
if ((charaProp & 2) > 0) {
Log.e(TAG, "CharProp & 2 : " + charaProp);
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp & 16) > 0) {
Log.e(TAG, "CharProp & 16 : " + charaProp);
mNotifyCharacteristic = characteristic;
} else {
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
}
if ((charaProp & 8) > 0 || (charaProp & 4) > 0) {
Log.e(TAG, "CharProp & 4 : " + charaProp);
} else {
Log.e(TAG, "Else : " + charaProp);
}
}
public void disconnectBLEDevice(){
// if (mNotifyCharacteristic != null) {
mBluetoothLeService.disconnect();
// }
}
#Override
public void onDestroy(){
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}

Android USB communication with Infineon XMC4500 Relax Kit

I am very beginner in stuff which I am doing.
My problem is that: I am programming an Android application in order to be able to send data and receive data from Infineon XMC4500 processor, I am working with my evaluation board Infineon XMC4500 Relax kit.
Could you please tell me, what actually do I do wrong in order to send data.
I would like to to add, that in Infineon DAVE IDE (IDE based on eclipse), I use DAVE app (software component) USBVC001 (USB_VirtualCOMDevice_USBVC001 is App for Communications Device Class demonstration application.)
Every suggestion is highly appreciated!
com.example.mateusz.buttonexample;
android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity {
final int RQSID_SET_LINE_CODING = 0x20;
final int RQSID_SET_CONTROL_LINE_STATE = 0x22;
private static final String ACTION_USB_PERMISSION = "com.example.USB_PERMISSION";
private static final String TAG = "MyActivity";
private final int vendorID = 1419;
private final int productID = 88;
PendingIntent mPermissionIntent;
private UsbDevice device;
private UsbManager connectedDevices;
UsbEndpoint in = null;
UsbEndpoint out = null;
UsbDeviceConnection usbDeviceConnection = null;
UsbInterface interfaceUSB = null;
private Button checkButton;
private TextView infoDevice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsbDevice device1 = null;
UsbManager manager = (UsbManager)getSystemService(USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
registerReceiver(mUsbDeviceReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
registerReceiver(mUsbDeviceReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
//UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
device1 = deviceIterator.next();
//your code
}
device = device1;
manager.requestPermission(device, mPermissionIntent);
infoDevice = (TextView) findViewById(R.id.infoDevice);
checkButton = (Button) findViewById(R.id.checkButton);
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showInformationAboutConnectedDevices();
}
});
//setUpCommunication();
}
private void releaseUsb()
{
if(usbDeviceConnection != null)
{
if(interfaceUSB != null)
{
usbDeviceConnection.releaseInterface(interfaceUSB);
interfaceUSB = null;
}
usbDeviceConnection.close();
usbDeviceConnection = null;
}
in = null;
out = null;
usbDeviceConnection = null;
device = null;
}
#Override
protected void onDestroy() {
releaseUsb();
unregisterReceiver(mUsbReceiver);
unregisterReceiver(mUsbDeviceReceiver);
super.onDestroy();
}
private void setUpCommunication()
{
UsbDevice usbDevice = null;
UsbDevice usbDeviceFound = null;
UsbManager manager = (UsbManager)getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext())
{
usbDevice = deviceIterator.next();
//do sprawdzenia
if((usbDevice.getVendorId() == vendorID) && (usbDevice.getProductId() == productID))
{
device = usbDevice;
TextView check = (TextView)findViewById(R.id.checkText1);
check.setText("Sprawdzony vendorID i productID");
}
if(device != null)
{
//TextView check = (TextView)findViewById(R.id.checkText1);
//check.setText("Device != null");
//wait(2000);
//for(int i = 0; i < 100000; i++){ ; }
for(int i = 0; i < device.getInterfaceCount(); i++)
{
UsbInterface usbInter = device.getInterface(i);
if(usbInter.getEndpointCount() >= 2){
for(int j = 0; j < usbInter.getEndpointCount(); j++)
{
if(usbInter.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
{
if (usbInter.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN)
{
in = usbInter.getEndpoint(j);
}
if(usbInter.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT)
{
//check.setText("USB_DIR_OUT");
//wait(2000);
interfaceUSB = usbInter;
out = usbInter.getEndpoint(j);
}
}
}
}
}
}
}
TextView check = (TextView)findViewById(R.id.checkText1);
TextView pozwolenie = (TextView)findViewById(R.id.pozwolenie);
if(manager.hasPermission(device)){ pozwolenie.setText("Wszedlem w pozwolenie"); }
byte[] myBuffer = new byte[] {(byte)'A'};
//Ustanowienie komunikacji
UsbDeviceConnection connection = manager.openDevice(device);
connection.claimInterface(interfaceUSB, true);
int length = connection.bulkTransfer(out,myBuffer, myBuffer.length,100);
if(length >= 0)
{
check.setText("Udalo sie " + Integer.toString(length));
}
byte[] tablica = new byte[1];
tablica[0] = (byte)'B';
int d = tablica[0];
connection.bulkTransfer(in, tablica, 1, 100);
int z = tablica[0];
check.setText("B code" + Integer.toString(d) + "bulkTransfer" + Integer.toString(z));
usbDeviceConnection = connection;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showInformationAboutConnectedDevices()
{
connectedDevices = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = connectedDevices.getDeviceList();
Iterator<UsbDevice> deviceListIterator = deviceList.values().iterator();
String informationAboutDevice = "";
while (deviceListIterator.hasNext())
{
UsbDevice connectedDeviceTemporary = deviceListIterator.next();
String tempString;
tempString = "\n";
tempString = "Device id: " + connectedDeviceTemporary.getDeviceId() + "\n"
+ "Device name:" + connectedDeviceTemporary.getDeviceName() + "\n" + "dupa";
informationAboutDevice += tempString;
}
infoDevice.setText(informationAboutDevice);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
TextView permissionText = (TextView) findViewById(R.id.textPermission);
if(ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbDevice connectedDeviceTemporary = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
// device = connectedDeviceTemporary;
if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if(connectedDeviceTemporary != null)
{
permissionText.setText("Wszedlem w mUsbReceiver");
setUpCommunication();
}
}
else
{
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
{
//UsbDevice device1 = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
TextView text = (TextView)findViewById(R.id.checkingText);
text.setText("Wszedlem mUsbDeviceReceiver ACTION_USB_DEVICE_DETACHED");
if(usbDeviceConnection != null)
{
if(interfaceUSB != null)
{
usbDeviceConnection.releaseInterface(interfaceUSB);
interfaceUSB = null;
}
usbDeviceConnection.close();
usbDeviceConnection = null;
}
in = null;
out = null;
usbDeviceConnection = null;
device = null;
}
else if(UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action))
{
device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
TextView text = (TextView)findViewById(R.id.checkingText);
text.setText("Wszedlem mUsbDeviceReceiver ACTION_USB_DEVICE_ATTACHED");
setUpCommunication();
}
}
};
}

Passing string from class to activity

I am trying to pass a string named 'str' from Cbreceiver.class which extends broadcast receiver to an activity cbdata.java.but i cannot pass the value,i am not getting any errors either.Thank you.Help me with this please
**CbReceiver.class:**
package com.example.Lovisis;
import java.io.UnsupportedEncodingException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class CbReceiver extends BroadcastReceiver
{
public static class SmsCbHeader {
public static final int PDU_HEADER_LENGTH = 6;
public final int geographicalScope;
public final int messageCode;
public final int updateNumber;
public final int messageIdentifier;
public final int dataCodingScheme;
public final int pageIndex;
public final int nrOfPages;
public SmsCbHeader(byte[] pdu) throws IllegalArgumentException {
if (pdu == null || pdu.length < PDU_HEADER_LENGTH) {
throw new IllegalArgumentException("Illegal PDU");
}
geographicalScope = (pdu[0] & 0xc0) >> 6;
messageCode = ((pdu[0] & 0x3f) << 4) | ((pdu[1] & 0xf0) >> 4);
updateNumber = pdu[1] & 0x0f;
messageIdentifier = (pdu[2] << 8) | pdu[3];
dataCodingScheme = pdu[4];
int pageIndex = (pdu[5] & 0xf0) >> 4;
int nrOfPages = pdu[5] & 0x0f;
if (pageIndex == 0 || nrOfPages == 0 || pageIndex > nrOfPages) {
pageIndex = 1;
nrOfPages = 1;
}
this.pageIndex = pageIndex;
this.nrOfPages = nrOfPages;
}
}
public static class SmsCbMessage {
public static final int GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE = 0;
public static final int GEOGRAPHICAL_SCOPE_PLMN_WIDE = 1;
public static final int GEOGRAPHICAL_SCOPE_LA_WIDE = 2;
public static final int GEOGRAPHICAL_SCOPE_CELL_WIDE = 3;
public static SmsCbMessage createFromPdu(byte[] pdu) {
try {
return new SmsCbMessage(pdu);
} catch (IllegalArgumentException e) {
return null;
}
}
private String[] LANGUAGE_CODES_GROUP_0 = {
"de", "en", "it", "fr", "es", "nl", "sv", "da", "pt", "fi", "no", "el", "tr", "hu",
"pl", null
};
private String[] LANGUAGE_CODES_GROUP_2 = {
"cs", "he", "ar", "ru", "is", null, null, null, null, null, null, null, null, null,
null, null
};
private static final char CARRIAGE_RETURN = 0x0d;
private SmsCbHeader mHeader;
private String mLanguage;
private String mBody;
private SmsCbMessage(byte[] pdu) throws IllegalArgumentException {
mHeader = new SmsCbHeader(pdu);
parseBody(pdu);
}
public int getGeographicalScope() {
return mHeader.geographicalScope;
}
public String getLanguageCode() {
return mLanguage;
}
public String getMessageBody() {
return mBody;
}
public int getMessageIdentifier() {
return mHeader.messageIdentifier;
}
public int getMessageCode() {
return mHeader.messageCode;
}
public int getUpdateNumber() {
return mHeader.updateNumber;
}
private void parseBody(byte[] pdu) {
int encoding;
boolean hasLanguageIndicator = false;
switch ((mHeader.dataCodingScheme & 0xf0) >> 4) {
case 0x00:
encoding = SmsMessage.ENCODING_7BIT;
mLanguage = LANGUAGE_CODES_GROUP_0[mHeader.dataCodingScheme & 0x0f];
break;
case 0x01:
hasLanguageIndicator = true;
if ((mHeader.dataCodingScheme & 0x0f) == 0x01) {
encoding = SmsMessage.ENCODING_16BIT;
} else {
encoding = SmsMessage.ENCODING_7BIT;
}
break;
case 0x02:
encoding = SmsMessage.ENCODING_7BIT;
mLanguage = LANGUAGE_CODES_GROUP_2[mHeader.dataCodingScheme & 0x0f];
break;
case 0x03:
encoding = SmsMessage.ENCODING_7BIT;
break;
case 0x04:
case 0x05:
switch ((mHeader.dataCodingScheme & 0x0c) >> 2) {
case 0x01:
encoding = SmsMessage.ENCODING_8BIT;
break;
case 0x02:
encoding = SmsMessage.ENCODING_16BIT;
break;
case 0x00:
default:
encoding = SmsMessage.ENCODING_7BIT;
break;
}
break;
case 0x06:
case 0x07:
case 0x09:
case 0x0e:
encoding = SmsMessage.ENCODING_UNKNOWN;
break;
case 0x0f:
if (((mHeader.dataCodingScheme & 0x04) >> 2) == 0x01) {
encoding = SmsMessage.ENCODING_8BIT;
} else {
encoding = SmsMessage.ENCODING_7BIT;
}
break;
default:
encoding = SmsMessage.ENCODING_7BIT;
break;
}
switch (encoding) {
case SmsMessage.ENCODING_7BIT:
if (hasLanguageIndicator && mBody != null && mBody.length() > 2) {
mLanguage = mBody.substring(0, 2);
mBody = mBody.substring(3);
}
break;
case SmsMessage.ENCODING_16BIT:
int offset = SmsCbHeader.PDU_HEADER_LENGTH;
if (hasLanguageIndicator && pdu.length >= SmsCbHeader.PDU_HEADER_LENGTH + 2) {
offset += 2;
}
try {
mBody = new String(pdu, offset, (pdu.length & 0xfffe) - offset, "utf-16");
} catch (UnsupportedEncodingException e) {
}
break;
default:
break;
}
if (mBody != null) {
for (int i = mBody.length() - 1; i >= 0; i--) {
if (mBody.charAt(i) != CARRIAGE_RETURN) {
mBody = mBody.substring(0, i + 1);
break;
}
}
} else {
mBody = "";
}
}
}
public String str;
public String str1="hello";
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
//str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB :" +msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
//Toast.makeText(context, "" +str, Toast.LENGTH_LONG).show();
}
Toast.makeText(context,str, Toast.LENGTH_LONG).show();
Intent in=new Intent(CbReceiver.this,Cbdata.class);
in.putExtra("cb", str);
abortBroadcast();
}
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
}
**Cbdata.java:**
Remove the OnRecieve() method Use
#Override
protected void onNewIntent(Intent intent) {
Log.d("YourActivity", "onNewIntent is called!");
memberFieldString = intent.getStringExtra("KEY");
super.onNewIntent(intent);
} // End of onNewIntent(Intent intent)
tell me weather its working or not
u can try by creating an object of class Cbreceiver in Cbdata...
eg.
Cbreceiver rec = new Cbreceiver(this);
then directly use the string as rec.str

change imageview using int

I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];

Categories

Resources