Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I think i did everything well, but i don't know why this appear
This MainActivity.java Code
Java
package com.smarty_tech.boundservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    private static String LOG_TAG = "MainActivity";

    private Button btnStartService;
    private Button btnStopService;

    SmartyService service;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Intent intent = new Intent(MainActivity.this, SmartyService.class);
        btnStartService = (Button) findViewById(R.id.btn_start_service);
        btnStopService = (Button) findViewById(R.id.btn_stop_service);



        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               bindService(intent, connection, Service.BIND_AUTO_CREATE);
               //service.printHelloWorld();
             int x = service.getRandomNumber();
                Log.e("Start Bound Service", "Bound Successfuly and X value is ");
            }
        });

        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(connection);
                Log.e("Start Bound Service", "UnBounded Successfuly");
            }
        });

    }

    /** Defines callbacks for service binding, passed to bindService() */
    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to SmartyService, cast the IBinder and get SmartyService instance
            SmartyService.SmartyBinder smartyBinder = (SmartyService.SmartyBinder) service;
            MainActivity.this.service = smartyBinder.getService();
            mBound = true;
            Log.e(LOG_TAG, "onServiceConnected call");
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            MainActivity.this.service = null;
            mBound = false;
            Log.e(LOG_TAG, "onServiceDisconnected call");
        }
    };
}


And this is my Service Code

Java
package com.smarty_tech.boundservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.util.Random;

public class SmartyService extends Service {
    private static String LOG_TAG = "SmartyService";

    public SmartyService() {
    }

    // Binder given to clients
    private final IBinder binder = new SmartyBinder();
    // Random number generator
    private final Random mGenerator = new Random();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class SmartyBinder extends Binder{
        SmartyService getService(){
            // Return this instance of LocalService so clients can call public methods
            Log.v(LOG_TAG, "in SmartyBinder");
            return SmartyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        //throw new UnsupportedOperationException("Not yet implemented");
       // printHelloWorld();
        Log.v(LOG_TAG, "in onBind");
        return binder;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.v(LOG_TAG, "in onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.v(LOG_TAG, "in onUnbind");
        return true;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(LOG_TAG, "onCreated Called !");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(LOG_TAG, "onDestroy Called , I will miss you !");
    }

    /** method for clients */
    public void printHelloWorld(){
        //for(int i = 0; i < 1000 ; i++){
            Log.e(LOG_TAG, "Hello Wolrd");
        //}
    }

    /** method for clients */
    public int getRandomNumber() {
        return mGenerator.nextInt(100);
    }
    /*

    The SmartyBinder provides the getService() method for clients to retrieve the current instance of SmartyService.
    This allows clients to call public methods in the service. For example, clients can call printHelloWorld() from the service.
     */
}


and This is main_activity.xml of the layout

Java
<pre><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_start_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"
        />

    <Button
        android:id="@+id/btn_stop_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        />

</LinearLayout>


What I have tried:

When i try to start service, the following exception appears on Logcat

06-11 09:43:03.654 2380-2380/com.smarty_tech.boundservice E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.smarty_tech.boundservice, PID: 2380
    java.lang.NullPointerException
        at com.smarty_tech.boundservice.MainActivity$1.onClick(MainActivity.java:39)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5019)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
Posted
Updated 10-Jun-18 22:37pm

It's a timing issue. You call bindService to bind your service, which will asynchronously call onServiceConnected. After that, you can use the variable service. You use it before it is assigned.
 
Share this answer
 
Then, the best place to call
getRandomNumber()

In
onServiceConnected

Like that:
public void onServiceConnected(ComponentName className, IBinder service) {
    // We've bound to SmartyService, cast the IBinder and get SmartyService instance
    SmartyService.SmartyBinder smartyBinder = (SmartyService.SmartyBinder) service;
    MainActivity.this.service = smartyBinder.getService();
    mBound = true;
    int x = MainActivity.this.service.getRandomNumber();
    Log.e(LOG_TAG, "onServiceConnected call the value of X is "+ x);
}


Is it true?
 
Share this answer
 
Comments
[no name] 11-Jun-18 4:26am    
That will work, but then it will call it every time you bind the service. This may or may not be what you want.
You could consider adding 3 buttons; "Bind", "Get random" and "Unbind". Then in the handler for "Get random" do a check if service is not null.
Thank you very much (Thaddeus Jones), it is worked for me ..
 
Share this answer
 
Comments
[no name] 11-Jun-18 4:41am    
Anytime :) For future reference; you can use comments to post replies to a solution, rather than posting as a new solution.
Mohamed Android Developer 11-Jun-18 5:15am    
Ok, Thanks ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900