Putting Views on top SurfaceView Android - android

I need help with my code on Android, I've been trying and searching for 3 hours and no luck
so what I've is a library that call MediaPlayerSDK, I'm using it in my application to play videos. The library is using SurfaceView to play video. Now, I've to include getSurfaceView().setZOrderOnTop(true) to the player so I can show the video otherwise it will not be shown ( only audio). But, when I'm using getSurfaceView().setZOrderOnTop(true) I cannot put any view on top of player. I want to build a controllers to the player but I couldn't. I've tired getSurfaceView().setZOrderMediaOverlay(true) and same problem the video is not shown.
The XML code for Activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent">
<FrameLayout
android:id="#+id/playerViewLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:text="...."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ChTitle"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_marginLeft="5dp"/>
<veg.mediaplayer.sdk.MediaPlayer
android:id="#+id/playerView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</FrameLayout>
</RelativeLayout>
And the java code is
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.MediaPlayerCallback {
private static final String TAG = "Tag";
private boolean playing = false;
private MediaPlayer player = null;
private enum PlayerStates
{
Busy,
ReadyForUse
};
private enum PlayerConnectType
{
Normal,
Reconnecting
};
private PlayerStates player_state = PlayerStates.ReadyForUse;
private PlayerConnectType reconnect_type = PlayerConnectType.Normal;
private int mOldMsg = 0;
// Event handler
private Handler handler = new Handler()
{
String strText = "Connecting";
String sText;
String sCode;
#Override
public void handleMessage(Message msg)
{
MediaPlayer.PlayerNotifyCodes status = (MediaPlayer.PlayerNotifyCodes) msg.obj;
switch (status)
{
case CP_CONNECT_STARTING:
if (reconnect_type == PlayerConnectType.Reconnecting)
strText = "Reconnecting";
else
strText = "Connecting";
player_state = PlayerStates.Busy;
//showStatusView();
reconnect_type = PlayerConnectType.Normal;
break;
case PLP_BUILD_SUCCESSFUL:
sText = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_TEXT);
sCode = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_CODE);
Log.i(TAG, "=Status PLP_BUILD_SUCCESSFUL: Response sText="+sText+" sCode="+sCode);
break;
case VRP_NEED_SURFACE:
player_state = PlayerStates.Busy;
//showVideoView();
break;
case PLP_PLAY_SUCCESSFUL:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
break;
case PLP_CLOSE_STARTING:
player_state = PlayerStates.Busy;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_CLOSE_SUCCESSFUL:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
System.gc();
setUIDisconnected();
break;
case PLP_CLOSE_FAILED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case CP_CONNECT_FAILED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_BUILD_FAILED:
sText = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_TEXT);
sCode = player.getPropString(MediaPlayer.PlayerProperties.PP_PROPERTY_PLP_RESPONSE_CODE);
Log.i(TAG, "=Status PLP_BUILD_FAILED: Response sText="+sText+" sCode="+sCode);
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_PLAY_FAILED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case PLP_ERROR:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case CP_INTERRUPTED:
player_state = PlayerStates.ReadyForUse;
//stopProgressTask();
//showStatusView();
setUIDisconnected();
break;
case CP_RECORD_STARTED:
Log.v(TAG, "=handleMessage CP_RECORD_STARTED");
{
String sFile = player.RecordGetFileName(1);
Toast.makeText(getApplicationContext(),"Record Started. File "+sFile, Toast.LENGTH_LONG).show();
}
break;
case CP_RECORD_STOPPED:
Log.v(TAG, "=handleMessage CP_RECORD_STOPPED");
{
String sFile = player.RecordGetFileName(0);
Toast.makeText(getApplicationContext(),"Record Stopped. File "+sFile, Toast.LENGTH_LONG).show();
}
break;
//case CONTENT_PROVIDER_ERROR_DISCONNECTED:
case CP_STOPPED:
case VDP_STOPPED:
case VRP_STOPPED:
case ADP_STOPPED:
case ARP_STOPPED:
if (player_state != PlayerStates.Busy)
{
//stopProgressTask();
player_state = PlayerStates.Busy;
player.Close();
//showStatusView();
player_state = PlayerStates.ReadyForUse;
setUIDisconnected();
}
break;
case CP_ERROR_DISCONNECTED:
if (player_state != PlayerStates.Busy)
{
player_state = PlayerStates.Busy;
player.Close();
//showStatusView();
player_state = PlayerStates.ReadyForUse;
setUIDisconnected();
Toast.makeText(getApplicationContext(), "Demo Version!",
Toast.LENGTH_SHORT).show();
}
break;
default:
player_state = PlayerStates.Busy;
}
}
};
// callback from Native Player
#Override
public int OnReceiveData(ByteBuffer buffer, int size, long pts)
{
Log.e(TAG, "Form Native Player OnReceiveData: size: " + size + ", pts: " + pts);
return 0;
}
// All event are sent to event handlers
#Override
public int Status(int arg)
{
MediaPlayer.PlayerNotifyCodes status = MediaPlayer.PlayerNotifyCodes.forValue(arg);
if (handler == null || status == null)
return 0;
Log.e(TAG, "Form Native Player status: " + arg);
switch (MediaPlayer.PlayerNotifyCodes.forValue(arg))
{
default:
Message msg = new Message();
msg.obj = status;
handler.removeMessages(mOldMsg);
mOldMsg = msg.what;
handler.sendMessage(msg);
}
return 0;
}
Intent getI;
String Title, Path = TEST_URL;
TextView ChannelTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myplayer);
getI = getIntent();
// Create Player instance
player = (MediaPlayer)findViewById(R.id.playerView);
ChannelTitle = (TextView) findViewById(R.id.ChTitle);
Title = getI.getStringExtra("title");
Path = getI.getStringExtra("path");
ChannelTitle.setText(Title);
player.getSurfaceView().setZOrderMediaOverlay(true); // necessary
SurfaceHolder sfhTrackHolder = player.getSurfaceView().getHolder();
sfhTrackHolder.setFormat(PixelFormat.TRANSPARENT);
player.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
{
if (player.getState() == MediaPlayer.PlayerState.Paused)
player.Play();
else
if (player.getState() == MediaPlayer.PlayerState.Started)
player.Pause();
}
}
return true;
}
});
if (player != null)
{
player.getConfig().setConnectionUrl(Path);
if (player.getConfig().getConnectionUrl().isEmpty())
return;
//player_record.Close();
player.Close();
PlayerSettings sett = new PlayerSettings();
boolean bPort = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
int aspect = bPort ? 1 : sett.rendererEnableAspectRatio;
MediaPlayerConfig conf = new MediaPlayerConfig();
player.setVisibility(View.INVISIBLE);
conf.setConnectionUrl(player.getConfig().getConnectionUrl());
conf.setConnectionNetworkProtocol(sett.connectionProtocol);
conf.setConnectionDetectionTime(sett.connectionDetectionTime);
conf.setConnectionBufferingTime(sett.connectionBufferingTime);
conf.setDecodingType(sett.decoderType);
conf.setRendererType(sett.rendererType);
conf.setSynchroEnable(sett.synchroEnable);
conf.setSynchroNeedDropVideoFrames(sett.synchroNeedDropVideoFrames);
conf.setEnableColorVideo(sett.rendererEnableColorVideo);
conf.setEnableAspectRatio(aspect);
conf.setDataReceiveTimeout(30000);
conf.setNumberOfCPUCores(0);
// Open Player
player.Open(conf, this);
//record only
//conf.setMode(MediaPlayer.PlayerModes.PP_MODE_RECORD);
//conf.setRecordTrimPosStart(10000); //from 10th sec
//conf.setRecordTrimPosEnd(20000); //to 20th sec
/*player_record.Open(conf, new MediaPlayerCallback(){
#Override
public int Status(int arg) {
Log.i(TAG, "=player_record Status arg="+arg);
return 0;
}
#Override
public int OnReceiveData(ByteBuffer buffer, int size,
long pts) {
// TODO Auto-generated method stub
return 0;
}
});*/
playing = true;
}
}
private int[] mColorSwapBuf = null; // used by saveFrame()
public Bitmap getFrameAsBitmap(ByteBuffer frame, int width, int height)
{
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(frame);
return bmp;
}
protected void onPause()
{
Log.e("SDL", "onPause()");
super.onPause();
if (player != null)
player.onPause();
}
#Override
protected void onResume()
{
Log.e("SDL", "onResume()");
super.onResume();
if (player != null)
player.onResume();
}
#Override
protected void onStart()
{
Log.e("SDL", "onStart()");
super.onStart();
if (player != null)
player.onStart();
}
#Override
protected void onStop()
{
Log.e("SDL", "onStop()");
super.onStop();
if (player != null)
player.onStop();
}
#Override
public void onBackPressed() {
player.Close();
setUIDisconnected();
if (!playing)
{
super.onBackPressed();
return;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
Log.e("SDL", "onWindowFocusChanged(): " + hasFocus);
super.onWindowFocusChanged(hasFocus);
if (player != null)
player.onWindowFocusChanged(hasFocus);
}
#Override
public void onLowMemory()
{
Log.e("SDL", "onLowMemory()");
super.onLowMemory();
if (player != null)
player.onLowMemory();
}
#Override
protected void onDestroy()
{
Log.e("SDL", "onDestroy()");
if (player != null)
player.onDestroy();
System.gc();
super.onDestroy();
}
protected void setUIDisconnected()
{
playing = false;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
Please I need help on that
Thank you

Related

onServiceConnected not called

I'm developing a cordava plugin that manages my expansion files for android. The reading of an expansion file works, but I have problems with downloading them.
Here is my plugin:
public class ExpansionFileReader extends CordovaPlugin implements IDownloaderClient {
private final String MEDIA_FOLDER_NAME = "mediafiles";
private final String MAIN_EXPANSION = "main_expansion";
private final String URL = "url";
private final String TAG = "expansionFileReader";
private Context context;
private CallbackContext callbackContext;
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
JSONObject callbackValue = new JSONObject();
context = this.cordova.getActivity().getApplicationContext();
if(action.equalsIgnoreCase("downloadExpansionFileIfNecessary")) {
this.callbackContext = callbackContext;
downloadExpansionFileIfNecessary();
} else if(action.equalsIgnoreCase("getFile")){
[getFileAction]
}
return true;
}
private void downloadExpansionFileIfNecessary() {
if (!expansionFilesDelivered()) {
Log.d(TAG, "NO EXPANSION FILE FOUND");
try {
Intent launchIntent = this.cordova.getActivity().getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent((context), context.getClass());
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
if (launchIntent.getCategories() != null) {
for (String category : launchIntent.getCategories()) {
intentToLaunchThisActivityFromNotification.addCategory(category);
}
}
PendingIntent pendingIntent = PendingIntent.getActivity((context), 0, intentToLaunchThisActivityFromNotification, PendingIntent.FLAG_UPDATE_CURRENT);
// Request to start the download
Log.d(TAG, "REQUEST TO START DOWNLOAD");
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(context, pendingIntent, DownloaderService.class);
if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, DownloaderService.class);
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(context);
}
return;
}
else {
Log.d(TAG, "DOWNLOAD NOT NECESSARY");
callbackContext.success();
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Cannot find package!", e);
}
} else {
validateXAPKZipFiles();
}
}
/////////////////////////////
// INIT DOWNLOADS
/////////////////////////////
private IDownloaderService mRemoteService;
private IStub mDownloaderClientStub;
private int mState;
private boolean mCancelValidation;
// region Expansion Downloader
private static class XAPKFile {
public final boolean mIsMain;
public final int mFileVersion;
public final long mFileSize;
XAPKFile(boolean isMain, int fileVersion, long fileSize) {
mIsMain = isMain;
mFileVersion = fileVersion;
mFileSize = fileSize;
}
}
private static final XAPKFile[] xAPKS = {
new XAPKFile(
true, // true signifies a main file
1000006, // the version of the APK that the file was uploaded against
443975466L // the length of the file in bytes
)
};
static private final float SMOOTHING_FACTOR = 0.005f;
#Override
public void onStart() {
Log.d(TAG, "ON START");
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(context);
}
super.onStart();
}
#Override
public void onStop() {
Log.d(TAG, "ON STOP");
if (null != mDownloaderClientStub) {
mDownloaderClientStub.disconnect(context);
}
super.onStop();
}
#Override
public void onServiceConnected(Messenger m) {
Log.d(TAG, "ON SERVICE CONNECTED");
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
#Override
public void onDownloadStateChanged(int newState) {
Log.d(TAG, "ON DOWNLOAD STATE CHANGED: " + newState);
setState(newState);
boolean showDashboard = true;
boolean showCellMessage = false;
boolean paused;
boolean indeterminate;
switch (newState) {
case IDownloaderClient.STATE_IDLE:
// STATE_IDLE means the service is listening, so it's
// safe to start making calls via mRemoteService.
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_CONNECTING:
case IDownloaderClient.STATE_FETCHING_URL:
showDashboard = true;
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_DOWNLOADING:
paused = false;
showDashboard = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
paused = true;
showDashboard = false;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
paused = true;
indeterminate = false;
showCellMessage = true;
break;
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_ROAMING:
case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_COMPLETED:
showDashboard = false;
paused = false;
indeterminate = false;
validateXAPKZipFiles();
return;
default:
paused = true;
indeterminate = true;
showDashboard = true;
}
}
#Override
public void onDownloadProgress(DownloadProgressInfo progress) {
Log.d(TAG, "ON DOWNLOAD PROGESS: " + progress);
}
boolean expansionFilesDelivered() {
Log.d(TAG, "IF EXPANSION FILE IS DELIVERED");
for (XAPKFile xf : xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(context, xf.mIsMain, xf.mFileVersion);
if (!Helpers.doesFileExist(context, fileName, xf.mFileSize, false)) {
Log.d(TAG, "EXPANSION FILE DOESN'T EXIST");
return false;
}
}
Log.d(TAG, "EXPANSION FILE EXIST");
return true;
}
}
My problem is that onServiceConnected is never called although I call mDownloaderClientStub.connect(context);
Does anybody know why it is not called? I'm getting no error either.
The service connection could not be established because you pass an incorrect Class object into the expansion library methods.
You should change the argument in the call to DownloaderClientMarshaller from DownloaderService.class to MyDownloaderService.class or whichever class you use to extend the base DownloaderService. Also, make sure that your service is defined in your app's manifest.
// use the correct service class!
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(context, pendingIntent, MyDownloaderService.class);
// when creating a stub also
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, MyDownloaderService.class);
I recommend using the updated Downloader Library included in Better APK Expansion package. It has this and other issues fixed and also provides simplified API that minimizes chances to shoot yourself in the foot.

android PDF rendering issue

I am realizing pdf viewer function using APV library
when I load pdf file using APV library I mentioned, some part of pages are invisible and sometimes not.
Invisible parts are sometimes paragraph and sometimes picture etc. I think it does not depend on object but trial.
Does anyone have similar problem? If anyone knows, please let me know.
I attached 2 picture that have same page, one normal and the other abnormal.
abnormal
normal
public class mPDFActivity extends PdfViewerActivity {
byte[] startSign = {0x31};
byte[] stopSign = {0x32};
public static boolean isPDFPageRunning = false; // bluetoothservice에서 이 activity로 신호 보낼 때 해당 변수 상태 보고 동작(page 넘김) 할지 말지 결정
public int getPreviousPageImageResource() { return R.drawable.left_arrow; }
public int getNextPageImageResource() { return R.drawable.right_arrow; }
public int getZoomInImageResource() { return R.drawable.zoom_in; }
public int getZoomOutImageResource() { return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() { return R.id.etPassword; }
public int getPdfPasswordOkButton() { return R.id.btOK; }
public int getPdfPasswordExitButton() { return R.id.btExit; }
public int getPdfPageNumberEditField() { return R.id.pagenum_edit; }
public int getMenuOpenFile() {return R.drawable.openfile;}
public int getMenuScanBluetooth() {return R.drawable.ic_action_device_access_bluetooth_searching;}
public Handler PDFHandler;
mPDFActivity currentActivity;
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig .orientation == newConfig.ORIENTATION_LANDSCAPE)
{
}else{
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
isPDFPageRunning = true;
super.onCreate(savedInstanceState);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
//FragmentActivity activity = getActivity();
Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_LONG).show();
this.finish();
}
byte a[] = {(byte)0x01, (byte)0xff};
if(a[1] == -1) {
int re = Conversion.ByteArraytoInteger(a[0], a[1]);
}
Log.d(TAG,"KK");
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences pref = getSharedPreferences("PDF",0);
SharedPreferences.Editor edit = pref.edit();
if(isAlreadyCreated)
{
}else{
}
edit.putFloat(Constants.ZOOM, mZoom);
edit.putInt(Constants.PAGE, mPage);
edit.commit();
}
#Override
protected void onResume() {
isPDFPageRunning = true;
super.onResume();
float zoom;
int page;
SharedPreferences pref = getSharedPreferences(Constants.PDF, 0);
zoom = pref.getFloat(Constants.ZOOM,1);
page = pref.getInt(Constants.PAGE,1);
if(!isAlreadyCreated){
}
}
#Override
protected void onStop() {
isPDFPageRunning = false;
super.onStop();
}
#Override
protected void onDestroy() {
isPDFPageRunning = false;
super.onDestroy();
mChatService.write(stopSign);
if (mChatService != null) {
mChatService.stop();
}
}
private static final String TAG = "BluetoothChatFragment";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* String buffer for outgoing messages
*/
private StringBuffer mOutStringBuffer;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
//public BluetoothChatService mChatService = null;
public BluetoothChatService mChatService = null;
ArrayAdapter adapter;
int clickCounter=0;
ArrayList listItems=new ArrayList();
private File[] imagelist;
String[] pdflist;
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
private void setupChat() {
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
//setupChat();
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
this.finish();
}
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//Activity activity = getApplicationContext();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(getString(R.string.title_connecting));
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(getString(R.string.title_not_connected));
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
break;
case Constants.MESSAGE_READ:
/*
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.what);
//Log.i(TAG,readMessage);
//mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
int bytes = msg.arg1; // length of read bytes array
String str = Conversion.byteArraytoHexString(readBuf).substring(0, bytes * 2);
str = str.substring(str.indexOf("ff"));
while(str.length() >= 10)
{
String datA = str.substring(2,5);
String datB = str.substring(6,9);
int dat1 = Conversion.hexStringtoInteger(datA);
int dat2 = Conversion.hexStringtoInteger(datB);
//TODO: 데이터 저장 및 신호처리
str = str.substring(10);
}
Log.e("READ","READ : " + str);
*/
//TODO : mPDFActivity로 메시지에 따른 intent 날려
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (mPDFActivity.this != null) {
Toast.makeText(mPDFActivity.this, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
mChatService.write(startSign);
}
break;
case Constants.MESSAGE_TOAST:
if (mPDFActivity.this != null) {
Toast.makeText(mPDFActivity.this, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_PREV_PAGE:
prevPage();
break;
case Constants.MESSAGE_NEXT_PAGE:
nextPage();
break;
case Constants.MESSAGE_VIBRATE:
Vibrator vb = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
int duration = msg.getData().getInt(Constants.VIBRATE);
vb.vibrate(duration);
break;
}
}
};
/**
* Establish connection with other divice
*
* #param data An {#link Intent} with {#link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* #param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
Activity activity = this;
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
}

How to use MagTek card reader device's sdk for android?

I am using magtek card reader audio uDynamo device and i am integrating sdk with my android application. But when i am trying to open device through openDevice() method. Application unfortunately stopped. Why its doing like this ?
This is what i am doing
m_SCRA.setConnectionType(MTConnectionType.Audio);
m_SCRA.setAddress(m_deviceAddress);
m_connectionState = MTConnectionState.Connected;
// here its stopping
m_SCRA.openDevice();
Full source code
public class MainActivity extends AppCompatActivity {
private MTSCRA m_SCRA;
private Button btn;
private TextView txt;
private TextView txt1;
private TextView msg;
private TextView msg2;
private boolean m_startTransactionActionPending;
private boolean m_turnOffLEDPending;
private EditText Edit;
private AudioManager m_audioManager;
private int m_audioVolume;
private String m_deviceAddress;
private MTConnectionType m_connectionType;
private MTConnectionState m_connectionState = MTConnectionState.Disconnected;
private Handler m_scraHandler = new Handler(new SCRAHandlerCallback());
private class SCRAHandlerCallback implements Handler.Callback {
public boolean handleMessage(Message msg)
{
try
{
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert Switch");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
switch (msg.what)
{
case MTSCRAEvent.OnDeviceConnectionStateChanged:
OnDeviceStateChanged((MTConnectionState) msg.obj);
break;
case MTSCRAEvent.OnCardDataStateChanged:
OnCardDataStateChanged((MTCardDataState) msg.obj);
break;
case MTSCRAEvent.OnDataReceived:
OnCardDataReceived((IMTCardData) msg.obj);
break;
case MTSCRAEvent.OnDeviceResponse:
OnDeviceResponse((String) msg.obj);
break;
case MTEMVEvent.OnTransactionStatus:
OnTransactionStatus((byte[]) msg.obj);
break;
case MTEMVEvent.OnDisplayMessageRequest:
OnDisplayMessageRequest((byte[]) msg.obj);
break;
case MTEMVEvent.OnUserSelectionRequest:
OnUserSelectionRequest((byte[]) msg.obj);
break;
case MTEMVEvent.OnARQCReceived:
OnARQCReceived((byte[]) msg.obj);
break;
case MTEMVEvent.OnTransactionResult:
OnTransactionResult((byte[]) msg.obj);
break;
case MTEMVEvent.OnEMVCommandResult:
OnEMVCommandResult((byte[]) msg.obj);
break;
case MTEMVEvent.OnDeviceExtendedResponse:
OnDeviceExtendedResponse((String) msg.obj);
break;
}
}
catch (Exception ex)
{
}
return true;
}
}
public void OnCardDataReceived(IMTCardData cardData)
{
txt.setText(m_SCRA.getCardLast4());
}
protected void OnDeviceStateChanged(MTConnectionState deviceState)
{
setState(deviceState);
updateDisplay();
invalidateOptionsMenu();
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert ondevice state");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
switch (deviceState)
{
case Disconnected:
if (m_connectionType == MTConnectionType.Audio)
{
restoreVolume();
}
break;
case Connected:
if (m_connectionType == MTConnectionType.Audio)
{
setVolumeToMax();
}
clearMessage();
clearMessage2();
break;
case Error:
sendToDisplay("[Device State Error]");
break;
case Connecting:
break;
case Disconnecting:
break;
}
}
protected void OnCardDataStateChanged(MTCardDataState cardDataState)
{
switch (cardDataState)
{
case DataNotReady:
sendToDisplay("[Card Data Not Ready]");
break;
case DataReady:
sendToDisplay("[Card Data Ready]");
break;
case DataError:
sendToDisplay("[Card Data Error]");
break;
}
}
protected void OnDeviceResponse(String data)
{
sendToDisplay("[Device Response]");
sendToDisplay(data);
if (m_startTransactionActionPending)
{
m_startTransactionActionPending = false;
startTransaction();
}
}
protected void OnTransactionStatus(byte[] data)
{
sendToDisplay("[Transaction Status]");
//sendToDisplay(TLVParser.getHexString(data));
}
protected void OnDisplayMessageRequest(byte[] data)
{
sendToDisplay("[Display Message Request]");
//String message = TLVParser.getTextString(data, 0);
//sendToDisplay(message);
//displayMessage(message);
}
protected void OnEMVCommandResult(byte[] data)
{
sendToDisplay("[EMV Command Result]");
//sendToDisplay(TLVParser.getHexString(data));
if (m_turnOffLEDPending)
{
m_turnOffLEDPending = false;
setLED(false);
}
}
protected void OnDeviceExtendedResponse(String data)
{
sendToDisplay("[Device Extended Response]");
sendToDisplay(data);
}
protected void OnUserSelectionRequest(byte[] data)
{
sendToDisplay("[User Selection Request]");
//sendToDisplay(TLVParser.getHexString(data));
//processSelectionRequest(data);
}
protected void OnARQCReceived(byte[] data)
{
sendToDisplay("[ARQC Received]");
/*sendToDisplay(TLVParser.getHexString(data));
List<HashMap<String, String>> parsedTLVList = TLVParser.parseEMVData(data, true, "");
if (parsedTLVList != null)
{
String deviceSNString = TLVParser.getTagValue(parsedTLVList, "DFDF25");
byte[] deviceSN = TLVParser.getByteArrayFromHexString(deviceSNString);
sendToDisplay("SN Bytes=" + deviceSNString);
sendToDisplay("SN String=" + TLVParser.getTextString(deviceSN, 2));
boolean approved = true;
if (mMainMenu != null)
{
approved = mMainMenu.findItem(R.id.menu_emv_approved).isChecked();
}
byte[] response = buildAcquirerResponse(deviceSN, approved);
setAcquirerResponse(response);
}*/
}
protected void OnTransactionResult(byte[] data)
{
sendToDisplay("[Transaction Result]");
//sendToDisplay(TLVParser.getHexString(data));
/*if (data != null)
{
if (data.length > 0)
{
boolean signatureRequired = (data[0] != 0);
int lenBatchData = data.length - 3;
if (lenBatchData > 0)
{
byte[] batchData = new byte[lenBatchData];
System.arraycopy(data, 3, batchData, 0, lenBatchData);
sendToDisplay("(Parsed Batch Data)");
List<HashMap<String, String>> parsedTLVList = TLVParser.parseEMVData(batchData, false, "");
displayParsedTLV(parsedTLVList);
String cidString = TLVParser.getTagValue(parsedTLVList, "9F27");
byte[] cidValue = TLVParser.getByteArrayFromHexString(cidString);
boolean approved = false;
if (cidValue != null)
{
if (cidValue.length > 0)
{
if ((cidValue[0] & (byte) 0x40) != 0)
{
approved = true;
}
}
}
if (approved)
{
if (signatureRequired)
{
displayMessage2("( Signature Required )");
}
else
{
displayMessage2("( No Signature Required )");
}
}
}
}
}
setLED(false);*/
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = ( Button) findViewById(R.id.btn);
txt = (TextView) findViewById(R.id.txt1);
txt1 = (TextView) findViewById(R.id.txt2);
msg = (TextView) findViewById(R.id.msgtext1);
msg2 = (TextView) findViewById(R.id.msgtext2);
Edit = (EditText) findViewById(R.id.editText);
//m_SCRA.setConnectionType(MTConnectionType.Audio);
//if (! m_SCRA.isDeviceConnected())
//{
// m_SCRA.openDevice();
//}
m_audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
m_SCRA = new MTSCRA(this, m_scraHandler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
m_connectionType = MTConnectionType.Audio;
m_SCRA.setConnectionType(MTConnectionType.Audio);
m_SCRA.setAddress(m_deviceAddress);
m_connectionState = MTConnectionState.Connected;
m_SCRA.openDevice();
}
});
}
private void sendToDisplay(final String data)
{
if (data != null)
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Edit.append(data + "\n");
}
});
}
}
private void setState(MTConnectionState deviceState)
{
m_connectionState = deviceState;
updateDisplay();
invalidateOptionsMenu();
}
private void updateDisplay()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (m_connectionState == MTConnectionState.Connected)
{
updateConnectionState(R.string.connected);
}
else if (m_connectionState == MTConnectionState.Connecting)
{
updateConnectionState(R.string.connecting);
}
else if (m_connectionState == MTConnectionState.Disconnecting)
{
updateConnectionState(R.string.disconnecting);
}
else if (m_connectionState == MTConnectionState.Disconnected)
{
updateConnectionState(R.string.disconnected);
}
}
});
}
private void updateConnectionState(final int resourceId)
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
txt1.setText(resourceId);
}
});
}
private void restoreVolume()
{
setVolume(m_audioVolume);
}
private void setVolumeToMax()
{
saveVolume();
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert volume max");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
int volume = m_audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
setVolume(volume);
}
private void setVolume(int volume)
{
m_audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
}
private void saveVolume()
{
m_audioVolume = m_audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
private void clearMessage()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText("");
}
});
}
private void clearMessage2()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg2.setText("");
}
});
}
public void startTransaction()
{
if (m_SCRA != null)
{
byte timeLimit = 0x3C;
//byte cardType = 0x02; // Chip Only
byte cardType = 0x03; // MSR + Chip
byte option = 0x00;
byte[] amount = new byte[] {0x00, 0x00, 0x00, 0x00, 0x15, 0x00};
byte transactionType = 0x00; // Purchase
byte[] cashBack = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
byte[] currencyCode = new byte[] { 0x08, 0x40};
byte reportingOption = 0x02; // All Status Changes
clearMessage();
clearMessage2();
int result = m_SCRA.startTransaction(timeLimit, cardType, option, amount, transactionType, cashBack, currencyCode, reportingOption);
sendToDisplay("[Start Transaction] (Result=" + result + ")");
}
}
public void setLED(boolean on)
{
if (m_SCRA != null)
{
if (on)
{
m_SCRA.sendCommandToDevice(MTDeviceConstants.SCRA_DEVICE_COMMAND_STRING_SET_LED_ON);
}
else
{
m_SCRA.sendCommandToDevice(MTDeviceConstants.SCRA_DEVICE_COMMAND_STRING_SET_LED_OFF);
}
}
} }
I was facing the same issue. It turned out that I forgot audio recording runtime permission.
private void checkRecordPermission() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO},
123);
}
}

Is there a different xml view with "extends Fragment"? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get my class XML screen but with no success,
Until now I was able to create activity, and use startActivity(activity.class)
but now there is a problem.
At the main Java file of my app i call FTDI class :
public void onFTDIClick(View view){
startActivity(new Intent(this,FTDI.class));
}
The FTDI class:
package com.application.i;
import java.util.ArrayList;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
public class FTDI extends Fragment{
static Context DeviceUARTContext;
D2xxManager ftdid2xx;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
EditText writeText;
Spinner baudSpinner;;
Spinner stopSpinner;
Spinner dataSpinner;
Spinner paritySpinner;
Spinner flowSpinner;
Spinner portSpinner;
ArrayAdapter<CharSequence> portAdapter;
Button configButton;
Button openButton;
Button readEnButton;
Button writeButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
ArrayList<CharSequence> portNumberList;
public static final int readLength = 512;
public int readcount = 0;
public int iavailable = 0;
byte[] readData;
char[] readDataToText;
public boolean bReadThreadGoing = false;
public readThread read_thread;
boolean uart_configured = false;
// Empty Constructor
public FTDI()
{
}
/* Constructor */
public FTDI(Context parentContext , D2xxManager ftdid2xxContext)
{
DeviceUARTContext = parentContext;
ftdid2xx = ftdid2xxContext;
}
public int getShownIndex() {
return getArguments().getInt("index", 5);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.ftdisub, container, false);
readData = new byte[readLength];
readDataToText = new char[readLength];
readText = (EditText) view.findViewById(R.id.ReadValues);
readText.setInputType(0);
/* by default it is 9600 */
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
createDeviceList();
}
#Override
public void onStop()
{
disconnectFunction();
super.onStop();
}
public void notifyUSBDeviceAttach()
{
createDeviceList();
}
public void notifyUSBDeviceDetach()
{
disconnectFunction();
}
public void createDeviceList()
{
int tempDevCount = ftdid2xx.createDeviceInfoList(DeviceUARTContext);
if (tempDevCount > 0)
{
if( DevCount != tempDevCount )
{
DevCount = tempDevCount;
updatePortNumberSelector();
}
}
else
{
DevCount = -1;
currentIndex = -1;
}
}
public void disconnectFunction()
{
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if(ftDev != null)
{
synchronized(ftDev)
{
if( true == ftDev.isOpen())
{
ftDev.close();
}
}
}
}
public void connectFunction()
{
int tmpProtNumber = openIndex + 1;
if( currentIndex != openIndex )
{
if(null == ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
else
{
synchronized(ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
}
uart_configured = false;
}
else
{
Toast.makeText(DeviceUARTContext,"Device port " + tmpProtNumber + " is already opened",Toast.LENGTH_LONG).show();
return;
}
if(ftDev == null)
{
Toast.makeText(DeviceUARTContext,"open device port("+tmpProtNumber+") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen())
{
currentIndex = openIndex;
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if(false == bReadThreadGoing)
{
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
}
else
{
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
//Toast.makeText(DeviceUARTContext, "Need to get permission!", Toast.LENGTH_SHORT).show();
}
}
public void updatePortNumberSelector()
{
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl)
{
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
// configure our port
// reset to UART mode for 232 devices
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
switch (dataBits) {
case 7:
dataBits = D2xxManager.FT_DATA_BITS_7;
break;
case 8:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
default:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
}
switch (stopBits) {
case 1:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
case 2:
stopBits = D2xxManager.FT_STOP_BITS_2;
break;
default:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
}
switch (parity) {
case 0:
parity = D2xxManager.FT_PARITY_NONE;
break;
case 1:
parity = D2xxManager.FT_PARITY_ODD;
break;
case 2:
parity = D2xxManager.FT_PARITY_EVEN;
break;
case 3:
parity = D2xxManager.FT_PARITY_MARK;
break;
case 4:
parity = D2xxManager.FT_PARITY_SPACE;
break;
default:
parity = D2xxManager.FT_PARITY_NONE;
break;
}
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
short flowCtrlSetting;
switch (flowControl) {
case 0:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
case 1:
flowCtrlSetting = D2xxManager.FT_FLOW_RTS_CTS;
break;
case 2:
flowCtrlSetting = D2xxManager.FT_FLOW_DTR_DSR;
break;
case 3:
flowCtrlSetting = D2xxManager.FT_FLOW_XON_XOFF;
break;
default:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
}
// TODO : flow ctrl: XOFF/XOM
// TODO : flow ctrl: XOFF/XOM
ftDev.setFlowControl(flowCtrlSetting, (byte) 0x0b, (byte) 0x0d);
uart_configured = true;
Toast.makeText(DeviceUARTContext, "Config done", Toast.LENGTH_SHORT).show();
}
public void EnableRead (){
iEnableReadFlag = (iEnableReadFlag + 1)%2;
if(iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
}
else{
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
}
}
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(iavailable > 0)
{
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread
{
Handler mHandler;
readThread(Handler h){
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run()
{
int i;
while(true == bReadThreadGoing)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
synchronized(ftDev)
{
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if(iavailable > readLength){
iavailable = readLength;
}
ftDev.read(readData, iavailable);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if(DevCount > 0)
{
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
The XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="#+id/PITCHING"
android:textSize="15sp" />
<TextView android:text = "Read Bytes"
android:textStyle="bold"
android:gravity="center"
android:id="#+id/ReadBytes"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"
/>
<EditText
android:id="#+id/ReadValues"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:layout_weight="4"
android:background="#708070"
android:focusableInTouchMode="false"
android:gravity="left|center_vertical"
/>
<Button android:id="#+id/readEnButton"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_margin="10dp"
android:gravity="center"
android:scaleType="centerInside"
android:layout_weight="1"
android:text="Read Enabled"
/>
</LinearLayout>
At the manifest file:
<activity
android:name=".FTDI"
android:label="Reading Circuit Data"
android:theme="#android:style/Theme.Holo" >
</activity>
Until now i used , before working with Frgment:
package com.application.i;
import android.app.Activity;
import android.os.Bundle;
public class FTDI extends Activity
{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.ftdisub);
}
}
As i press the button on my main screen it stuck, the hole application finished with error.
Edit:
My problem is that I need a UI to check this class and then to put it as a Service, I know how to Service it, without user interface.
I changed the code to be an activity and it looks :
package com.application.i;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
public class FTDI extends Activity{
static Context DeviceUARTContext;
D2xxManager ftdid2xx;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
EditText writeText;
Spinner baudSpinner;;
Spinner stopSpinner;
Spinner dataSpinner;
Spinner paritySpinner;
Spinner flowSpinner;
Spinner portSpinner;
ArrayAdapter<CharSequence> portAdapter;
Button configButton;
Button openButton;
Button readEnButton;
Button writeButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
ArrayList<CharSequence> portNumberList;
public static final int readLength = 512;
public int readcount = 0;
public int iavailable = 0;
byte[] readData;
char[] readDataToText;
public boolean bReadThreadGoing = false;
public readThread read_thread;
boolean uart_configured = false;
// Empty Constructor
public FTDI()
{
}
/* Constructor */
public FTDI(Context parentContext , D2xxManager ftdid2xxContext)
{
DeviceUARTContext = parentContext;
ftdid2xx = ftdid2xxContext;
}
// public int getShownIndex() {
// return getArguments().getInt("index", 5);
// }
// #Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// if (container == null) {
// return null;
// }
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.ftdisub);
// View view = inflater.inflate(R.layout.ftdisub, container, false);
readData = new byte[readLength];
readDataToText = new char[readLength];
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
/* by default it is 9600 */
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
}
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
//
// }
#Override
public void onStart() {
super.onStart();
createDeviceList();
}
#Override
public void onStop()
{
disconnectFunction();
super.onStop();
}
public void notifyUSBDeviceAttach()
{
createDeviceList();
}
public void notifyUSBDeviceDetach()
{
disconnectFunction();
}
public void createDeviceList()
{
int tempDevCount = ftdid2xx.createDeviceInfoList(DeviceUARTContext);
if (tempDevCount > 0)
{
if( DevCount != tempDevCount )
{
DevCount = tempDevCount;
updatePortNumberSelector();
}
}
else
{
DevCount = -1;
currentIndex = -1;
}
}
public void disconnectFunction()
{
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if(ftDev != null)
{
synchronized(ftDev)
{
if( true == ftDev.isOpen())
{
ftDev.close();
}
}
}
}
public void connectFunction()
{
int tmpProtNumber = openIndex + 1;
if( currentIndex != openIndex )
{
if(null == ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
else
{
synchronized(ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
}
uart_configured = false;
}
else
{
Toast.makeText(DeviceUARTContext,"Device port " + tmpProtNumber + " is already opened",Toast.LENGTH_LONG).show();
return;
}
if(ftDev == null)
{
Toast.makeText(DeviceUARTContext,"open device port("+tmpProtNumber+") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen())
{
currentIndex = openIndex;
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if(false == bReadThreadGoing)
{
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
}
else
{
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
//Toast.makeText(DeviceUARTContext, "Need to get permission!", Toast.LENGTH_SHORT).show();
}
}
public void updatePortNumberSelector()
{
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl)
{
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
// configure our port
// reset to UART mode for 232 devices
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
switch (dataBits) {
case 7:
dataBits = D2xxManager.FT_DATA_BITS_7;
break;
case 8:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
default:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
}
switch (stopBits) {
case 1:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
case 2:
stopBits = D2xxManager.FT_STOP_BITS_2;
break;
default:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
}
switch (parity) {
case 0:
parity = D2xxManager.FT_PARITY_NONE;
break;
case 1:
parity = D2xxManager.FT_PARITY_ODD;
break;
case 2:
parity = D2xxManager.FT_PARITY_EVEN;
break;
case 3:
parity = D2xxManager.FT_PARITY_MARK;
break;
case 4:
parity = D2xxManager.FT_PARITY_SPACE;
break;
default:
parity = D2xxManager.FT_PARITY_NONE;
break;
}
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
short flowCtrlSetting;
switch (flowControl) {
case 0:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
case 1:
flowCtrlSetting = D2xxManager.FT_FLOW_RTS_CTS;
break;
case 2:
flowCtrlSetting = D2xxManager.FT_FLOW_DTR_DSR;
break;
case 3:
flowCtrlSetting = D2xxManager.FT_FLOW_XON_XOFF;
break;
default:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
}
// TODO : flow ctrl: XOFF/XOM
// TODO : flow ctrl: XOFF/XOM
ftDev.setFlowControl(flowCtrlSetting, (byte) 0x0b, (byte) 0x0d);
uart_configured = true;
Toast.makeText(DeviceUARTContext, "Config done", Toast.LENGTH_SHORT).show();
}
public void EnableRead (){
iEnableReadFlag = (iEnableReadFlag + 1)%2;
if(iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
}
else{
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
}
}
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(iavailable > 0)
{
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread
{
Handler mHandler;
readThread(Handler h){
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run()
{
int i;
while(true == bReadThreadGoing)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
synchronized(ftDev)
{
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if(iavailable > readLength){
iavailable = readLength;
}
ftDev.read(readData, iavailable);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if(DevCount > 0)
{
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
Any suggestions?
To attach a fragment to an Activity you have two ways:
1) Declare the fragment inside the activity's layout file.
2) Programmatically add the fragment to an existing ViewGroup.
In my opinion you can use the second way, so basically you need a ViewGroup in the activity where to put the Fragment; something like a Layout can be good for that.
When you have the place where to insert the Fragment you can insert it using the LayoutInfleter.
Fragment fragment = new YourFragment();
getLayoutInflater.inflate(R.id.youLayoutContainer, fragment, false);
Take a look at the page below for more informations:
http://developer.android.com/guide/components/fragments.html

Pass a variable from public void OnCreate

I wanted to know how can I pass a variable from private void to OnCreate?
public final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
int k=Integer.parseInt(readMessage.replaceAll("[\\D]",""));
mConversationArrayAdapter.add(readMessage);
Toast.makeText(getApplicationContext(),"ciao"+k ,Toast.LENGTH_SHORT).show();
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
This is OnCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mvc = (Button) findViewById(R.id.button1);
mvc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
public void run() {
while (progressStatus < 1000) {
Random r = new Random();
int i1 = r.nextInt(1000);
if (i1 > progressStatus){
progressStatus = i1;
}
else {
progressStatus = progressStatus;
}
// Update the progress bar and display the current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds. Just to display the progress slowly
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
res = (Button) findViewById(R.id.button2);
res.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressBar.setProgress(0);
progressStatus=0;
}
});
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
I pass the variable k, is there a method? or I have to go to a public int? I do not know how to solve. Thank you in advance!
Umm, why not make k a Global Variable?
Add int k inside starting of your class
For example :
...
public class MainActivity extends Activity {
int k;
//onCreate and other methods
}
...
Change
int k = =Integer.parseInt (readMessage.replaceAll.replaceAll("[\\D]",""));
to
k = =Integer.parseInt(readMessage.replaceAll.replaceAll("[\\D]",""));
as you've already made k an integer.
Then you can use k anywhere in your class

Categories

Resources