android scan barcode from camera with google barcode api (what is missing?) - java

in my app dependencies i have
compile 'com.google.android.gms:play-services:11.0.4'
in manifest file i have
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
this is my activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cameratest.test.hasan.com.barcodetest.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:text="Name"
android:layout_marginTop="107dp"
android:layout_marginEnd="39dp" />
<RelativeLayout
android:id="#+id/cameraHolder"
android:layout_width="176dp"
android:layout_height="144dp"
android:layout_marginEnd="75dp"
android:layout_marginTop="74dp"
android:keepScreenOn="true"></RelativeLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
CameraSurface cameraSurface;
RelativeLayout relativeLayout;
EditText etBarkod ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etBarkod = (EditText)findViewById(R.id.editText);
etBarkod.setOnEditorActionListener(new BarkodEditorActionListener(this.getBaseContext()));
relativeLayout = (RelativeLayout)findViewById(R.id.cameraHolder);
relativeLayout.setOnTouchListener(new MovingViewListener());
cameraSurface = new CameraSurface(this.getBaseContext());
cameraSurface.setBarkodEditText(etBarkod);
relativeLayout.addView(cameraSurface);
}
}
and CameraSurface.java class is
public class CameraSurface extends SurfaceView implements SurfaceHolder.Callback {
Context context;
Camera mCamera;
CameraSource cameraSource;
SurfaceHolder msurfaceHolder;
EditText etBarkod;
public CameraSurface(Context context) {
super(context);
super.setKeepScreenOn(true);
this.context = context;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
super.setLayoutParams(params);
msurfaceHolder = this.getHolder();
msurfaceHolder.addCallback(this);
msurfaceHolder.setKeepScreenOn(true);
msurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
attachBarcodeDetector();
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
try {
mCamera.setPreviewDisplay(msurfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
Camera.Parameters param;
param = mCamera.getParameters();
param.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
param.setPreviewFrameRate(0);
param.setPreviewSize(176, 144);
mCamera.setParameters(param);
try {
//noinspection MissingPermission
cameraSource.start(msurfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
}
private void attachBarcodeDetector(){
BarcodeDetector barcodeDetector =
new BarcodeDetector.Builder(context)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource
.Builder(context, barcodeDetector)
.setRequestedPreviewSize(176, 144)
.setAutoFocusEnabled(true)
.build();
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final EditText barkod= etBarkod;
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barkod.post(new Runnable() { // Use the post method of the TextView
public void run() {
barkod.setText( // Update the TextView
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
public EditText setBarkodEditText(EditText editText){
return this.etBarkod = editText;
}
}
Camera works fine , focuses fine supports defined preview size,but barcode detector does not detect barcodes and because of this edittext value does not change .
Note:this code was working perfectly and i dont really know what i have changed but after that it is not working anymore.
I am trying to understand what is wrong with this code but i cannot figure it out.
So I need your help.
thanks in advance.

Check this may help you:
private void scanBarcode() {
mCameraView.setZOrderMediaOverlay(true);
mHolder = mCameraView.getHolder();
mBarcode = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.ALL_FORMATS | Barcode.EAN_13 | Barcode.EAN_8 | Barcode.UPC_A | Barcode.UPC_E | Barcode.CODE_39 | Barcode.CODE_93 |
Barcode.CODE_128 | Barcode.ITF | Barcode.CODABAR | Barcode.ISBN | Barcode.QR_CODE | Barcode.DATA_MATRIX | Barcode.PDF417 | Barcode.AZTEC).build();
if (!mBarcode.isOperational()) {
Toast.makeText(getApplicationContext(), "Sorry,Couldn't setup the detector", Toast.LENGTH_LONG).show();
this.finish();
}
mCameraSource = new CameraSource.Builder(this, mBarcode)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(15.0f)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(1600, 1024)
.build();
mCameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ContextCompat.checkSelfPermission(ScanActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
mCameraSource.start(mCameraView.getHolder());
} else {
ActivityCompat.requestPermissions(ScanActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCameraSource.stop();
}
});
mBarcode.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() > 0) {
barkod.setText(barcodes.valueAt(0));
}
}
});
}

Please Do Querying the Detector Operational Status using method isOperational ()
if (!detector.isOperational()) {
}

Related

Below is my code but there is some error when i open camera appear and immediately disappear. How to hold on the camera view for a bit longer.?

1.MainActivity.java file
I think the error got at this line
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop()
I'm trying to open the camera and display using SurfaceView. This delays the loading of the activity for a really long time. So I'm wondering what are the best practices of opening the camera.
package com.example.software2.ocrhy;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private TextToSpeech textToSpeech;
private String stringResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
}
private void textRecognizer(){
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.build();
surfaceView = findViewById(R.id.surfaceView);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#SuppressLint("MissingPermission")
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<sparseArray.size(); ++i){
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() !=null){
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> {
stringResult = stringText;
resultObtained();
});
}
});
}
private void resultObtained(){
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void buttonStart(View view){
setContentView(R.layout.surface);
textRecognizer();
}
}
I got full code from this link
javafile
error got in camera activity
According to your source code, your camera starts reading the text immediately. If you want to first see your text on your camera and only then start reading it we can break down it to following steps:
Open your camera
Navigate to specific text
Finally when you see via your camera the text what you want to read it
I suggest you to do small modifications on your code
Add Capture button on your surfaceview.xml (for example in a code below)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="308dp"
android:layout_height="503dp"
android:layout_marginStart="64dp"
android:layout_marginTop="32dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:id="#+id/capture"
android:layout_marginHorizontal="32dp"
android:layout_marginBottom="32dp"
android:text="Capture"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Move out text processing to separate function
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<sparseArray.size(); ++i){
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() !=null){
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
Capture your text on capture button click
public void buttonStart(View view){
setContentView(R.layout.surfaceview);
Button capture = findViewById(R.id.capture);
capture.setOnClickListener(v -> capture());
textRecognizer();
}
As a result whole MainActivity
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private TextToSpeech textToSpeech;
private String stringResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
}
private void textRecognizer() {
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i<sparseArray.size(); ++i){
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() !=null){
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained(){
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void buttonStart(View view){
setContentView(R.layout.surfaceview);
Button capture = findViewById(R.id.capture);
capture.setOnClickListener(v -> capture());
textRecognizer();
}
}

Send button crash the application

This application is to send a text message through Wi-Fi direct Api. i used build-in API for that. code is running, discovering the devices also but problem while sending message when press send button
I've tried this solution also:
App crash while sending data over a socket using WifiP2p connection
but still application crash whenever press send button.
MainActivity:
public class MainActivity extends AppCompatActivity{
Switch switch1;
Button btnOnOff, btnSend, btnDiscover;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager.Channel mChannel;
WifiP2pManager mManager;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List <WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ = 1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialWork();
exqListner();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch(msg.what){
case MESSAGE_READ:
byte[] readbuff = (byte[]) msg.obj;
String tempMsg = new String(readbuff, 0, msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void exqListner() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
}else{
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText("Discovering started");
}
#Override
public void onFailure(int reason) {
connectionStatus.setText("Discovering starting failed");
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = writeMsg.getText().toString();
byte[] bytes =msg.getBytes();
btnSend.setVisibility(View.INVISIBLE);
if(connectionStatus.equals("Host")) {
serverClass.writeData(bytes);
} else {
clientClass.writeData(bytes);
}
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
final WifiP2pDevice device = deviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(), "Connected to "+device.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void initialWork() {
btnDiscover = (Button) findViewById(R.id.discover);
btnOnOff = (Button) findViewById(R.id.onOff);
btnSend = (Button) findViewById(R.id.sendButton);
listView = (ListView) findViewById(R.id.peerListView);
read_msg_box = (TextView) findViewById(R.id.readmsg);
connectionStatus = (TextView) findViewById(R.id.connectionStatus);
writeMsg = (EditText) findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(),null);
mReceiver = new WifiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers)){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for(WifiP2pDevice device : peerList.getDeviceList()){
deviceNameArray[index] = device.deviceName;
deviceArray[index] = device;
index++;
}
ArrayAdapter <String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, deviceNameArray);
listView.setAdapter(adapter);
}
if (peers.size() == 0){
Toast.makeText(getApplicationContext(), "No Device Found",Toast.LENGTH_SHORT).show();
return;
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;
if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
}
else if (wifiP2pInfo.groupFormed){
connectionStatus.setText("Client");
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
public class ServerClass extends AsyncTask<String, Integer, Boolean> {
Socket socket;
ServerSocket serverSocket;
InputStream inputStream;
OutputStream outputStream;
#Override
protected Boolean doInBackground(String... strings) {
boolean result = true;
try {
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
} catch (IOException e) {
result = false;
e.printStackTrace();
}
return result;
}
public void writeData(final byte[] bytes) {
new Thread(new Runnable() {
#Override
public void run() {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
btnSend.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Boolean result) {
if(result) {
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new Runnable(){
public void run() {
byte[] buffer = new byte[1024];
int x;
while (socket!=null) {
try {
x = inputStream.read(buffer);
if(x>0) {
handler.obtainMessage(MESSAGE_READ,x,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
btnSend.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getApplicationContext(),"could not create sockets",Toast.LENGTH_SHORT).show();
//restart socket assignment process
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt){
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (socket != null){
try {
bytes = inputStream.read(buffer);
if (bytes > 0){
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends AsyncTask<String, Integer, Boolean>{
Socket socket;
String hostAdd;
InputStream inputStream;
OutputStream outputStream;
public ClientClass(InetAddress hostAddress) {
hostAdd = hostAddress.getHostAddress();
socket = new Socket();
}
#Override
protected Boolean doInBackground(String... strings) {
boolean result = false;
try {
socket.connect(new InetSocketAddress(hostAdd, 8888), 5000);
result = true;
return result;
} catch (IOException e) {
e.printStackTrace();
result = false;
return result;
}
}
public void writeData(final byte[] bytes) {
new Thread(new Runnable() {
#Override
public void run() {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
btnSend.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Boolean result) {
if(result) {
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new Runnable(){
public void run() {
byte[] buffer = new byte[1024];
int x;
while (socket!=null) {
try {
x = inputStream.read(buffer);
if(x>0) {
handler.obtainMessage(MESSAGE_READ,x,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
btnSend.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getApplicationContext(),"could not create sockets",Toast.LENGTH_SHORT).show();
}
}
}
}
Broadcast Receiver class:
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WifiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity){
this.mActivity = mActivity;
this.mChannel = mChannel;
this.mManager = mManager;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"Wifi is on",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Wifi is off", Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
if (mManager != null){
mManager.requestPeers(mChannel, mActivity.peerListListener);
}
}else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
if(mManager == null){
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel, mActivity.connectionInfoListener);
}
else{
mActivity.connectionStatus.setText("Device Disconnected");
}
}else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
}
}
}
and the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"enter code here
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="#+id/onOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="25dp"
android:layout_marginTop="55dp"
android:text="Wifi On"/>
<Button
android:id="#+id/discover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/onOff"
android:layout_alignBottom="#+id/onOff"
android:layout_centerHorizontal="true"
android:text="Discover" />
<ListView
android:id="#+id/peerListView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/onOff"
android:layout_marginTop="25dp"
android:background="#android:color/holo_blue_light">
</ListView>
<TextView
android:id="#+id/readmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/peerListView"
android:layout_marginTop="31dp"
android:text="Message"
android:textAlignment="center"
android:textSize="20dp"
android:textStyle="italic"/>
<EditText
android:id="#+id/writeMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:ems="10"
android:inputType="textPersonName"
android:layout_toStartOf="#id/sendButton"/>
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="SEND"/>
<TextView
android:id="#+id/connectionStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:textAlignment="center"
android:text="Connection Status"
android:textColor="#color/design_default_color_primary_dark"
android:textSize="15dp"
android:textStyle="italic"/>
</RelativeLayout>
After pressing send button, message should be sent but it crash whole application. please help.enter code here

It is Possible to send Image from SurfaceView to Server?

I want make the camera always send picture when captured from SurfaceView.
This is my Code for SurfaceView.
public class CustomCamera extends AppCompatActivity implements SurfaceHolder.Callback,Camera.PictureCallback, Camera.ShutterCallback {
Camera camera;
SurfaceView mPreview;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_camera);
mPreview = (SurfaceView) findViewById(R.id.preview);
mPreview.getHolder().addCallback(this);
mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
camera = Camera.open();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
AutomatedPicture();
count++;
}
};
final Timer autoCapture = new Timer();
autoCapture.schedule(new TimerTask() {
#Override
public void run() {
if (count != 3) {
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, false);
handler.post(runnable);
}else {
autoCapture.cancel();
finish();
Toast.makeText(getApplicationContext(),"Verify failed",Toast.LENGTH_LONG).show();
camera.release();
}
}
},500,5000);
}
#Override
protected void onPause() {
super.onPause();
camera.stopPreview();
}
#Override
protected void onDestroy() {
super.onDestroy();
camera.release();
Log.d("Camera","Destroy");
}
public void onCancelClick(View v){
camera.release();
finish();
}
public void onSnapClick(View v){
camera.takePicture(this, null, null, this);
}
public void AutomatedPicture(){
camera.takePicture(this,null,null,this);
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try{FileOutputStream out = openFileOutput("picture"+count+".jpg", Activity.MODE_PRIVATE);
out.write(data);
out.flush();
out.close(); } catch (FileNotFoundException e) {
Log.e("Error",e.getMessage());
}catch (IOException e){
Log.e("Error",e.getMessage());
}
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
camera.setPreviewDisplay(mPreview.getHolder());
} catch (IOException e) {
Log.e("Error",e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters params = camera.getParameters();
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Camera.Size selected = sizes.get(0);
params.setPreviewSize(selected.width,selected.height);
camera.setParameters(params);
camera.setDisplayOrientation(90);
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("PREVIew","Surface Destroyed");
}
#Override
public void onShutter() {
AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
and this is my XML.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.simasjiwa.sijiku.CustomCamera">
<SurfaceView
android:id="#+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="100dip"
android:layout_alignParentBottom="true"
android:gravity="center_vertical"
android:background="#A000">>
<Button
android:id="#+id/button2"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:onClick="onCancelClick"
android:text="Cancel" />
<Button
android:id="#+id/button3"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:onClick="onSnapClick"
android:text="Snap Photo" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
And my question is it is possible to make the surface View send data to server when the picture captured every 5 second?
If possible what method must i use or function?
Thank You before.
If you are extending SurfaceView, use this method inside your class.
public Bitmap getBitmap() {
setDrawingCacheEnabled(true);
buildDrawingCache(true);
final Bitmap bitmap = Bitmap.createBitmap(getDrawingCache());
setDrawingCacheEnabled(false);
destroyDrawingCache();
return bitmap;
}
Without extending, it would look like this:
public Bitmap getBitmap(SurfaceView surfaceView) {
surfaceView.setDrawingCacheEnabled(true);
surfaceView.buildDrawingCache(true);
final Bitmap bitmap = Bitmap.createBitmap(surfaceView.getDrawingCache());
surfaceView.setDrawingCacheEnabled(false);
surfaceView.destroyDrawingCache();
return bitmap;
}
I haven't tested it without extending SurfaceView.

Not Showing camera on button Click in emulator

I'am trying to create an application whose purpose is to take picture on a button click.i am using an emulator to run the app. but the problem now is, when I click on the button nothing happens.
if anyone knows the solution please help.
MAINACTIVITY.JAVA
public class MainActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
Button b1;
Camera.PictureCallback rawCallback;
Camera.ShutterCallback shutterCallback;
Camera.PictureCallback jpegCallback;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takepicture();
}
});
}
public void takepicture() {
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
jpegCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Toast.makeText(getApplicationContext(), "Picture Saved", Toast.LENGTH_LONG).show();
refreshCamera();
}
};
}
public void captureImage(View v) throws IOException {
camera.takePicture(null, null, jpegCallback);
}
public void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
return;
}
try {
camera.stopPreview();
} catch (Exception e) {
}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
} catch (RuntimeException e) {
System.err.println(e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
param.setPreviewSize(352, 288);
camera.setParameters(param);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
System.err.println(e);
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
}
activity_main.xml
<RelativeLayout 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: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.test.MainActivity" >
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera"
android:id="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="86dp" />
</RelativeLayout>
MANIFEST
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

Extending my Android Radio Application

Recently, I uploaded simple Radio Application to the Google Play Store. And it has kinda a lot of downloaders. But it was really simple and I want to extend that Radio App to the next level. What it has for now is only ONE radio station to choose. No next, no previous buttons to choose from more Radio Stations. What I really want to do is to extend it so the user can listen for more Radio Stations(not one, but about 6 more or so). So maybe I need to add Previous and Next buttons to the app so the user can actually do that. But there is a problem - I don't know how to do this.
This is MainActivity.java class :
public class MainActivity extends Activity {
static String radioTitle = "RadioLink1";
static String radioStreamURL = "http://108.61.73.117:8124";
Button playButton;
Button pauseButton;
Button stopButton;
TextView statusTextView, bufferValueTextView;
NotificationCompat.Builder notifyBuilder;
private SeekBar volumeSeekbar;
private AudioManager audioManager = null;
private RadioUpdateReceiver radioUpdateReceiver;
private RadioService radioServiceBinder;
// Notification
private static final int NOTIFY_ME_ID = 12345;
private NotificationManager notifyMgr = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView titleTextView = (TextView) this
.findViewById(R.id.titleTextView);
titleTextView.setText(radioTitle);
playButton = (Button) this.findViewById(R.id.PlayButton);
pauseButton = (Button) this.findViewById(R.id.PauseButton);
stopButton = (Button) this.findViewById(R.id.StopButton);
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
pauseButton.setVisibility(View.INVISIBLE);
initControls();
statusTextView = (TextView) this
.findViewById(R.id.StatusDisplayTextView);
notifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
setFont();
// Bind to the service
Intent bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, RadioService.class));
}
private void initControls() {
try {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0,
int progress, boolean arg2) {
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC, progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void setFont() {
// Font path
String fontPath = "fonts/Christmas Card.ttf";
// text view label
TextView txtGhost = (TextView) findViewById(R.id.titleTextView);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtGhost.setTypeface(tf);
}
public void onClickPlayButton(View view) {
radioServiceBinder.play();
}
public void onClickPauseButton(View view) {
radioServiceBinder.pause();
}
public void onClickStopButton(View view) {
radioServiceBinder.stop();
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
}
#Override
protected void onResume() {
super.onResume();
/* Register for receiving broadcast messages */
if (radioUpdateReceiver == null)
radioUpdateReceiver = new RadioUpdateReceiver();
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_CREATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_DESTROYED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_STARTED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_PREPARED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_PLAYING));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_PAUSED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_STOPPED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_COMPLETED));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_ERROR));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_BUFFERING_START));
registerReceiver(radioUpdateReceiver, new IntentFilter(
RadioService.MODE_BUFFERING_END));
}
/* Receive Broadcast Messages from RadioService */
private class RadioUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RadioService.MODE_CREATED)) {
showNotification();
} else if (intent.getAction().equals(RadioService.MODE_DESTROYED)) {
clearNotification();
} else if (intent.getAction().equals(RadioService.MODE_STARTED)) {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Buffering...");
} else if (intent.getAction().equals(RadioService.MODE_PREPARED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Rady");
} else if (intent.getAction().equals(
RadioService.MODE_BUFFERING_START)) {
updateStatus("Buffering...");
} else if (intent.getAction().equals(
RadioService.MODE_BUFFERING_END)) {
updateStatus("Playing");
} else if (intent.getAction().equals(RadioService.MODE_PLAYING)) {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
playButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
showNotification();
updateStatus("Playing");
} else if (intent.getAction().equals(RadioService.MODE_PAUSED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Paused");
} else if (intent.getAction().equals(RadioService.MODE_STOPPED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
clearNotification();
} else if (intent.getAction().equals(RadioService.MODE_COMPLETED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
} else if (intent.getAction().equals(RadioService.MODE_ERROR)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Error");
}
}
}
public void updateStatus(String status) {
try {
if (notifyBuilder != null && notifyMgr != null) {
notifyBuilder.setContentText(status).setWhen(0);
notifyMgr.notify(NOTIFY_ME_ID, notifyBuilder.build());
}
statusTextView.setText(status);
} catch (Exception e) {
e.printStackTrace();
}
}
public void showNotification() {
notifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(radioTitle).setContentText("");
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
notifyBuilder.setContentIntent(resultPendingIntent);
notifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(NOTIFY_ME_ID, notifyBuilder.build());
}
public void clearNotification() {
notifyMgr.cancel(NOTIFY_ME_ID);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
// Handles the connection between the service and activity
private ServiceConnection radioConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
radioServiceBinder = ((RadioService.RadioBinder) service)
.getService();
}
public void onServiceDisconnected(ComponentName className) {
radioServiceBinder = null;
}
};
}
and RadioService.java class:
public class RadioService extends Service implements OnErrorListener, OnCompletionListener, OnPreparedListener, OnInfoListener {
private MediaPlayer mediaPlayer;
private String radioStreamURL = MainActivity.radioStreamURL;
public static final String MODE_CREATED = "CREATED";
public static final String MODE_DESTROYED = "DESTROYED";
public static final String MODE_PREPARED = "PREPARED";
public static final String MODE_STARTED = "STARTED";
public static final String MODE_PLAYING = "PLAYING";
public static final String MODE_PAUSED = "PAUSED";
public static final String MODE_STOPPED = "STOPPED";
public static final String MODE_COMPLETED = "COMPLETED";
public static final String MODE_ERROR = "ERROR";
public static final String MODE_BUFFERING_START = "BUFFERING_START";
public static final String MODE_BUFFERING_END = "BUFFERING_END";
private boolean isPrepared = false;
private final IBinder binder = new RadioBinder();
#Override
public void onCreate() {
/* Create MediaPlayer when it starts for first time */
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnInfoListener(this);
sendBroadcast(new Intent(MODE_CREATED));
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.reset();
isPrepared = false;
sendBroadcast(new Intent(MODE_DESTROYED));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sendBroadcast(new Intent(MODE_STARTED));
/* Starts playback at first time or resumes if it is restarted */
if(mediaPlayer.isPlaying())
sendBroadcast(new Intent(MODE_PLAYING));
else if(isPrepared) {
sendBroadcast(new Intent(MODE_PAUSED));
}
else
prepare();
return Service.START_STICKY;
}
#Override
public void onPrepared(MediaPlayer _mediaPlayer) {
/* If radio is prepared then start playback */
sendBroadcast(new Intent(MODE_PREPARED));
isPrepared = true;
play();
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
/* When no stream found then complete the playback */
mediaPlayer.stop();
mediaPlayer.reset();
isPrepared = false;
sendBroadcast(new Intent(MODE_COMPLETED));
}
public void prepare() {
/* Prepare Async Task - starts buffering */
try {
mediaPlayer.setDataSource(radioStreamURL);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void play() {
if(isPrepared) {
mediaPlayer.start();
System.out.println("RadioService: play");
sendBroadcast(new Intent(MODE_PLAYING));
}
else
{
sendBroadcast(new Intent(MODE_STARTED));
prepare();
}
}
public void pause() {
mediaPlayer.pause();
System.out.println("RadioService: pause");
sendBroadcast(new Intent(MODE_PAUSED));
}
public void stop() {
mediaPlayer.stop();
mediaPlayer.reset();
isPrepared = false;
System.out.println("RadioService: stop");
sendBroadcast(new Intent(MODE_STOPPED));
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
/* Check when buffering is started or ended */
if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
sendBroadcast(new Intent(MODE_BUFFERING_START));
}
else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
sendBroadcast(new Intent(MODE_BUFFERING_END));
}
return false;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
sendBroadcast(new Intent(MODE_ERROR));
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.v("ERROR","MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.v("ERROR","MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.v("ERROR","MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
/* Allowing activity to access all methods of RadioService */
public class RadioBinder extends Binder {
RadioService getService() {
return RadioService.this;
}
}
}
And this layout:
<RelativeLayout 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:background="#4a4a4a"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/player_header_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:background="#color/bgcolor"
android:gravity="center"
android:text="Classic Christmas Radio"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#c0413b"
android:textSize="40sp" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_marginBottom="120dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="110dp"
android:src="#drawable/cover" />
<TextView
android:id="#+id/StatusDisplayTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/PauseButton"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignRight="#+id/imageView1"
android:gravity="center"
android:text="Unknown" />
<Button
android:id="#+id/PauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/StatusDisplayTextView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0.0dip"
android:background="#drawable/btn_pause"
android:onClick="onClickPauseButton" />
<Button
android:id="#+id/PlayButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/StatusDisplayTextView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0.0dip"
android:background="#drawable/btn_play"
android:onClick="onClickPlayButton" />
<Button
android:id="#+id/StopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#id/StatusDisplayTextView"
android:layout_marginBottom="0.0dip"
android:background="#drawable/btn_stop"
android:onClick="onClickStopButton" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/PauseButton"
android:background="#drawable/btn_previous" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/button1"
android:background="#drawable/btn_next" />
</RelativeLayout>
I actually didn't write all the code and that's why I can't get my head straight to the problem solution. I just extended given code for my needs but now I don't really now how to implement Previous and Next buttons to navigate through different Radio Stations. What I want from you guys is to maybe give me some ideas or just set me on the road how can I add this functionality to this app. How can I get more than one stream (in this case from SHOUTcast) and add this navigation through them. I hope I didn't breaking the StackOverflow rules of asking this kind of question. Thank you and appreciate any help.
UPDATE:
In the MainActivity:
static String radioTitle = "RadioStation1";
static String radioStreamURL = "http://108.61.73.117:8124";
static String radioTitle2 = "RadioStation2";
static String radioStreamURL2 = "http://108.61.73.117:8124";
static String radioTitle3 = "RadioStation3";
static String radioStreamURL3 = "http://108.61.73.117:8124";
...........
nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
prevButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
And the RadioService class:
private String radioStreamURL = MainActivity.radioStreamURL;
private String radioStreamURL2 = MainActivity.radioStreamURL2;
private String radioStreamURL3 = MainActivity.radioStreamURL3;
...............
public void prepare() {
/* Prepare Async Task - starts buffering */
try {
mediaPlayer.setDataSource(radioStreamURL);
mediaPlayer.setDataSource(radioStreamURL2);
mediaPlayer.setDataSource(radioStreamURL3);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Look at your method at RadioService.java
public void prepare() {
/* Prepare Async Task - starts buffering */
try {
mediaPlayer.setDataSource(radioStreamURL);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here you set the URL to your radio stream, the fast way to change your code without knowing all your code is to alter radioStreamURL variable.
private String radioStreamURL = MainActivity.radioStreamURL;
If you have some static information about the radios you want to use, just change this String to a List and add all the Radio's URL you want.
Add a Next and Preview button to your layout, set the listener to call your RadioService with this function, something like this:
MainActivity
private static int station = 0;//Not right, just to show
public void onNextStationClicked(){
radioServiceBinder.changeStation(++station);
}
RadioService
public static final String MODE_STATION_CHANGE = "STATION_CHANGE";
public void changeStation(int stationIndex){
radioStreamURL = MainActivity.radioStreamURL.get(stationIndex);
stop();
play();
}
This is just an idea, the code isn't the best but with a little work should work...
UPDATE
Try change your code to this:
RadioService
private List<String> radioStreamURL = new ArrayList<String>
private int radioStreamingIndex = 0;
then on your constructor add this
#Override
public void onCreate() {
radioStreamURL.add(radioStreamURL);
radioStreamURL.add(radioStreamURL2);
radioStreamURL.add(radioStreamURL3);
// etc
}
public void prepare() {
/* Prepare Async Task - starts buffering */
try {
mediaPlayer.setDataSource(radioStreamURL.get(radioStreamingIndex));
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
public void nextStation(){
changeStation(radioStreamingIndex+1);
}
public void prevStation(){
changeStation(radioStreamingIndex-1);
}
private void changeStation(int stationIndex){
if(stationIndex > 0 && stationIndex < radioStreamURL.size()){
radioStreamingIndex = stationIndex;
stop();
play();
}
}
MainActivity
nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
radioServiceBinder.nextStation();
}
});
prevButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
radioServiceBinder.prevStation();
}
});
I am not too experience in Android development, but you may need a complex algorithm developed if you would like to follow Spotify and Pandora's steps in the sense that the radio stations are created in relation to the listener's genre, etc.

Categories

Resources