How to get cell tower strength before outgoing call, if there is no signal or not enough strength it should prompt user with text No Signal.
See this signalStrength..this should do the trick
hi please use the following code hope it will solve yours problem
HomeActivity .java
// Android Packages
import android.app.Activity;
import android.os.Bundle;
import android.os.Build;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Button;
import android.telephony.SignalStrength;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.telephony.CellLocation;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.widget.Toast;
import android.util.Log;
public final class HomeActivity extends Activity
{
public static final String TAG = HomeActivity.class.getSimpleName();
public static final String EMAIL = "tbarrasso#sevenplusandroid.org";
private CellLocation mCellLocation;
private SignalStrength mSignalStrength;
private boolean mDone = false;
private TextView mText = null;
private String mTextStr;
private Button mSubmit, mCancel;
private TelephonyManager mManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mText = (TextView) findViewById(R.id.text);
mSubmit = (Button) findViewById(R.id.submit);
mCancel = (Button) findViewById(R.id.cancel);
// Prevent button press.
mSubmit.setEnabled(false);
// Handle click events.
mSubmit.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View mView)
{
sendResults();
finish();
}
});
mCancel.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View mView)
{
finish();
}
});
// Register the listener with the telephony manager
mManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS |
PhoneStateListener.LISTEN_CELL_LOCATION);
}
// Listener for signal strength.
final PhoneStateListener mListener = new PhoneStateListener()
{
#Override
public void onCellLocationChanged(CellLocation mLocation)
{
if (mDone) return;
Log.d(TAG, "Cell location obtained.");
mCellLocation = mLocation;
update();
}
#Override
public void onSignalStrengthsChanged(SignalStrength sStrength)
{
if (mDone) return;
Log.d(TAG, "Signal strength obtained.");
mSignalStrength = sStrength;
update();
}
};
// AsyncTask to avoid an ANR.
private class ReflectionTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... mVoid)
{
mTextStr =
("DEVICE INFO\n\n" + "SDK: `" + Build.VERSION.SDK_INT + "`\nCODENAME: `" +
Build.VERSION.CODENAME + "`\nRELEASE: `" + Build.VERSION.RELEASE +
"`\nDevice: `" + Build.DEVICE + "`\nHARDWARE: `" + Build.HARDWARE +
"`\nMANUFACTURER: `" + Build.MANUFACTURER + "`\nMODEL: `" + Build.MODEL +
"`\nPRODUCT: `" + Build.PRODUCT + ((getRadio() == null) ? "" : ("`\nRADIO: `" + getRadio())) +
"`\nBRAND: `" + Build.BRAND + ((Build.VERSION.SDK_INT >= 8) ? ("`\nBOOTLOADER: `" + Build.BOOTLOADER) : "") +
"`\nBOARD: `" + Build.BOARD + "`\nID: `"+ Build.ID + "`\n\n" +
ReflectionUtils.dumpClass(SignalStrength.class, mSignalStrength) + "\n" +
ReflectionUtils.dumpClass(mCellLocation.getClass(), mCellLocation) + "\n" + getWimaxDump() +
ReflectionUtils.dumpClass(TelephonyManager.class, mManager) +
ReflectionUtils.dumpStaticFields(Context.class, getApplicationContext()));
return null;
}
protected void onProgressUpdate(Void... progress)
{
// Do nothing...
}
protected void onPostExecute(Void result)
{
complete();
}
}
private final void complete()
{
mDone = true;
try
{
mText.setText(mTextStr);
// Stop listening.
mManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
Toast.makeText(getApplicationContext(), R.string.done, Toast.LENGTH_SHORT).show();
mSubmit.setEnabled(true);
}
catch (Exception e)
{
Log.e(TAG, "ERROR!!!", e);
}
}
private final void update()
{
if (mSignalStrength == null || mCellLocation == null) return;
final ReflectionTask mTask = new ReflectionTask();
mTask.execute();
}
/**
* #return The Radio of the {#link Build} if available.
*/
public static final String getRadio()
{
if (Build.VERSION.SDK_INT >= 8 && Build.VERSION.SDK_INT < 14)
return Build.RADIO;
else if (Build.VERSION.SDK_INT >= 14)
return Build.getRadioVersion();
else
return null;
}
private static final String[] mServices =
{
"WiMax", "wimax", "wimax", "WIMAX", "WiMAX"
};
/**
* #return A String containing a dump of any/ all WiMax
* classes/ services loaded via {#link Context}.
*/
public final String getWimaxDump()
{
String mStr = "";
for (final String mService : mServices)
{
final Object mServiceObj = getApplicationContext()
.getSystemService(mService);
if (mServiceObj != null)
{
mStr += "getSystemService(" + mService + ")\n\n";
mStr += ReflectionUtils.dumpClass(mServiceObj.getClass(), mServiceObj);
}
}
return mStr;
}
/**
* Start an {#link Intent} chooser for the user to submit the results.
*/
public final void sendResults()
{
final Intent mIntent = new Intent(Intent.ACTION_SEND);
mIntent.setType("plain/text");
mIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { EMAIL });
mIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.results));
mIntent.putExtra(Intent.EXTRA_TEXT, mTextStr);
HomeActivity.this.startActivity(Intent.createChooser(mIntent, "Send results."));
}
}
ReflectionUtils.java
import java.lang.reflect.*;
import android.util.Log;
public final class ReflectionUtils
{
public static final String TAG = ReflectionUtils.class.getSimpleName();
/**
* Dumps a {#link Class}'s {#link Method}s and {#link Field}s
* as a String.
*/
public static final String dumpClass(Class<?> mClass, Object mInstance)
{
if (mClass == null || mInstance == null) return null;
String mStr = mClass.getSimpleName() + "\n\n";
mStr += "FIELDS\n\n";
final Field[] mFields = mClass.getDeclaredFields();
for (final Field mField : mFields)
{
mField.setAccessible(true);
mStr += mField.getName() + " (" + mField.getType() + ") = ";
try
{
mStr += mField.get(mInstance).toString();
}
catch (Exception e)
{
mStr += "null";
Log.e(TAG, "Could not get Field `" + mField.getName() + "`.", e);
}
mStr += "\n";
}
mStr += "METHODS\\nn";
// Dump all methods.
final Method[] mMethods = mClass.getMethods();
for (final Method mMethod : mMethods)
{
mMethod.setAccessible(true);
mStr += mMethod.getReturnType() + " " + mMethod.getName() + "() = ";
try
{
final Object mRet = mMethod.invoke(mInstance);
mStr += (mRet == null) ? "null" : mMethod.invoke(mInstance).toString();
}
catch (Exception e)
{
mStr += "null";
Log.e(TAG, "Could not get Method `" + mMethod.getName() + "`.", e);
}
mStr += "\n";
}
return mStr;
}
/**
* #return A string containing the values of all static {#link Field}s.
*/
public static final String dumpStaticFields(Class<?> mClass, Object mInstance)
{
if (mClass == null || mInstance == null) return null;
String mStr = mClass.getSimpleName() + "\n\n";
mStr += "STATIC FIELDS\n\n";
final Field[] mFields = mClass.getDeclaredFields();
for (final Field mField : mFields)
{
if (ReflectionUtils.isStatic(mField))
{
mField.setAccessible(true);
mStr += mField.getName() + " (" + mField.getType() + ") = ";
try
{
mStr += mField.get(mInstance).toString();
}
catch (Exception e)
{
mStr += "null";
Log.e(TAG, "Could not get Field `" + mField.getName() + "`.", e);
}
mStr += "\n";
}
}
return mStr;
}
/**
* #return True if the {#link Field} is static.
*/
public final static boolean isStatic(Field field)
{
final int modifiers = field.getModifiers();
return (Modifier.isStatic(modifiers));
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#android:color/black"
android:padding="8dp"
android:id="#+id/root">
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="56dp"
android:fillViewport="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/text"
android:textColor="#android:color/white" />
</LinearLayout>
</ScrollView>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:stretchColumns="0,1">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/cancel"
android:textColor="#android:color/white"/>
<Button
android:id="#+id/submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/submit"
android:textColor="#android:color/white"/>
</TableRow>
</TableLayout>
</RelativeLayout>
do not forget to use following features and permissions
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<uses-feature android:name="android.hardware.location" android:required="false" />
<uses-feature android:name="android.hardware.location.network" android:required="false" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
<uses-feature android:name="android.hardware.telephony" android:required="false" />
<uses-permission android:name="android.permission.ACCESS_WIMAX_STATE" android:required="false" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" android:required="false" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:required="false" />
Related
I am using opentok videocall library in android. I want the same feature as in WhatsApp. in this app, there are 3 subscribers and 1 publisher view on my screen. when we touch any subscriber view it should switch with a full-screen view. I am attaching a screen for better understanding.
in this screen when we touch subscriber 2 view, it should exchange its view with subscriber 1 and when we press any other subscriber view it should exchange with the main view which is in large size.
screen two
screen three
My code is here, in this I am able to switch subscriber with each other but not able to manage them in main screen.
menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tokbox.android.tutorials.simple_multiparty">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" android:supportsRtl="true" android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My activity_main.xml file is here
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RelativeLayout
android:id="#+id/video_call_main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:keepScreenOn="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:id="#+id/subscriberview0">
</RelativeLayout>
<RelativeLayout
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_toLeftOf="#+id/subscriberview1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#154612"
android:id="#+id/subscriberview2">
</RelativeLayout>
<RelativeLayout
android:layout_width="120dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="5dp"
android:background="#af1234"
android:layout_toLeftOf="#+id/publisherview"
android:id="#+id/subscriberview1">
</RelativeLayout>
<RelativeLayout
android:background="#86dec6"
android:id="#+id/publisherview"
android:layout_height="150dp"
android:layout_width="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="5dp">
</RelativeLayout>
</RelativeLayout>
My MainActivity.java file is here
package com.tokbox.android.tutorials.simple_multiparty;
import android.Manifest;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.opentok.android.BaseVideoRenderer;
import com.opentok.android.OpentokError;
import com.opentok.android.Publisher;
import com.opentok.android.PublisherKit;
import com.opentok.android.Session;
import com.opentok.android.Stream;
import com.opentok.android.Subscriber;
import com.opentok.android.TextureViewRenderer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
public class MainActivity extends AppCompatActivity
implements EasyPermissions.PermissionCallbacks,
Publisher.PublisherListener,
Session.SessionListener {
public static final String API_KEY = "46139802";//"46089252";
public static final String TOKEN = "T1==cGFydG5lcl9pZD00NjEzOTgwMiZzaWc9NjZmOGRiY2Q3MDdiNWNiY2M0Yzc4Nzg4NWZlYTZlNzdiYzQyZDRkZDpzZXNzaW9uX2lkPTFfTVg0ME5qRXpPVGd3TW41LU1UVXlPVE13TXpJME9UazNNbjVDWTFaUVpteG1NMnh2UTFocWVWUlBVazloVGxKM1NYUi1mZyZjcmVhdGVfdGltZT0xNTI5MzAzMzQxJm5vbmNlPTAuNDEyNTM2NjMyNDUxODU2MjMmcm9sZT1wdWJsaXNoZXImZXhwaXJlX3RpbWU9MTUyOTM4OTcwMSZpbml0aWFsX2xheW91dF9jbGFzc19saXN0PQ==";
public static final String SESSION_ID = "1_MX40NjEzOTgwMn5-MTUyOTMwMzI0OTk3Mn5CY1ZQZmxmM2xvQ1hqeVRPUk9hTlJ3SXR-fg";
private static final String TAG = "simple-multiparty " + MainActivity.class.getSimpleName();
private final int MAX_NUM_SUBSCRIBERS = 4;
private static final int RC_SETTINGS_SCREEN_PERM = 123;
private static final int RC_VIDEO_APP_PERM = 124;
private Session mSession;
private Publisher mPublisher;
private ArrayList<Subscriber> mSubscribers = new ArrayList<Subscriber>();
private HashMap<Stream, Subscriber> mSubscriberStreams = new HashMap<Stream, Subscriber>();
private RelativeLayout mPublisherViewContainer;
private RelativeLayout subscriberview0, subscriberview1, subscriberview2;
int widthView;
RelativeLayout.LayoutParams view0Params, view1Params, view2Params, viewParams;
View subscriberViewBig;
View subscriberViewSmall;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPublisherViewContainer = (RelativeLayout) findViewById(R.id.publisherview);
subscriberview0 = (RelativeLayout) findViewById(R.id.subscriberview0);
subscriberview1 = (RelativeLayout) findViewById(R.id.subscriberview1);
subscriberview2 = (RelativeLayout) findViewById(R.id.subscriberview2);
int totalMeasuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
totalMeasuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
totalMeasuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
int paddingInPx = (int) convertDpToPixel(5, MainActivity.this);
totalMeasuredwidth = totalMeasuredwidth - (4*paddingInPx);
widthView = totalMeasuredwidth / 3 ;
Log.d(TAG, "widthView : in pixel "+ widthView);
view0Params = new RelativeLayout.LayoutParams(widthView, (int) convertDpToPixel(150, MainActivity.this));
view1Params = new RelativeLayout.LayoutParams(widthView, (int) convertDpToPixel(150, MainActivity.this));
view2Params = new RelativeLayout.LayoutParams(widthView, (int) convertDpToPixel(150, MainActivity.this));
viewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
requestPermissions();
subscriberview0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPublisherViewContainer.bringToFront();
subscriberview0.setLayoutParams(viewParams);
view1Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view1Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view1Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view1Params.addRule(RelativeLayout.LEFT_OF, R.id.publisherview);
subscriberview1.setLayoutParams(view1Params);
subscriberview1.bringToFront();
view2Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view2Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view2Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view2Params.addRule(RelativeLayout.LEFT_OF, R.id.subscriberview1);
subscriberview2.setLayoutParams(view2Params);
subscriberview2.bringToFront();
}
});
subscriberview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPublisherViewContainer.bringToFront();
view0Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view0Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view0Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view0Params.addRule(RelativeLayout.LEFT_OF, R.id.publisherview);
subscriberview0.setLayoutParams(view0Params);
subscriberview0.bringToFront();
viewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
subscriberview1.setLayoutParams(viewParams);
view2Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view2Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view2Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view2Params.addRule(RelativeLayout.LEFT_OF, R.id.subscriberview0);
subscriberview2.setLayoutParams(view2Params);
subscriberview2.bringToFront();
}
});
subscriberview2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPublisherViewContainer.bringToFront();
view0Params.rightMargin = (int) Utility.convertDpToPixel(3, MainActivity.this);
view0Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view0Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view0Params.addRule(RelativeLayout.LEFT_OF, R.id.publisherview);
subscriberview0.setLayoutParams(view0Params);
subscriberview0.bringToFront();
view1Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view1Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view1Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view1Params.addRule(RelativeLayout.LEFT_OF, R.id.subscriberview0);
subscriberview1.setLayoutParams(view1Params);
subscriberview1.bringToFront();
subscriberview2.setLayoutParams(viewParams);
}
});
}
private int getResIdForSubscriberIndex(int index) {
TypedArray arr = getResources().obtainTypedArray(R.array.subscriber_view_ids);
int subId = arr.getResourceId(index, 0);
arr.recycle();
return subId;
}
public static float convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return px;
}
#Override
protected void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
#Override
protected void onRestart() {
Log.d(TAG, "onRestart");
super.onRestart();
}
#Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
if (mSession == null) {
return;
}
mSession.onResume();
}
#Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
if (mSession == null) {
return;
}
mSession.onPause();
if (isFinishing()) {
disconnectSession();
}
}
#Override
protected void onStop() {
Log.d(TAG, "onPause");
super.onStop();
}
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
disconnectSession();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
}
#Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this)
.setTitle(getString(R.string.title_settings_dialog))
.setRationale(getString(R.string.rationale_ask_again))
.setPositiveButton(getString(R.string.setting))
.setNegativeButton(getString(R.string.cancel))
.setRequestCode(RC_SETTINGS_SCREEN_PERM)
.build()
.show();
}
}
#AfterPermissionGranted(RC_VIDEO_APP_PERM)
private void requestPermissions() {
String[] perms = {
Manifest.permission.INTERNET,
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
};
if (EasyPermissions.hasPermissions(this, perms)) {
//mSession = new Session.Builder(MainActivity.this, OpenTokConfig.API_KEY, OpenTokConfig.SESSION_ID).build();
mSession = new Session.Builder(MainActivity.this, API_KEY, SESSION_ID)
.sessionOptions(new Session.SessionOptions() {
#Override
public boolean useTextureViews() {
return true;
}
}).build();
mSession.setSessionListener(this);
mSession.connect(TOKEN);
} else {
EasyPermissions.requestPermissions(this, getString(R.string.rationale_video_app), RC_VIDEO_APP_PERM, perms);
}
}
#Override
public void onConnected(Session session) {
Log.d(TAG, "onConnected: Connected to session " + session.getSessionId());
mPublisher = new Publisher.Builder(MainActivity.this).name("publisher").build();
mPublisher.setPublisherListener(this);
mPublisher.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL);
mPublisherViewContainer.addView(mPublisher.getView());
mSession.publish(mPublisher);
}
#Override
public void onDisconnected(Session session) {
Log.d(TAG, "onDisconnected: disconnected from session " + session.getSessionId());
mSession = null;
}
#Override
public void onError(Session session, OpentokError opentokError) {
Log.d(TAG, "onError: Error (" + opentokError.getMessage() + ") in session " + session.getSessionId());
Toast.makeText(this, "Session error. See the logcat please.", Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onStreamReceived(Session session, Stream stream) {
Log.d(TAG, "onStreamReceived: New stream " + stream.getStreamId() + " in session " + session.getSessionId());
if (mSubscribers.size() + 1 > MAX_NUM_SUBSCRIBERS) {
Toast.makeText(this, "New subscriber ignored. MAX_NUM_SUBSCRIBERS limit reached.", Toast.LENGTH_LONG).show();
return;
}
final Subscriber subscriber = new Subscriber.Builder(MainActivity.this, stream).build();
mSession.subscribe(subscriber);
mSubscribers.add(subscriber);
mSubscriberStreams.put(stream, subscriber);
subscriber.setSubscribeToAudio(false);
int position = mSubscribers.size() - 1;
int id = getResources().getIdentifier("subscriberview" + (new Integer(position)).toString(), "id", MainActivity.this.getPackageName());
RelativeLayout subscriberViewContainer = (RelativeLayout) findViewById(id);
//subscriber.setStyle(BaseVideoRenderer.STYLE_VIDEO_FILL, BaseVideoRenderer.STYLE_VIDEO_FILL);
subscriber.setStyle(TextureViewRenderer.STYLE_VIDEO_SCALE, TextureViewRenderer.STYLE_VIDEO_FIT);
subscriberViewContainer.addView(subscriber.getView());
if (mSubscribers.size() == 1) {
Log.d(TAG, "mSubscribers: view0 visible size : " + mSubscribers.size());
subscriberview1.setVisibility(View.GONE);
subscriberview2.setVisibility(View.GONE);
}
if (mSubscribers.size() == 2) {
Log.d(TAG, "mSubscribers: view1 visible size : " + mSubscribers.size());
subscriberview1.setVisibility(View.VISIBLE);
subscriberview2.setVisibility(View.GONE);
view1Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view1Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view1Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view1Params.addRule(RelativeLayout.LEFT_OF, R.id.publisherview);
subscriberview1.setLayoutParams(view1Params);
//subscriberview1.setZ(1);
subscriberview1.bringToFront();
}
if (mSubscribers.size() == 3) {
Log.d(TAG, "mSubscribers: view2 visible size : " + mSubscribers.size());
subscriberview1.setVisibility(View.VISIBLE);
subscriberview2.setVisibility(View.VISIBLE);
view2Params.rightMargin = (int) Utility.convertDpToPixel(5, MainActivity.this);
view2Params.bottomMargin = (int) Utility.convertDpToPixel(10, MainActivity.this);
view2Params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
view2Params.addRule(RelativeLayout.LEFT_OF, R.id.subscriberview1);
subscriberview2.setLayoutParams(view2Params);
//subscriberview1.setZ(1);
subscriberview2.bringToFront();
}
}
#Override
public void onStreamDropped(Session session, Stream stream) {
Log.d(TAG, "onStreamDropped: Stream " + stream.getStreamId() + " dropped from session " + session.getSessionId());
Subscriber subscriber = mSubscriberStreams.get(stream);
if (subscriber == null) {
return;
}
int position = mSubscribers.indexOf(subscriber);
int id = getResources().getIdentifier("subscriberview" + (new Integer(position)).toString(), "id", MainActivity.this.getPackageName());
mSubscribers.remove(subscriber);
mSubscriberStreams.remove(stream);
RelativeLayout subscriberViewContainer = (RelativeLayout) findViewById(id);
subscriberViewContainer.removeView(subscriber.getView());
}
#Override
public void onStreamCreated(PublisherKit publisherKit, Stream stream) {
Log.d(TAG, "onStreamCreated: Own stream " + stream.getStreamId() + " created");
}
#Override
public void onStreamDestroyed(PublisherKit publisherKit, Stream stream) {
Log.d(TAG, "onStreamDestroyed: Own stream " + stream.getStreamId() + " destroyed");
}
#Override
public void onError(PublisherKit publisherKit, OpentokError opentokError) {
Log.d(TAG, "onError: Error (" + opentokError.getMessage() + ") in publisher");
Toast.makeText(this, "Session error. See the logcat please.", Toast.LENGTH_LONG).show();
finish();
}
private void disconnectSession() {
if (mSession == null) {
return;
}
if (mSubscribers.size() > 0) {
for (Subscriber subscriber : mSubscribers) {
if (subscriber != null) {
mSession.unsubscribe(subscriber);
subscriber.destroy();
}
}
}
if (mPublisher != null) {
mPublisherViewContainer.removeView(mPublisher.getView());
mSession.unpublish(mPublisher);
mPublisher.destroy();
mPublisher = null;
}
mSession.disconnect();
}
}
My Utility file is here
package com.tokbox.android.tutorials.simple_multiparty;
import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
public class Utility {
public static float convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi /
DisplayMetrics.DENSITY_DEFAULT);
return px;
}
}
Tokbox QA stuff here.
Opentok will not do that for you, because that's your functionality. You need to capture screen presses, and resize the canvas for publishers/subscribers by yourself. We don't handle how you want to show subscribers in your screen.
I am trying to build an Android Application and I have an Arduino Leonardo board that sends output via the keyboard write command. So far, I am able to receive the Arduino output on my Android device as keyboard input. I have an EditText text that just receives all the Arduino output and when the output sequence is over, I can then parse the EditText value easily.
However, the issue I'm having right now is sending data from Android to Arduino. I've done my research and the recommended/common ways of communication between Android and Arduino is via Bluetooth where the Android will send data to an Arduino with a Bluetooth shield. This is a viable solution, however, we have limited resources. I've also seen stackoverflow questions that involved an OTG Cable but those were communicating to Arduino Uno. It seems that those solutions did not work on Leonardo. I've also seen blogs wherein people in the comments section would ask on how to implement a cable based communication system between Android and Arduino Leonardo.
How can I resolve this problem? It seems like the communication interface/protocol across Arduino boards are different.
Also, as a side note, is it possible to use a different command to send data from Arduino Leonardo to Android aside from the keyboard write command?
This example show how to send String from Android to Arduino Uni via USB OTG cable, before sending you must be know about the
vendor-id="9025"
product-id="0067"
of Arduino have a look for this example
import java.util.HashMap;
import java.util.Iterator;
import android.support.v7.app.ActionBarActivity;
import 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.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
TextView textInfo;
TextView textSearchedEndpoint;
TextView textDeviceName;
TextView textStatus;
private static final int targetVendorID = 9025; //Arduino Uno
private static final int targetProductID = 67; //Arduino Uno, not 0067
UsbDevice deviceFound = null;
UsbInterface usbInterfaceFound = null;
UsbEndpoint endpointIn = null;
UsbEndpoint endpointOut = null;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent;
UsbInterface usbInterface;
UsbDeviceConnection usbDeviceConnection;
EditText textOut;
Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textStatus = (TextView) findViewById(R.id.textstatus);
textDeviceName = (TextView) findViewById(R.id.textdevicename);
textInfo = (TextView) findViewById(R.id.info);
textSearchedEndpoint = (TextView) findViewById(R.id.searchedendpoint);
// register the broadcast receiver
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));
connectUsb();
textOut = (EditText)findViewById(R.id.textout);
buttonSend = (Button)findViewById(R.id.send);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
OnClickListener buttonSendOnClickListener =
new OnClickListener(){
#Override
public void onClick(View v) {
if(deviceFound != null){
String tOut = textOut.getText().toString();
byte[] bytesOut = tOut.getBytes(); //convert String to byte[]
int usbResult = usbDeviceConnection.bulkTransfer(
endpointOut, bytesOut, bytesOut.length, 0);
}else{
Toast.makeText(MainActivity.this,
"deviceFound == null",
Toast.LENGTH_LONG).show();
}
}};
#Override
protected void onDestroy() {
releaseUsb();
unregisterReceiver(mUsbReceiver);
unregisterReceiver(mUsbDeviceReceiver);
super.onDestroy();
}
private void connectUsb() {
Toast.makeText(MainActivity.this, "connectUsb()", Toast.LENGTH_LONG)
.show();
textStatus.setText("connectUsb()");
searchEndPoint();
if (usbInterfaceFound != null) {
setupUsbComm();
}
}
private void releaseUsb() {
Toast.makeText(MainActivity.this, "releaseUsb()", Toast.LENGTH_LONG)
.show();
textStatus.setText("releaseUsb()");
if (usbDeviceConnection != null) {
if (usbInterface != null) {
usbDeviceConnection.releaseInterface(usbInterface);
usbInterface = null;
}
usbDeviceConnection.close();
usbDeviceConnection = null;
}
deviceFound = null;
usbInterfaceFound = null;
endpointIn = null;
endpointOut = null;
}
private void searchEndPoint() {
textInfo.setText("");
textSearchedEndpoint.setText("");
usbInterfaceFound = null;
endpointOut = null;
endpointIn = null;
// Search device for targetVendorID and targetProductID
if (deviceFound == null) {
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == targetVendorID) {
if (device.getProductId() == targetProductID) {
deviceFound = device;
}
}
}
}
if (deviceFound == null) {
Toast.makeText(MainActivity.this, "device not found",
Toast.LENGTH_LONG).show();
textStatus.setText("device not found");
} else {
String s = deviceFound.toString() + "\n" + "DeviceID: "
+ deviceFound.getDeviceId() + "\n" + "DeviceName: "
+ deviceFound.getDeviceName() + "\n" + "DeviceClass: "
+ deviceFound.getDeviceClass() + "\n" + "DeviceSubClass: "
+ deviceFound.getDeviceSubclass() + "\n" + "VendorID: "
+ deviceFound.getVendorId() + "\n" + "ProductID: "
+ deviceFound.getProductId() + "\n" + "InterfaceCount: "
+ deviceFound.getInterfaceCount();
textInfo.setText(s);
// Search for UsbInterface with Endpoint of USB_ENDPOINT_XFER_BULK,
// and direction USB_DIR_OUT and USB_DIR_IN
for (int i = 0; i < deviceFound.getInterfaceCount(); i++) {
UsbInterface usbif = deviceFound.getInterface(i);
UsbEndpoint tOut = null;
UsbEndpoint tIn = null;
int tEndpointCnt = usbif.getEndpointCount();
if (tEndpointCnt >= 2) {
for (int j = 0; j < tEndpointCnt; j++) {
if (usbif.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT) {
tOut = usbif.getEndpoint(j);
} else if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN) {
tIn = usbif.getEndpoint(j);
}
}
}
if (tOut != null && tIn != null) {
// This interface have both USB_DIR_OUT
// and USB_DIR_IN of USB_ENDPOINT_XFER_BULK
usbInterfaceFound = usbif;
endpointOut = tOut;
endpointIn = tIn;
}
}
}
if (usbInterfaceFound == null) {
textSearchedEndpoint.setText("No suitable interface found!");
} else {
textSearchedEndpoint.setText("UsbInterface found: "
+ usbInterfaceFound.toString() + "\n\n"
+ "Endpoint OUT: " + endpointOut.toString() + "\n\n"
+ "Endpoint IN: " + endpointIn.toString());
}
}
}
private boolean setupUsbComm() {
// for more info, search SET_LINE_CODING and
// SET_CONTROL_LINE_STATE in the document:
// "Universal Serial Bus Class Definitions for Communication Devices"
final int RQSID_SET_LINE_CODING = 0x20;
final int RQSID_SET_CONTROL_LINE_STATE = 0x22;
boolean success = false;
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
Boolean permitToRead = manager.hasPermission(deviceFound);
if (permitToRead) {
usbDeviceConnection = manager.openDevice(deviceFound);
if (usbDeviceConnection != null) {
usbDeviceConnection.claimInterface(usbInterfaceFound, true);
int usbResult;
usbResult = usbDeviceConnection.controlTransfer(0x21, // requestType
RQSID_SET_CONTROL_LINE_STATE, // SET_CONTROL_LINE_STATE
0, // value
0, // index
null, // buffer
0, // length
0); // timeout
Toast.makeText(
MainActivity.this,
"controlTransfer(SET_CONTROL_LINE_STATE): " + usbResult,
Toast.LENGTH_LONG).show();
// baud rate = 9600
// 8 data bit
// 1 stop bit
byte[] encodingSetting = new byte[] { (byte) 0x80, 0x25, 0x00,
0x00, 0x00, 0x00, 0x08 };
usbResult = usbDeviceConnection.controlTransfer(0x21, // requestType
RQSID_SET_LINE_CODING, // SET_LINE_CODING
0, // value
0, // index
encodingSetting, // buffer
7, // length
0); // timeout
Toast.makeText(MainActivity.this,
"controlTransfer(RQSID_SET_LINE_CODING): " + usbResult,
Toast.LENGTH_LONG).show();
/*
byte[] bytesHello = new byte[] { (byte) 'H', 'e', 'l', 'l',
'o', ' ', 'f', 'r', 'o', 'm', ' ', 'A', 'n', 'd', 'r',
'o', 'i', 'd' };
usbResult = usbDeviceConnection.bulkTransfer(endpointOut,
bytesHello, bytesHello.length, 0);
Toast.makeText(MainActivity.this, "bulkTransfer: " + usbResult,
Toast.LENGTH_LONG).show();
*/
}
} else {
manager.requestPermission(deviceFound, mPermissionIntent);
Toast.makeText(MainActivity.this, "Permission: " + permitToRead,
Toast.LENGTH_LONG).show();
textStatus.setText("Permission: " + permitToRead);
}
return success;
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
Toast.makeText(MainActivity.this, "ACTION_USB_PERMISSION",
Toast.LENGTH_LONG).show();
textStatus.setText("ACTION_USB_PERMISSION");
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
connectUsb();
}
} else {
Toast.makeText(MainActivity.this,
"permission denied for device " + device,
Toast.LENGTH_LONG).show();
textStatus.setText("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_ATTACHED.equals(action)) {
deviceFound = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
Toast.makeText(
MainActivity.this,
"ACTION_USB_DEVICE_ATTACHED: \n"
+ deviceFound.toString(), Toast.LENGTH_LONG)
.show();
textStatus.setText("ACTION_USB_DEVICE_ATTACHED: \n"
+ deviceFound.toString());
connectUsb();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
Toast.makeText(MainActivity.this,
"ACTION_USB_DEVICE_DETACHED: \n" + device.toString(),
Toast.LENGTH_LONG).show();
textStatus.setText("ACTION_USB_DEVICE_DETACHED: \n"
+ device.toString());
if (device != null) {
if (device == deviceFound) {
releaseUsb();
}else{
Toast.makeText(MainActivity.this,
"device == deviceFound, no call releaseUsb()\n" +
device.toString() + "\n" +
deviceFound.toString(),
Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(MainActivity.this,
"device == null, no call releaseUsb()", Toast.LENGTH_LONG).show();
}
textInfo.setText("");
}
}
};
}
Create /res/xml/device_filter.xml to specify vendor-id and product-id.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- idVendor=2341, idProduct=0043 for Arduino Uno R3 -->
<usb-device
vendor-id="9025"
product-id="0067" />
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidusbhostarduinouno"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="keyboard|orientation"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
</activity>
</application>
</manifest>
layout, /res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.androidusbhostarduinouno.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<EditText
android:id="#+id/textout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send"/>
<TextView
android:id="#+id/textstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/textdevicename"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold|italic" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/info"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/searchedendpoint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
I hope it will helps you
I am developing an application that sends over a webservice information about the last dialed number, call status, and duration of the call.
The application works perfectly fine, but when the device closes the application the android service does restart but the activity does not.
The way I am sure about that is that I have Toasts when the service is started: "Servicio TRUCKA iniciado" and "Servicio TRUCKA creado" tell me that the service has been created and started.
And when the information is sent to the webservice I have toasts saying: "Enviando información..." and "Información enviada."
But when the application is closed (via the android task manager that automatically closes apps) the messages from the service "Servicio TRUCKA iniciado" and "Servicio TRUCKA creado" do appear, but the toasts from the information sent part do not.
I hope someone can help me and tell what am I doing wrong? :)
This is my Activity:
package com.trucka.llamadasdrivers;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import com.trucka.llamadasdrivers.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;
import android.widget.Toast;
import android.telephony.*;
import android.util.Log;
import java.text.SimpleDateFormat;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class ActividadLlamadasDrivers extends Activity {
TextView txtInformacion = null;
TextView txtDetalles = null;
TextView tv = null;
// Comunicación con el webservice.
private final String NAMESPACE = "http://truckanet.com/MensajeOperador";
// private final String URL =
// "http://192.168.10.94/MensajeOperador/MensajeOperador.asmx";
private final String URL = "http://200.76.187.148/MensajeOperador/MensajeOperador.asmx";
private final String SOAP_ACTION = "http://truckanet.com/MensajeOperador/ActualizarFede";
private final String METHOD_NAME = "ActualizarFede";
private String TAG = "TRUCKA_DRIVERS";
private String resultado;
String phNumber = null;
String callType = null;
String callDate = null;
DateFormat shortFecha = null;
DateFormat shortDF = null;
Date callDayTime = null;
Date fin = null;
String fechaLlamada1 = null;
String fechaLlamada2 = null;
String callDuration = null;
String dir = null;
public String tolo = null;
String imei = null;
String comentario = null;
String fechaRegistro = null;
String insercion = null;
String fechaInicio = null;
String fechaFin = null;
String estadoLlamada = null;
int reinicios = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_llamadas_drivers);
if (!ServicioLlamadas.isRunning()) {
reinicios ++;
Toast.makeText(getApplicationContext(), Integer.toString(reinicios) , Toast.LENGTH_LONG).show();
Intent in = new Intent(ActividadLlamadasDrivers.this,
ServicioLlamadas.class);
ActividadLlamadasDrivers.this.startService(in);
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(),
PhoneStateListener.LISTEN_CALL_STATE);
tv = (TextView) findViewById(R.id.txvEstadoServicio);
txtInformacion = (TextView) findViewById(R.id.textview_call);
txtDetalles = (TextView) findViewById(R.id.textview_call2);
}
}
class TeleListener extends PhoneStateListener {
private boolean telefonoLlamando = false;
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
//getCallDetails();
telefonoLlamando = true;
Toast.makeText(getApplicationContext(),
"Enviando información...", Toast.LENGTH_SHORT).show();
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended,
// need detect flag from CALL_STATE_OFFHOOK
Toast.makeText(getApplicationContext(),
"Información enviada.", Toast.LENGTH_SHORT).show();
if (telefonoLlamando) {
// restart app
getCallDetails();
telefonoLlamando = false;
}
}
}
}
// Obtener la fecha actual del teléfono.
public long getTodayTimestamp() {
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
return c2.getTimeInMillis();
}
// Obtener el detalle de las llamadas con la fecha actual.
#SuppressLint("SimpleDateFormat")
private void getCallDetails() {
String timestamp = String.valueOf(getTodayTimestamp());
StringBuffer sb = new StringBuffer();
#SuppressWarnings("deprecation")
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
CallLog.Calls.DATE + ">= ?", new String[] { timestamp }, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Bitácora de llamadas :");
Integer contador = 0;
// while (managedCursor.moveToNext()) {
// managedCursor.moveToFirst();
managedCursor.moveToLast();
contador = contador + 1;
phNumber = managedCursor.getString(number);
callType = managedCursor.getString(type);
callDate = managedCursor.getString(date);
shortFecha = DateFormat.getDateInstance(DateFormat.SHORT);
shortDF = DateFormat.getTimeInstance(DateFormat.SHORT);
callDayTime = new Date(Long.valueOf(callDate));
fechaLlamada1 = shortDF.format(callDayTime);
fechaLlamada2 = shortFecha.format(callDayTime);
callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "Saliente";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "Entrante";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "Perdida";
break;
}
imei = mngr.getDeviceId();
comentario = dir;
fechaRegistro = fechaLlamada2;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String ahorita = df.format(callDayTime);
fechaInicio = ahorita.toString();
// fechaFin =
// df.format(callDayTime.setSeconds(callDayTime.getSeconds()+5));
insercion = "DECLARE #claveDriver INT, #nombreDriver VARCHAR(max), #evento VARCHAR(max), #duracion int, #inicial varchar(max) "
+ "SET #claveDriver = (SELECT cve_tra FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"
+ mngr.getDeviceId()
+ "') "
+ "SET #nombreDriver = (SELECT nombre FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"
+ mngr.getDeviceId()
+ "') "
+ "SET #duracion = "
+ managedCursor.getString(duration)
+ "SET #evento = '(LOG) Llamada "
+ dir
+ ". Duración ' + CONVERT(varchar, #duracion, 103) + ' segundos al número: "
+ managedCursor.getString(number)
+ "' "
// + "SET #duracion = " + callDuration
+ " SET #inicial = '"
+ fechaInicio
+ "'"
+ "INSERT INTO bitacora.dbo.registroDellamadasOperadores (fechacreacion,fecha_fin,fecha_inicio,idMobil,Tractor,Nom_tra,Cve_tra,FechaRegistro,Evento) "
+ " VALUES('"
+ fechaInicio
+ "', DATEADD(SECOND,#duracion,#inicial),'"
+ fechaInicio
+ "','"
+ mngr.getDeviceId()
+ "','',#nombreDriver,#claveDriver,current_timestamp,#evento)";
AsyncCallWS tareaEnviarABD = new AsyncCallWS();
tareaEnviarABD.execute();
sb.append("\nNúmero de teléfono:--- " + phNumber
+ " \nTipo de llamada:--- " + dir + " \nFecha de llamada:--- "
+ fechaLlamada2 + " " + fechaLlamada1
+ " \nDuración en segundos:--- " + callDuration
+ " \nDispositivo actual:--" + mngr.getDeviceId());
sb.append("\n----------------------------------");
// }
txtDetalles.setText(sb);
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
InsertarLlamada(insercion);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
txtInformacion.setText("Información enviada");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
txtInformacion.setText("Enviando información...");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
public void InsertarLlamada(String insercion) {
// Creamos la solicitud
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Propiedades que contienen los valores
PropertyInfo propiedades = new PropertyInfo();
propiedades.setName("insercion");
propiedades.setValue(insercion);
propiedades.setType(String.class);
// Agregamos las propiedades
request.addProperty(propiedades);
// Creamos el envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
// ponemos la salida SOAP
envelope.setOutputSoapObject(request);
// Creamos la llamada HTTP
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invocamos el servicio
androidHttpTransport.call(SOAP_ACTION, envelope);
// Obtenemos la respuesta
Object response = envelope.getResponse();
// Asignamos el resultado de la consulta
resultado = response.toString();
} catch (Exception e) {
resultado = e.getMessage();
}
}
}
}
BootReceiver class:
package com.trucka.llamadasdrivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, ActividadLlamadasDrivers.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
Llamadas service:
package com.trucka.llamadasdrivers;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.widget.Toast;
public class ServicioLlamadas extends Service {
private static ServicioLlamadas instance = null;
public static boolean isRunning() {
return instance != null;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA creado",
Toast.LENGTH_SHORT).show();
instance = this;
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA destruído",
Toast.LENGTH_SHORT).show();
instance = null;
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA iniciado",
Toast.LENGTH_SHORT).show();
lanzarNotificacion();
}
#SuppressWarnings("deprecation")
void lanzarNotificacion() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notManager = (NotificationManager) getSystemService(ns);
// Configuramos la notificacion
Notification notif = new Notification(
android.R.drawable.ic_menu_agenda, "Servicio TRUCKA",
System.currentTimeMillis());
// Configuramos el Intent
Context contexto = ServicioLlamadas.this;
CharSequence titulo = "Notificación Servicio TRUCKA";
CharSequence descripcion = "Registro habilitado.";
// Intent que se abrira al clickear la notificacion
PendingIntent contIntent = PendingIntent.getActivity(contexto, 0, null,
0);
notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.defaults |= Notification.DEFAULT_VIBRATE;
notManager.notify(1, notif);
}
}
And manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.trucka.llamadasdrivers"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.trucka.llamadasdrivers.ActividadLlamadasDrivers"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.trucka.llamadasdrivers.ServicioLlamadas"
android:enabled="true"
android:icon="#drawable/ic_launcher" >
</service>
<receiver android:name=".BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Human stupidity has no limits.
My actines where not in the service
I am having difficulty making my layout to work...
What I want to do is have two spinners and a button below those and once the button is clicked, I display the results based on the values selected in the spinners.
-----------
| Spinner 1 |
-----------
-----------
| Spinner 2 |
-----------
-----------
| Button |
-----------
Result 1
Result 2
Result 3
Result 4
Result 5
I have tried to put the results in a ListView, but the problem I face is that once the button is clicked, I can see the repetition of Spinner1, Spinner2 and the Button itself multiple times.
The xml for the layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/done" />
<LinearLayout
android:id="#+id/moreContent"
android:layout_width="match_parent"
android:visibility="visible"
android:orientation="vertical"
android:layout_height="wrap_content"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
</LinearLayout>
Can someone please advise where am I going wrong?
The code is as follows:
package ms.timetable;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ListActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
RetreiveFeedTask rft = new RetreiveFeedTask();
rft.execute();
}
});
}
#SuppressLint("NewApi")
private class RetreiveFeedTask extends AsyncTask<Void, Void, String> {
TreeMap<String, String> _timetable = null;
#Override
protected String doInBackground(Void... arg0) {
// TODO Auto-generated method stub
_timetable = FetchTimetableInfo();
return null;
}
protected void onPostExecute(String str){
if (_timetable != null){
ArrayList<TimeTable> tarr = new ArrayList<TimeTable>();
Iterator<Entry<String, String>> it = _timetable.entrySet().iterator();
String toastText = "";
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
toastText = toastText + key + " --- " + value + "\n";
//System.err.println(key + " --- " + value);
TimeTable tt = new TimeTable();
tt.set_line(value);
String [] tem = key.split("---");
tt.set_arrival(tem[1]);
tt.set_departure(tem[1]);
tarr.add(tt);
}
//Toast.makeText(context, toastText, Toast.LENGTH_LONG).show();
//tmap.add(_timetable);
setListAdapter((ListAdapter) new TimetableAdapter(getApplicationContext(), tarr));
}
}
private TreeMap<String, String> FetchTimetableInfo(){
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
String origin = (String) spinner1.getSelectedItem();
String destination = (String) spinner2.getSelectedItem();
//String val = String.valueOf(spinner1.getSelectedItem());
ArrayList<String> linesServOrigin = LineStation.GetServingLines(origin);
ArrayList<String> linesServDest = LineStation.GetServingLines(destination);
linesServOrigin.retainAll(linesServDest);
//ArrayList<String> preferredLines = linesServOrigin.re.retainAll(linesServDest);
Log.e(this.getClass().toString(), "Selected value is : " + linesServOrigin.get(0));
try
{
for (int k = 0; k < linesServOrigin.size(); k++)
{
String url = "http://tt.ptv.vic.gov.au/tt/XSLT_REQUEST?itdLPxx_lineMain=" + LineStation.GetLineMain(linesServOrigin.get(0)) + "&itdLPxx_lineID=" + LineStation.GetLineID(linesServOrigin.get(0)) + "&itdLPxx_output=html";
DataManager dm = new DataManager(url, getApplicationContext());
ArrayList<String> stationData = dm.GetStationsData();
ArrayList<ArrayList<String>> timetableData = dm.GetTimetableData();
ArrayList<String> originTimetable = null;
ArrayList<String> originTimetable1 = null;
ArrayList<String> destinationTimetable = null;
ArrayList<String> destinationTimetable1 = null;
int origPos = 0;
int destPos = 0;
int ctr = 0;
for (int i = 0; i < stationData.size(); i++)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
//originTimetable = timetableData[i];
origPos = i;
}
else if (stationData.get(i).equals( destination) || (destination + " - ARR").equals(stationData.get(i)))
{
//destinationTimetable = timetableData[i];
destPos = i;
}
if (origPos != 0 && destPos != 0)
{
break;
}
}
if (origPos > destPos)
{
dm.SwitchDirection();
stationData = dm.GetStationsData();
timetableData = dm.GetTimetableData();
}
for (int i = stationData.size() - 1; i >= 0; i--)
{
if (stationData.get(i).equals(origin) || (origin + " - DEP").equals(stationData.get(i)))
{
if (originTimetable == null)
{
originTimetable = timetableData.get(i);
}
else if (originTimetable1 == null)
{
originTimetable1 = timetableData.get(i);
}
}
else if (stationData.get(i).equals(destination) || (destination + " - ARR").equals(stationData.get(i)))
{
if (destinationTimetable == null)
{
destinationTimetable = timetableData.get(i);
}
else if (destinationTimetable1 == null)
{
destinationTimetable1 = timetableData.get(i);
}
}
}
TreeMap<String, String> ttable = new TreeMap<String, String>();
if (originTimetable != null && destinationTimetable != null)
{
//int curtime = Integer.parseInt(DateTime.Now.ToString("HHmm", CultureInfo.CurrentCulture));
String temp = new SimpleDateFormat("HHmm").format(Calendar.getInstance().getTime());
int curtime =Integer.parseInt(temp);
System.err.println("Origin timetable size = " + originTimetable.size());
System.err.println("Destination timetable size = " + destinationTimetable.size());
for (int j = 0; j < originTimetable.size(); j++)
{
if (Integer.parseInt((originTimetable.get(j))) > curtime)
{
if (Integer.parseInt((destinationTimetable.get(j))) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j)) == -1))
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
ctr = 0;
if (originTimetable1 != null)
{
for (int j = 0; j < originTimetable1.size(); j++)
{
if (originTimetable1 != null && Integer.parseInt(originTimetable1.get(j)) > curtime)
{
if (Integer.parseInt(destinationTimetable.get(j)) == -1)
{
if (destinationTimetable1 == null || (Integer.parseInt(destinationTimetable1.get(j)) == -1))
{
continue;
}
}
else if (destinationTimetable1 != null && Integer.parseInt(destinationTimetable1.get(j)) == -1)
{
if (destinationTimetable == null || (Integer.parseInt(destinationTimetable.get(j))) == -1)
{
continue;
}
}
ctr++;
if (destinationTimetable1 != null)
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable1.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable1.get(j), linesServOrigin.get(k));
}
}
else
{
if (Integer.parseInt(originTimetable1.get(j)) < Integer.parseInt(destinationTimetable.get(j)))
{
ttable.put(originTimetable1.get(j) + " --- " + destinationTimetable.get(j), linesServOrigin.get(k));
}
}
if (ctr == 5)
{
break;
}
}
}
}
Iterator<Entry<String, String>> it = ttable.entrySet().iterator();
//foreach (KeyValuePair<String, List<String>> item in lineStations)
while (it.hasNext())
{
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
String key = pairs.getKey();
String value = pairs.getValue();
System.err.println(key + " --- " + value);
}
return ttable;
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
class TimeTable{
private String _departure, _arrival, _line;
public TimeTable(){
}
public TimeTable(String departure, String arrival, String line){
_departure = departure;
_arrival = arrival;
_line = line;
}
public String get_departure() {
return _departure;
}
public void set_departure(String _departure) {
this._departure = _departure;
}
public String get_arrival() {
return _arrival;
}
public void set_arrival(String _arrival) {
this._arrival = _arrival;
}
public String get_line() {
return _line;
}
public void set_line(String _line) {
this._line = _line;
}
}
}
The adapter is as follows:
package ms.timetable;
import java.util.ArrayList;
import ms.timetable.MainActivity.TimeTable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TimetableAdapter extends ArrayAdapter<TimeTable>{
private final Context context;
private final ArrayList<TimeTable> values;
public TimetableAdapter(Context context, ArrayList<TimeTable> values){
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
TextView textView2 = (TextView) rowView.findViewById(R.id.textView2);
//System.err.println("Position is : "+position);
TimeTable tt = values.get(position);
textView.setText(tt.get_departure());
textView2.setText(tt.get_arrival());
return rowView;
}
}
The problem is due to
View rowView = inflater.inflate(R.layout.activity_main, parent, false);
in getView() method.
You are inflating whole activity_main in a row and then adding it to a listview.
Put a row for results in separate xml instead of activity_main. So you will have a new xml file say, row.xml which will contain:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#ff0000"
android:textSize="12sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/hello_world"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#0000ff"
android:textSize="12sp" />
So you will have to inflate as
View rowView = inflater.inflate(R.layout.row, parent, false);
And then add the generated rows in the listview which is in activity_main.xml.
So your problem will be solved. Hope it helps.
First off I wanted to thank everyone for the help I've gotten on my last few questions. I've searched and done my best to figure out my latest problem but I've had no luck even after searching here. I'm trying to check to see if "heapFile.csv" exists and if it doesn't, to create the file and then write a string to it. If it does then I just want to append a string to it instead. I think what I have will do that but I keep getting an IOException along with it saying the file system is Read Only. I do have the manifest file changed to include accessing the sdcard and even used the android too to make a virtual sdcard in case that was the problem.
First here's the main activity java...
package com.loch.meaptracker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private SeekBar happyBar, energyBar, anxietyBar, painBar;
private EditText noteField;
private DatePicker dPick;
private TimePicker tPick;
#SuppressWarnings("unused")
private Button enterButton;
private int happyValue = 4, energyValue = 4, anxietyValue = 4,
painValue = 4;
private static final String TAG = "heapApp";
private String Mood = "Blah";
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bars
happyBar = (SeekBar) findViewById(R.id.happinessBarID);
happyBar.setOnSeekBarChangeListener(this);
energyBar = (SeekBar) findViewById(R.id.energyBarID);
energyBar.setOnSeekBarChangeListener(this);
anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID);
anxietyBar.setOnSeekBarChangeListener(this);
painBar = (SeekBar) findViewById(R.id.painBarID);
painBar.setOnSeekBarChangeListener(this);
// end bars
dPick = (DatePicker) findViewById(R.id.datePicker1);
tPick = (TimePicker) findViewById(R.id.timePicker1);
noteField = (EditText) findViewById(R.id.noteTextFieldID);
enterButton = (Button) findViewById(R.id.enterButtonID);
} catch (Exception onCreateException) {
Log.e(TAG, "Exception received", onCreateException);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Bar listener methods
#Override
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) {
try {
switch (arg0.getId()) {
case R.id.happinessBarID:
happyValue = barValue + 1;
break;
case R.id.energyBarID:
energyValue = barValue + 1;
break;
case R.id.anxietyBarID:
anxietyValue = barValue + 1;
break;
case R.id.painBarID:
painValue = barValue + 1;
break;
}
String debugBarValue = "Happy is " + happyValue + ", Energy is "
+ energyValue + ", Anxiety is " + anxietyValue
+ ", Pain is " + painValue + ".";
System.out.println(debugBarValue);
} catch (Exception BarValueException) {
Log.e(TAG, "Exception received", BarValueException);
}
}
#Override
public void onStartTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
// end Bar listener methods
// Enter Button listener Method
public void dialogPop(View v) {
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set Title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage("You entered: " + getMood())
.setCancelable(false).setPositiveButton("Okay",
// When Okay button clicked the write mood string to file
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
try {
// This is the string that should be
// written to file
String data = getMood();
// This is the file that should be
// written to
File heapFile = new File(Environment.getExternalStorageDirectory(), "/heapFile.csv");
// if file doesn't exists, then create
// it
if (!heapFile.exists()) {
heapFile.createNewFile();
}
// true = append file
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
BufferedWriter heapBufferWritter = new BufferedWriter(
heapFileWritter);
heapBufferWritter.write(data);
heapBufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
})
// If they press either the cancel button or the back button
// on their device (Same thing) then close the dialog and
// give the user a chance to change what they've entered
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} catch (Exception buttonListenerException) {
Log.e(TAG, "Exception received", buttonListenerException);
}
return;
}
public String getMood() {
try {
int month = dPick.getMonth();
int day = dPick.getDayOfMonth();
int year = dPick.getYear();
int minute = tPick.getCurrentMinute();
String moodAntePost = "AM";
boolean hourType = tPick.is24HourView();
int moodHour = tPick.getCurrentHour();
if (hourType == false && moodHour > 12) {
moodHour = (moodHour - 12);
moodAntePost = "PM";
} else if (hourType == false && moodHour <= 0) {
moodHour = 12;
} else {
}
String noteText = noteField.getText().toString();
Mood = "Happiness," + happyValue + ",Energy," + energyValue
+ ",Anxiety," + anxietyValue + ",Pain," + painValue
+ ",Date," + month + "/" + day + "/" + year + ",Time,"
+ moodHour + ":" + minute + "," + moodAntePost + ",Note,"
+ noteText;
System.out.println(Mood);
} catch (Exception getMoodException) {
Log.e(TAG, "Exception received", getMoodException);
}
return Mood;
}
}
And the Manifest...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loch.meaptracker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.loch.meaptracker.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I think problem is in this line:
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
instead try this:
FileWriter heapFileWritter = new FileWriter(
heapFile, true);
explanation:
heapFile.getName() refers to your file name so lets say heapFile.txt.
so when you ask FileWriter to write to this file. It doesn't know which file you are referring to. So it try to create the file. But wait! where it will create the file, as it has only the file name, not the complete path.
So even I am sure where it would think of creating the file, my guess is Root( I am not sure). Which is read-only hence the error.
public FileWriter(String fileName,
boolean append)
throws IOException
IOException - if the named file exists but is a directory rather than
a regular file, does not exist but cannot be created, or cannot be
opened for any other reason