উদাহরণ: বার্তা ব্যবহার করে ক্রিয়াকলাপ এবং পরিষেবাগুলির মধ্যে যোগাযোগ


584

কোনও ক্রিয়াকলাপ এবং কোনও পরিষেবার মধ্যে কীভাবে বার্তাগুলি প্রেরণ করা যায় তার কোনও উদাহরণ আমি খুঁজে পাইনি এবং এটি আবিষ্কার করতে আমি অনেক বেশি সময় ব্যয় করেছি। অন্যদের উল্লেখের জন্য এখানে একটি উদাহরণ প্রকল্প।

এই উদাহরণটি আপনাকে সরাসরি কোনও পরিষেবা শুরু করতে বা বন্ধ করতে এবং পরিষেবা থেকে পৃথকভাবে বাঁধাই / আবদ্ধ করতে দেয়। যখন পরিষেবাটি চলছে, এটি 10 ​​হার্জেজে একটি সংখ্যা বৃদ্ধি করে। ক্রিয়াকলাপটি যদি আবদ্ধ থাকে তবে Serviceএটি বর্তমান মানটি প্রদর্শন করবে। ডেটা একটি পূর্ণসংখ্যার হিসাবে এবং একটি স্ট্রিং হিসাবে স্থানান্তরিত হয় যাতে আপনি দেখতে পারেন যে এটি কীভাবে দুটি পৃথক উপায়ে করা যায়। ক্রিয়াকলাপে পরিষেবার মধ্যে বার্তা প্রেরণের বোতামগুলিও রয়েছে (ইনক্রিমেন্ট-বাই মান পরিবর্তন করে)।

স্ক্রীনশট:

অ্যান্ড্রয়েড পরিষেবা বার্তাপ্রেরণের স্ক্রিনশট

Andro আইডি:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exampleservice"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <service android:name=".MyService"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>

মাঝামাঝি \ মান \ strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExampleService</string>
    <string name="service_started">Example Service started</string>
    <string name="service_label">Example Service Label</string>
</resources>

মাঝামাঝি \ বিন্যাস \ main.xml:

<RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

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

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Stop Service" >
    </Button>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/RelativeLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnBind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind to Service" >
    </Button>

    <Button
        android:id="@+id/btnUnbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Unbind from Service" >
    </Button>
</RelativeLayout>

<TextView
    android:id="@+id/textStatus"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Status Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textIntValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Integer Value Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textStrValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="String Value Goes Here"
    android:textSize="24sp" />

<RelativeLayout
    android:id="@+id/RelativeLayout03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnUpby1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Increment by 1" >
    </Button>

    <Button
        android:id="@+id/btnUpby10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Increment by 10" >
    </Button>
</RelativeLayout>

src \ com.exampleservice \ MainActivity.java:

package com.exampleservice;

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.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
    TextView textStatus, textIntValue, textStrValue;
    Messenger mService = null;
    boolean mIsBound;
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MyService.MSG_SET_INT_VALUE:
                textIntValue.setText("Int Message: " + msg.arg1);
                break;
            case MyService.MSG_SET_STRING_VALUE:
                String str1 = msg.getData().getString("str1");
                textStrValue.setText("Str Message: " + str1);
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            textStatus.setText("Attached.");
            try {
                Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
            }
            catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
            textStatus.setText("Disconnected.");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        btnBind = (Button)findViewById(R.id.btnBind);
        btnUnbind = (Button)findViewById(R.id.btnUnbind);
        textStatus = (TextView)findViewById(R.id.textStatus);
        textIntValue = (TextView)findViewById(R.id.textIntValue);
        textStrValue = (TextView)findViewById(R.id.textStrValue);
        btnUpby1 = (Button)findViewById(R.id.btnUpby1);
        btnUpby10 = (Button)findViewById(R.id.btnUpby10);

        btnStart.setOnClickListener(btnStartListener);
        btnStop.setOnClickListener(btnStopListener);
        btnBind.setOnClickListener(btnBindListener);
        btnUnbind.setOnClickListener(btnUnbindListener);
        btnUpby1.setOnClickListener(btnUpby1Listener);
        btnUpby10.setOnClickListener(btnUpby10Listener);

        restoreMe(savedInstanceState);

        CheckIfServiceIsRunning();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("textStatus", textStatus.getText().toString());
        outState.putString("textIntValue", textIntValue.getText().toString());
        outState.putString("textStrValue", textStrValue.getText().toString());
    }
    private void restoreMe(Bundle state) {
        if (state!=null) {
            textStatus.setText(state.getString("textStatus"));
            textIntValue.setText(state.getString("textIntValue"));
            textStrValue.setText(state.getString("textStrValue"));
        }
    }
    private void CheckIfServiceIsRunning() {
        //If the service is running when the activity starts, we want to automatically bind to it.
        if (MyService.isRunning()) {
            doBindService();
        }
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnStopListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
            stopService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnBindListener = new OnClickListener() {
        public void onClick(View v){
            doBindService();
        }
    };
    private OnClickListener btnUnbindListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
        }
    };
    private OnClickListener btnUpby1Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(1);
        }
    };
    private OnClickListener btnUpby10Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(10);
        }
    };
    private void sendMessageToService(int intvaluetosend) {
        if (mIsBound) {
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                }
            }
        }
    }


    void doBindService() {
        bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        textStatus.setText("Binding.");
    }
    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
            textStatus.setText("Unbinding.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            doUnbindService();
        }
        catch (Throwable t) {
            Log.e("MainActivity", "Failed to unbind from the service", t);
        }
    }
}

src \ com.exampleservice \ MyService.java:

package com.exampleservice;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MyService extends Service {
    private NotificationManager nm;
    private Timer timer = new Timer();
    private int counter = 0, incrementby = 1;
    private static boolean isRunning = false;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
    int mValue = 0; // Holds last value set by a client.
    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_INT_VALUE = 3;
    static final int MSG_SET_STRING_VALUE = 4;
    final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.


    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    class IncomingHandler extends Handler { // Handler of incoming messages from clients.
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_INT_VALUE:
                incrementby = msg.arg1;
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private void sendMessageToUI(int intvaluetosend) {
        for (int i=mClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));

                //Send data as a String
                Bundle b = new Bundle();
                b.putString("str1", "ab" + intvaluetosend + "cd");
                Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
                msg.setData(b);
                mClients.get(i).send(msg);

            }
            catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                mClients.remove(i);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
        timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
        isRunning = true;
    }
    private void showNotification() {
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_started, notification);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    public static boolean isRunning()
    {
        return isRunning;
    }


    private void onTimerTick() {
        Log.i("TimerTick", "Timer doing work." + counter);
        try {
            counter += incrementby;
            sendMessageToUI(counter);

        }
        catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
            Log.e("TimerTick", "Timer Tick Failed.", t);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {timer.cancel();}
        counter=0;
        nm.cancel(R.string.service_started); // Cancel the persistent notification.
        Log.i("MyService", "Service Stopped.");
        isRunning = false;
    }
}

53
দুর্দান্ত উদাহরণ! আর একটি দুর্দান্ত বৈশিষ্ট্য: আপনি যদি আপনার ম্যানিফেস্ট.এক্সএমএলগুলিতে আপনার পরিষেবার ট্যাগের android:process=:myservicenameবৈশিষ্ট্যটি রাখেন service: যেমন:, <service android:name="sname" android:process=":myservicename" />তবে এটি আপনার পরিষেবাটিকে একটি পৃথক প্রক্রিয়া হিসাবে চালাবে - এইভাবে একটি ভিন্ন থ্রেডে। এর অর্থ, যে কোনও ভারী গণনা করা হয়েছে / পরিষেবাটির দীর্ঘ অনুরোধ আপনার ইউআই থ্রেডটি স্থির রাখবে না।
২১:০১ এ সিড করুন

28
আমি জানি আপনি এটি করার জন্য প্রচেষ্টা করেছেন তবে এটি গিথুব বা অনুরূপ উত্স-কোড ভাগ করে নেওয়ার সাইটে এবং লিঙ্কটি এখানে পোস্ট করা আরও বোধগম্য হবে। এইভাবে উঠানো এবং এভাবে চালানো মানুষের পক্ষে সহজ।
এহতেশ চৌধুরী

25
ভালো উদাহরণ. যারা এই ক্লোন করতে চান তাদের জন্য আমি একটি অনলাইন রেপোতে (সামান্য পরিবর্তন সহ) এই কোডটি রেখেছি: বিটবুকিট.আর.এলএক্সফু
অ্যালেক্স ফু

7
আপনার পরিষেবাটিকে অন্যান্য অ্যাপ্লিকেশন দ্বারা কল করা যেতে পারে তবে মেসেজিং সত্যই প্রয়োজনীয়। অন্যথায় আপনি কোনও বাইন্ডারের সাথে আটকে থাকতে পারেন যা আপনাকে পরিষেবার একটি রেফারেন্স দেয় এবং কেবল এটির সর্বজনীন পদ্ধতিগুলিতে কল করতে পারে।
টাইপ- a1pha

13
আপনার প্রশ্ন করা উচিত ছিল এবং তারপরে একটি উত্তর নিজেই তৈরি করা উচিত, প্রশ্নের সমস্যার উত্তর নয়। যদিও দুর্দান্ত উদাহরণ;)
7hi4g0

উত্তর:


46

LocalService উদাহরণ

তোমার Serviceআয় সমস্ত গ্রাহক কল নিজেই একটি দৃষ্টান্ত onBind। তারপরে আপনি সরাসরি পরিষেবার সাথে ইন্টারঅ্যাক্ট করতে পারেন, যেমন পরিষেবার সাথে আপনার নিজের শ্রোতা ইন্টারফেসটি নিবন্ধন করুন, যাতে আপনি কলব্যাক পেতে পারেন।


2
এর সাথে একমাত্র সমস্যাটি হ'ল এটি মেসেঞ্জার ব্যবহার করবে না, সুতরাং এটি এই সিডো-প্রশ্নের উত্তর দেবে না। আমি একটি লোকাল সার্ভিস ব্যবহার করেছি তবে আমি ম্যাসেঞ্জার / হ্যান্ডলারের উদাহরণ পেয়ে খুশি হয়েছি। আমি বিশ্বাস করি না যে কোনও লোকাল সার্ভিসিকে অন্য প্রক্রিয়াতে রাখা যায়।
বেন

@ ক্রিস্টোপার-অর: আমি Android BroadcastReceiverটিউটোরিয়ালটির সেই লিঙ্কটি পোস্ট করেছি বলে আমি অত্যন্ত কৃতজ্ঞ । আমি LocalBroadcastManagerদুটি Activityউদাহরণের মধ্যে ক্রমাগত ডেটা এক্সচেঞ্জ করতে একটি ব্যবহার করেছি ।
ডিস্ক

সমস্যাটি LocalBroadcastManagerহ'ল এটি অবরুদ্ধ নয় এবং আপনাকে ফলাফলের জন্য অপেক্ষা করতে হবে। কখনও কখনও আপনি তাত্ক্ষণিক ফলাফল চান।
TheRealChx101

আপনি কি দয়া করে এই প্রশ্নে আমাকে সহায়তা করতে পারেন stackoverflow.com/questions/51508046/…
রাজেশ কে

20

কোনও পরিষেবাতে ডেটা প্রেরণের জন্য আপনি ব্যবহার করতে পারেন:

Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);

এবং অন স্টার্টকমন্ড () এ পরিষেবা দেওয়ার পরে অভিপ্রায় থেকে ডেটা পান।

কোনও অ্যাপ্লিকেশনে কোনও পরিষেবা থেকে ডেটা বা ইভেন্ট প্রেরণের জন্য (এক বা একাধিক ক্রিয়াকলাপের জন্য):

private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
    Intent intent = new Intent(intentFilterName);
    if (arg1 != -1 && extraKey != null) {
        intent.putExtra(extraKey, arg1);
    }
    sendBroadcast(intent);
}

এই পদ্ধতিটি আপনার পরিষেবা থেকে কল করছে। আপনি কেবল আপনার ক্রিয়াকলাপের জন্য ডেটা প্রেরণ করতে পারেন।

private void someTaskInYourService(){

    //For example you downloading from server 1000 files
    for(int i = 0; i < 1000; i++) {
        Thread.sleep(5000) // 5 seconds. Catch in try-catch block
        sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
    }

ডেটা সহ একটি ইভেন্ট পাওয়ার জন্য, আপনার ক্রিয়াকলাপে পদ্ধতি রেজিস্টারড্রোডকাস্টার রিসিভার্স () তৈরি এবং রেজিস্টার করুন:

private void registerBroadcastReceivers(){
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int arg1 = intent.getIntExtra("up_download_progress",0);
            progressBar.setProgress(arg1);
        }
    };
    IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
    registerReceiver(broadcastReceiver,progressfilter);

আরও ডেটা প্রেরণের জন্য, আপনি পদ্ধতিটি পরিবর্তন করতে পারেন sendBroadcastMessage();। মনে রাখবেন: আপনাকে অবশ্যই অনারিউম () এবং ব্র্যান্ডকাস্টগুলি অনস্টপ () পদ্ধতিতে নিবন্ধভুক্ত করতে হবে!

হালনাগাদ

ক্রিয়াকলাপ এবং পরিষেবার মধ্যে আমার ধরণের যোগাযোগ ব্যবহার করবেন না। এটি ভুল উপায়। আরও ভাল অভিজ্ঞতার জন্য দয়া করে বিশেষ লিবস ব্যবহার করুন, যেমন আমাদের:

1) গ্রিনরোবট থেকে ইভেন্টবাস

2) স্কয়ার ইনক থেকে ওটো

পিএস আমি কেবল আমার প্রকল্পগুলিতে গ্রিনরোবট থেকে ইভেন্টবাস ব্যবহার করছি,


2
অনুরুপ এবং অনস্টপে আমাকে ক্রিয়াকলাপের জন্য নিখরচায়কের নিবন্ধন করার দরকার কোথায়?
ব্যবহারকারী3233280

হ্যাঁ. পরিষেবা থেকে ইভেন্ট পাওয়ার জন্য আপনাকে অবশ্যই অনারুমে সম্প্রচারিত নিবন্ধন করতে হবে। মনে রাখবেন যে আপনাকে অবশ্যই অনস্টপে সম্প্রচারিত নিবন্ধন বাতিল করতে হবে। এখন, আমি আমার পদ্ধতিটি ব্যবহার করার পরামর্শ দিচ্ছি না। দয়া করে অন্যান্য মতামত / ক্রিয়াকলাপ / পরিষেবাদি যেমন ইভেন্টবাস github.com/greenrobot/EventBus বা অটো github.com/square/otto
এ.ব্ল্যাক 13

1
আপনি কি দয়া করে আমাকে পরিষেবা প্রকল্পে আটকে থাকা এই প্রকল্পটি আমি কীভাবে ব্যবহার করতে পারি
ইউজার 23233280

8
গুগল কি এর বিপরীতে সুপারিশ করেছে, বা আপনি কেবল "ভুল" বলছেন কারণ আপনি মনে করেন যে অন্যান্য সমাধানগুলি আরও ভাল?
কেভিন ক্রামউইদে

আরও EventBusএবং লিঙ্ক সরবরাহ করার জন্য এক Otto
মোহাম্মদ আলী

14

দ্রষ্টব্য: আপনার পরিষেবাটি চলছে কিনা তা পরীক্ষা করে দেখার দরকার নেই CheckIfServiceIsRunning(), কারণ bindService()এটি চালু না থাকলে এটি শুরু করবে।

এছাড়াও: আপনি যদি ফোনটি ঘোরান তবে আপনি এটি bindService()আবার চান না , কারণ onCreate()আবার কল করা হবে। onConfigurationChanged()এটি প্রতিরোধের জন্য সংজ্ঞা দিতে ভুলবেন না ।


আমার ক্ষেত্রে, সার্বক্ষণিক আমার পরিষেবা চালানোর দরকার নেই। কার্যকলাপটি শুরু হওয়ার আগে যদি পরিষেবাটি ইতিমধ্যে চলমান থাকে, তবে আমি এটির সাথে আবদ্ধ হতে চাই। ক্রিয়াকলাপ শুরু হওয়ার পরে যদি পরিষেবাটি চলমান না থাকে তবে আমি পরিষেবাটি বন্ধ করে দিতে চাই।
ল্যান্স লেফবুর

1
আমি নিশ্চিত নই যে এটি সত্য, বাইন্ডসার্ভিস পরিষেবাটি শুরু করে না, আপনি কি দয়া করে ডকুমেন্টেশনে নির্দেশ করতে পারেন?
ক্যালিন

1
developer.android.com/references/android/app/Service.html প্রথম অনুচ্ছেদে বলা হয়েছেServices can be started with Context.startService() and Context.bindService()
কেউ কোথাও

8
Message msg = Message.obtain(null, 2, 0, 0);
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("names", names);
                    bundle.putString("captions",captions); 
                    msg.setData(bundle);

সুতরাং আপনি এটি পরিষেবাতে প্রেরণ করুন। পরে গ্রহণ।


8

সবকিছু fine.Good উদাহরণ activity/serviceব্যবহার যোগাযোগ রসূল

একটি মন্তব্য: পদ্ধতিটি MyService.isRunning()প্রয়োজন হয় না .. bindService()যে কোনও সময় করা যায়। এতে কোনও ক্ষতি হবে না।

মাই সার্ভিস যদি অন্য কোনও প্রক্রিয়াতে চলছে তবে স্থির ফাংশনটি MyService.isRunning()সর্বদা মিথ্যা হয়ে যাবে return সুতরাং এই ফাংশন কোন প্রয়োজন নেই।


2

এইভাবে আমি ক্রিয়াকলাপটি>> পরিষেবা যোগাযোগ প্রয়োগ করেছি: আমার ক্রিয়াকলাপে

private static class MyResultReciever extends ResultReceiver {
     /**
     * Create a new ResultReceive to receive results.  Your
     * {@link #onReceiveResult} method will be called from the thread running
     * <var>handler</var> if given, or from an arbitrary thread if null.
     *
     * @param handler
     */
     public MyResultReciever(Handler handler) {
         super(handler);
     }

     @Override
     protected void onReceiveResult(int resultCode, Bundle resultData) {
         if (resultCode == 100) {
             //dostuff
         }
     }

এবং তারপরে আমি আমার পরিষেবা শুরু করতে এটি ব্যবহার করেছি

protected void onCreate(Bundle savedInstanceState) {
MyResultReciever resultReciever = new MyResultReciever(handler);
        service = new Intent(this, MyService.class);
        service.putExtra("receiver", resultReciever);
        startService(service);
}

আমার সেবা ছিল

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null)
        resultReceiver = intent.getParcelableExtra("receiver");
    return Service.START_STICKY;
}

আশাকরি এটা সাহায্য করবে


0

আমার কাছে মনে হচ্ছে আপনি "ক্রিয়াকলাপগুলি হ্যান্ডলারের কলব্যাক" দিয়ে আপনার ক্রিয়াকলাপটি ঘোষণা করে কিছু স্মৃতি সঞ্চয় করতে পেরেছিলেন


0

দুর্দান্ত টিউটোরিয়াল, দুর্দান্ত উপস্থাপনা। ঝরঝরে, সরল, সংক্ষিপ্ত এবং খুব ব্যাখ্যামূলক। যদিও, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);পদ্ধতি আর নেই। এখানে যেমন বলা হয়েছে , ভাল পন্থাটি হ'ল :

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

নিজেকে পরীক্ষা করে দেখুন, সমস্ত কিছুই কবজের মতো কাজ করে (ক্রিয়াকলাপ এবং পরিষেবার নামগুলি মূল থেকে পৃথক হতে পারে)।


0

আমি সব উত্তর দেখেছি। আমি এখন সবচেয়ে শক্তিশালী উপায় বলতে চাই একটি দিন । এটি আপনাকে Activity - Service - Dialog - Fragments(সমস্ত কিছুর) মধ্যে যোগাযোগ করতে দেবে ।

EventBus

আমি এই প্রকল্পগুলিতে আমার প্রকল্পগুলিতে ব্যবহার করছি মেসেজিং সম্পর্কিত দুর্দান্ত বৈশিষ্ট্য রয়েছে।

ইভেন্ট পদ 3 পদক্ষেপে

  1. ইভেন্টগুলি সংজ্ঞায়িত করুন:

    public static class MessageEvent { /* Additional fields if needed */ }

  2. গ্রাহক প্রস্তুত করুন:

আপনার সাবস্ক্রাইব করার পদ্ধতিটি ঘোষণা করুন এবং এনেটেট করুন, allyচ্ছিকভাবে একটি থ্রেড মোড নির্দিষ্ট করুন :

@Subscribe(threadMode = ThreadMode.MAIN) 
public void onMessageEvent(MessageEvent event) {/* Do something */};

নিবন্ধভুক্ত করুন এবং আপনার গ্রাহক নিবন্ধন করুন। অ্যান্ড্রয়েডে উদাহরণস্বরূপ, ক্রিয়াকলাপ এবং টুকরা সাধারণত তাদের জীবনচক্র অনুযায়ী নিবন্ধভুক্ত করা উচিত:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}
  1. ইভেন্ট পোস্ট করুন:

    EventBus.getDefault().post(new MessageEvent());

আপনার অ্যাপ স্তরের গ্রেডে কেবল এই নির্ভরতা যুক্ত করুন

compile 'org.greenrobot:eventbus:3.1.1'
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.