Nithila
Nithila

Reputation: 139

Android Activity Service Communication

I am implementing a android software which has a service and a activity.And I do some code according to the youtube video. But when i click the start button,Run button they work fine. But after I restart the service (by press stop and then press start again) program crashed. So can anyone please help me to figure this.

Also is there any way in android to do two way communication between service and activity? (Ex:- service get the GPS location and change position by 0.001 and after that ui show the edited position automatically)

Please SomeOne help me to figure thisout.

My code:-

MyActivity.java

package com.example.autocomplete.servicemessenger;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class MyActivity extends Activity {
    boolean status=false;
    Messenger msngr=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
    }


    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void startMethod(View v){
    if (status){
        Toast.makeText(getApplicationContext(), "already started", Toast.LENGTH_SHORT).show();
    }
    else {
        Intent i = new Intent(this, MyService.class);
        bindService(i, mConnection, Context.BIND_AUTO_CREATE);
        status = true;
        Toast.makeText(getApplicationContext(), "start", Toast.LENGTH_SHORT).show();
    }
}

public void stoptMethod(View v){
    if (status) {
        Intent i = new Intent(this, MyService.class);
        unbindService(mConnection);
        stopService(i);

        mConnection = null;
        status = false;
        Toast.makeText(getApplicationContext(), "stop", Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(getApplicationContext(), "already stopped", Toast.LENGTH_SHORT).show();
    }
}

public void runMethod(View v){
    Message ms=Message.obtain(null,1,0,0,0);
    String s="This is the message by Activity";
    Bundle bn=new Bundle();
    bn.putString("my_string",s);
    ms.setData(bn);
    try {
        msngr.send(ms);
    } catch (RemoteException e) {
        e.printStackTrace();
    }

}

ServiceConnection mConnection=new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        msngr=new Messenger(service);
        status=true;
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        msngr=null;
        status=false;
        Toast.makeText(getApplicationContext(),"Disc",Toast.LENGTH_SHORT).show();
    }
};
}

MyService.java

package com.example.autocomplete.servicemessenger;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.format.Time;
import android.widget.Toast;

import java.util.logging.Handler;

/**
 * Created by NRV on 9/3/2014.
 */
public class MyService extends Service {
int val=1;
@Override
public IBinder onBind(Intent intent) {
    return msgnr.getBinder();
}



@Override
public boolean onUnbind(Intent intent) {
    stopSelf();
    return super.onUnbind(intent);
}

class MessageHandler extends android.os.Handler{

    public  void handleMessage(Message msg){
        if (msg.what==val){
            Toast.makeText(getBaseContext(),"I am toast in service",Toast.LENGTH_SHORT).show();
            Bundle bundle=msg.getData();
            String msg_snt=bundle.getString("my_string");
            Toast.makeText(getApplicationContext(),"I recv : "+msg_snt,Toast.LENGTH_SHORT).show();
        }
        else{
            super.handleMessage(msg);
        }

    }
}

Messenger msgnr=new Messenger(new MessageHandler());


}

activity_my.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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">

<TextView
    android:text="@string/hello_world"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
   />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    android:id="@+id/button"
    android:layout_below="@+id/textView"
    android:layout_marginTop="93dp"
    android:layout_toLeftOf="@+id/button2"
    android:onClick="startMethod"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Stop"
    android:id="@+id/button2"
    android:layout_below="@+id/button"
    android:layout_alignParentRight="true"
    android:layout_marginRight="106dp"
    android:onClick="stoptMethod"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Run"
    android:id="@+id/button3"
    android:layout_below="@+id/button2"
    android:layout_alignParentLeft="true"
    android:onClick="runMethod"/>

</RelativeLayout>

Upvotes: 3

Views: 328

Answers (1)

avinash
avinash

Reputation: 1774

When you are making mConnection=null in stoptMethod(View v), and when your are trying to bind the service from startMethod(View v) it is trying to bind the service with mConnection(which is null). Therefore it is crashing. Fix : comment out the mConnection=null in stoptMethod(View v). Also there is no need for

Intent i = new Intent(this, MyService.class); stopService(i); in stoptMethod(View v)

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

For more information please visit bound-services and Services.

Upvotes: 1

Related Questions