i have a service running which receive broadcast messages in LAN and i have started the service from fragment and i want to stop the service when the fragment is destroyed but its giving NPE when i call stopservice.
My service calling fragment is:
public class Receive extends Fragment {
TextView tv1,tv2;
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView =inflater.inflate(R.layout.receive, container, false);
intent = new Intent(getActivity(), Server.class);
tv1=(TextView)rootView.findViewById(R.id.textView1);
tv2=(TextView)rootView.findViewById(R.id.textView2);
//getActivity().startService(intent);
return rootView;
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}};
private void updateUI(Intent intent) {
Toast.makeText(getActivity().getApplicationContext(), "Yea!!! Service called", Toast.LENGTH_SHORT).show();
String message = intent.getStringExtra("messages");
String senderip = intent.getStringExtra("sender");
tv2.setText(message);
tv1.setText(senderip);
}
#Override
public void onResume() {
super.onResume();
getActivity().startService(intent);
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(
Server.UDP_BROADCAST));
Log.i("UDP", "reg started");
}
#Override
public void onPause() {
super.onPause();
getActivity(). unregisterReceiver(broadcastReceiver);
getActivity().stopService(intent);
Log.i("UDP", "unreg started");
}
}
My service is:
public class Server extends Service {
static String UDP_BROADCAST = "soft.b.peopleassist";
//Boolean shouldListenForUDPBroadcast = false;
DatagramSocket socket;
//Intent intent;
private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
byte[] recvBuf = new byte[15000];
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket(port, broadcastIP);
socket.setBroadcast(true);
}
//socket.setSoTimeout(1000);
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
Log.e("UDP", "Waiting for UDP broadcast");
socket.receive(packet);
String senderIP = packet.getAddress().getHostAddress();
String message = new String(packet.getData());
Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);
broadcastIntent(senderIP, message);
socket.close();
}
private void broadcastIntent(String senderIP, String message) {
Intent intent = new Intent(Server.UDP_BROADCAST);
intent.putExtra("sender", senderIP);
intent.putExtra("messages", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
InetAddress broadcastIP = InetAddress.getByName("192.168.1.255"); //172.16.238.42 //192.168.1.255
Integer port = 11111;
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent(broadcastIP, port);
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
private Boolean shouldRestartSocketListen=true;
void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}
#Override
public void onCreate() {
};
#Override
public void onDestroy() {
stopListen();
//stopService(intent);
Log.i("UDP", "Service stoped");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("UDP", "Service started");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
My logcat is:
09-03 09:17:21.995: D/gralloc_goldfish(908): Emulator without GPU emulation detected.
09-03 09:17:28.763: I/UDP(908): reg started
09-03 09:17:28.853: I/UDP(908): Service started
09-03 09:17:28.993: I/UDP(908): no longer listening for UDP broadcasts cause of error bind failed: EADDRNOTAVAIL (Cannot assign requested address)
09-03 09:17:30.653: I/UDP(908): unreg started
09-03 09:17:30.893: D/AndroidRuntime(908): Shutting down VM
09-03 09:17:30.893: W/dalvikvm(908): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
09-03 09:17:30.963: E/AndroidRuntime(908): FATAL EXCEPTION: main
09-03 09:17:30.963: E/AndroidRuntime(908): java.lang.RuntimeException: Unable to stop service soft.b.peopleassist.Server#4137dbb8: java.lang.NullPointerException
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.handleStopService(ActivityThread.java:2405)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.access$2000(ActivityThread.java:122)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.os.Handler.dispatchMessage(Handler.java:99)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.os.Looper.loop(Looper.java:137)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.main(ActivityThread.java:4340)
09-03 09:17:30.963: E/AndroidRuntime(908): at java.lang.reflect.Method.invokeNative(Native Method)
09-03 09:17:30.963: E/AndroidRuntime(908): at java.lang.reflect.Method.invoke(Method.java:511)
09-03 09:17:30.963: E/AndroidRuntime(908): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-03 09:17:30.963: E/AndroidRuntime(908): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-03 09:17:30.963: E/AndroidRuntime(908): at dalvik.system.NativeStart.main(Native Method)
09-03 09:17:30.963: E/AndroidRuntime(908): Caused by: java.lang.NullPointerException
09-03 09:17:30.963: E/AndroidRuntime(908): at soft.b.peopleassist.Server.stopListen(Server.java:68)
09-03 09:17:30.963: E/AndroidRuntime(908): at soft.b.peopleassist.Server.onDestroy(Server.java:78)
09-03 09:17:30.963: E/AndroidRuntime(908): at android.app.ActivityThread.handleStopService(ActivityThread.java:2388)
09-03 09:17:30.963: E/AndroidRuntime(908): ... 10 more
09-03 09:17:33.533: I/Process(908): Sending signal. PID: 908 SIG: 9
Thanks in Advance.
In the stopListen() method you set the stop boolean and then immediately close the socket.
It is possible, that your other thread is deeply in work with that. I would suggest, that you close sockets in the thread in which they where created. e.g. socket.close() in the catchblock and remove it from stopListen().
Related
I am working on a simple Service application which increments a counter ever 1 second and shows notification after every 10 seconds. I have used thread so, when I close my app service runs in the background.
Problem- Everything is working fine but when I immediately press back button after starting the counter on button click. My App crashes. Can somebody tell me what is the problem? Thanks!
public class MyService extends Service {
private static final int NOTIFICATION_ID = 5453;
String s;
boolean flag=true;
int cooo;
int m;
int n=0;
private void triggerNotification(final int text){ //Notification Triggering Function
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_noti);
Intent intent = new Intent(this, ServiceActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ServiceActivity.class); // Creates a virtual stack so that when back key is pressed main activity will be displayed
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
CharSequence tickerText="Current Counter Value :"+text;
Notification notification = new Notification.Builder(this)
.setLargeIcon(bm)
.setSmallIcon(R.drawable.ic_action_noti) // Setting Notification Icon
.setContentTitle(getString(R.string.notification)) // Setting Title of Notification
.setAutoCancel(true) // Makes this notification automatically dismissed when the user touches it
.setPriority(Notification.PRIORITY_MAX) // Setting priority to Max
.setContentIntent(pendingIntent)
.setContentText(tickerText)
.setLights(0xFF0000FF, 100,3000)
.setSound(soundUri)
.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager = //Notification Manager
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
// Log.d(TAG, "Notification sent successfully.");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
} //Default function of service class
public int onStartCommand(Intent intent, int flags, int startID){ //Function recieving intent from startService
cooo=intent.getIntExtra("cont", 0);
s=Integer.toString(cooo);
Thread thread=new Thread(new Runnable() {
#Override
public void run() { //Thread Initialized
while(flag){
try{ Log.d("The counter value is:", s + " ");
m=Integer.parseInt(s);
m++;
n++;
s=Integer.toString(m);
if(n%10==0){
Log.d("Notification Triggered", "Congrats!");
triggerNotification(m);
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start(); //Thread Started
return super.onStartCommand(intent,flags,startID); //sending intent again
}
public void onDestroy(){ //function call on stop button pressed
super.onDestroy();
flag=false;
Log.d("Notification Triggered","on stop Button");
triggerNotification(m);
//Toast.makeText(getApplicationContext(),"stopped",Toast.LENGTH_LONG).show();
}
}
Error Log-
04-06 23:06:11.450 16940-16940/headfirst.com.serviceapplication
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service
headfirst.com.serviceapplication.MyService#427724e8 with null:
java.lang.NullPointerException
at
android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2850)
at android.app.ActivityThread.access$2000(ActivityThread.java:159)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at
headfirst.com.serviceapplication.MyService.onStartCommand(MyService.java:72)
at
android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2833)
at android.app.ActivityThread.access$2000(ActivityThread.java:159)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
I am trying to run a background music in my android application but I am getting errors
IF MY QUESTION FORMAT IS WRONG, PLEASE CORRECT ME
how to solve this problem ?
I have a main activity MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent svc=new Intent(this, BackgroundMusic.class);
startService(svc);
}
in the service activity BackgroundMusic:
package com.example.tttgame;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class BackgroundMusic extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
in the AndroidManifiest :
<activity
android:name="com.example.tttgame.BoardActivity"
android:label="#string/app_name" >
</activity>
<service android:enabled="true" android:name="com.example.tttgame.BackgroundMusic" />
</application>
my error message :
09-03 21:45:20.387: E/MainActivity(1392): starting Main Activity ..
09-03 21:45:22.077: E/MainActivity(1392): checking if key 'flag' exists in preferences..
09-03 21:45:22.377: E/MediaPlayer(1392): Should have subtitle controller already set
09-03 21:45:22.797: E/MediaPlayer(1392): error (1, -2147483648)
09-03 21:45:22.837: E/AndroidRuntime(1392): FATAL EXCEPTION: main
09-03 21:45:22.837: E/AndroidRuntime(1392): Process: com.example.tttgame, PID: 1392
09-03 21:45:22.837: E/AndroidRuntime(1392): java.lang.RuntimeException: Unable to create service com.example.tttgame.BackgroundMusic: java.lang.NullPointerException
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2563)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.access$1700(ActivityThread.java:135)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1479)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.os.Handler.dispatchMessage(Handler.java:102)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.os.Looper.loop(Looper.java:137)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.main(ActivityThread.java:4998)
09-03 21:45:22.837: E/AndroidRuntime(1392): at java.lang.reflect.Method.invokeNative(Native Method)
09-03 21:45:22.837: E/AndroidRuntime(1392): at java.lang.reflect.Method.invoke(Method.java:515)
09-03 21:45:22.837: E/AndroidRuntime(1392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
09-03 21:45:22.837: E/AndroidRuntime(1392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
09-03 21:45:22.837: E/AndroidRuntime(1392): at dalvik.system.NativeStart.main(Native Method)
09-03 21:45:22.837: E/AndroidRuntime(1392): Caused by: java.lang.NullPointerException
09-03 21:45:22.837: E/AndroidRuntime(1392): at com.example.tttgame.BackgroundMusic.onCreate(BackgroundMusic.java:21)
09-03 21:45:22.837: E/AndroidRuntime(1392): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2553)
09-03 21:45:22.837: E/AndroidRuntime(1392): ... 10 more
player = MediaPlayer.create(this, R.raw.music);
I think this is the problem
Because error is java.lang.NullPointerException
Look at my Class for sound and take reference with that.
public class SoundService extends Service {
private static MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
try {
if (player != null) {
player.stop();
player.release();
player= null;
}
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true);
player.start();
} catch (Exception e) {
}
}
public static boolean isMediaPlaying() {
if (player != null) {
try {
return player.isPlaying();
} catch (Exception e) {
}
}
return false;
}
#Override
public void onDestroy() {
if (player!= null) {
player.stop();
player.release();
player = null;
}
super.onDestroy();
}
}
I have realesed mediaplayer in onStart if it is already there. and no need to use onstart command.
I'm developing an app with eclipse and arduino which connects to a bluetooth module. I can then control the LEDS on the board. However my code shows no errors but the app force closes everytime I hit a button. Here is my code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothTest extends Activity
{
TextView labelConnect;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
Button onButton = (Button)findViewById(R.id.onButton);
Button offButton = (Button)findViewById(R.id.offButton);
Button redButton = (Button)findViewById(R.id.redButton);
Button greenButton = (Button)findViewById(R.id.greenButton);
Button blueButton = (Button)findViewById(R.id.blueButton);
labelConnect = (TextView)findViewById(R.id.mylabel);
//Open Bluetooth
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close Bluetooth
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
//Red Button
redButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
redButton();
}
catch (IOException ex) { }
}
});
//Green Button
greenButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
greenButton();
}
catch (IOException ex) { }
}
});
//Blue Button
blueButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
blueButton();
}
catch (IOException ex) { }
}
});
//On Button - set strip to white
onButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
onButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Off Button - set strip to all OFF
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
} // end onCreate
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
labelConnect.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("BTNode0")) // Change to match RN42 - node name
{
mmDevice = device;
Log.i("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.i("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
labelConnect.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
labelConnect.setText("BT << " + mmDevice.getName() + " >> is now open ");
}
void closeBT() throws IOException
{
mmOutputStream.close();
mmSocket.close();
labelConnect.setText("Bluetooth Closed");
}
void offButton() throws IOException
{
mmOutputStream.write("0".getBytes());
}
void redButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
void greenButton() throws IOException
{
mmOutputStream.write("2".getBytes());
}
void blueButton() throws IOException
{
mmOutputStream.write("3".getBytes());
}
void onButton() throws IOException
{
mmOutputStream.write("4".getBytes());
}
}
And here is my log for what happens when I hit the connect button
04-25 12:15:10.771: W/asset(22604): Copying FileAsset 0x74c0a9d8 (zip:/data/app/Android.Arduino.Bluetooth-2.apk:/resources.arsc) to buffer size 1912 to make it aligned.
04-25 12:15:10.821: D/RenderPolicy(22604): ViewRootImpl.enableHardwareAcceleration -> enableRenderPolicy
04-25 12:15:10.881: I/Adreno-EGL(22604): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
04-25 12:15:10.881: I/Adreno-EGL(22604): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-25 12:15:10.881: I/Adreno-EGL(22604): Build Date: 02/04/14 Tue
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Remote Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Patches:
04-25 12:15:10.881: I/Adreno-EGL(22604): Reconstruct Branch:
04-25 12:15:12.363: W/dalvikvm(22604): threadid=1: thread exiting with uncaught exception (group=0x41625e18)
04-25 12:15:12.373: E/AndroidRuntime(22604): FATAL EXCEPTION: main
04-25 12:15:12.373: E/AndroidRuntime(22604): Process: Android.Arduino.Bluetooth, PID: 22604
04-25 12:15:12.373: E/AndroidRuntime(22604): java.lang.NullPointerException
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:185)
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:53)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View.performClick(View.java:4480)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View$PerformClick.run(View.java:18673)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Looper.loop(Looper.java:157)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.app.ActivityThread.main(ActivityThread.java:5872)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-25 12:15:12.373: E/AndroidRuntime(22604): at dalvik.system.NativeStart.main(Native Method)
As they have already said in the comments, the mmDevice you are trying to use in the openBT method is null, because no device was found in the findBT method and the variable was not initialized. You need to fix your code so that you don't try to open the connection if the device was not found.
The other main issue in your code, once you solve this, is the SocketConnection you are trying to open in the Main Thread. Button handlers and GUI events are executed in the main thread, so your openBT should be moved to a separate thread (or better, a Service).
Hi I am trying to use the service class for first time and have been facing problems. What I want is an infinitely running (unless killed by Android System) service with an active Network connection. I have written the code which works fine on Android 4.3 and 4.4 but the application crashes when I try running on Android 2.2. My code is as follows:
public class BackgroundMusicService extends Service {
private MediaPlayer mp;
private int id;
private static class BackgroundAsyncTaskClass extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... params) {
Log.v("Async","Async Called");
/*Network connection will be created here*/
return null;
}
}
private class ForThread implements Runnable{
public void run() {
while (true) {
try {
Log.v("ThreadSleeping","5 sec");
BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
task.execute();
Thread.sleep(5000);
} catch (InterruptedException e) {
}finally{
Log.v("Finally called","Finally called");
}
}
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("onStartCommand Called","onStart Command Called");
Thread t;
ForThread ft = new ForThread();
t = new Thread(ft);
t.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(null != mp){
mp.stop();
mp.release();
Log.v("Destroyed","onDestroy Called");
}
}
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),
this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(
getApplicationContext(), 1, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
and the exception thrown by Android 2.2 is as follows:
04-28 09:51:41.435: W/dalvikvm(280): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
04-28 09:51:41.435: E/AndroidRuntime(280): FATAL EXCEPTION: Thread-8
04-28 09:51:41.435: E/AndroidRuntime(280): java.lang.ExceptionInInitializerError
04-28 09:51:41.435: E/AndroidRuntime(280): at com.example.backgroundservicedemo.BackgroundMusicService$ForThread.run(BackgroundMusicService.java:45)
04-28 09:51:41.435: E/AndroidRuntime(280): at java.lang.Thread.run(Thread.java:1096)
04-28 09:51:41.435: E/AndroidRuntime(280): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.Handler.<init>(Handler.java:121)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
Also, when I try using handler.post(new Runnable(){.... run(){}....} The UI hangs up but the background thread continues running and exits after it becomes out of memory.
Another thing that I have doubts about is:
When the application restarts, I want this active Service to stop, but how do I get a reference to this thread running in Background and how do I stop this? I would appreciate if anyone can redirect me to a suitable link/reference or could help me out with the code. Thanks
You have this inside a thread's run method
BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
task.execute();
Threading rules from the docs
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
I am working on a project in which I have a TCP connection with a server via Android.
I am using the following code:
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
Socket s;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
try {
s = new Socket("192.168.1.54", 64000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am running the connection as a service.
The real problem is I can make a connection with my Android phone (2.3.7) and with the emulator (2.3.3) but when I want to test in on my tablet (4.0.3), my app always crashes when I want to start the connection.
Can someone help me with this?
Here is the logcat log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service
com.gunther.servicetcp.MyService#412b0a98 with Intent
{ cmp=com.gunther.servicetcp/.MyService }: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2376)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
0at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at com.gunther.servicetcp.MyService.onStart(MyService.java:53)
at android.app.Service.onStartCommand(Service.java:438)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
: ... 10 more
You shouldn't do network operations on the main thread. This will lead to your app being unresponsive. Before Honeycomb you could get away with it, but Honeycomb and newer Android versions will check and throw the exception you're getting. See also this page of the Android Developers API
Services's onStart() method runs on the main thread, (yes, services seem to run on the main thread of the application.) so you should fork another thread in the onStart() method and do everything you need to do in that thread.