Android Activity 服务通信

标签 android android-activity android-service android-service-binding

我正在实现一个具有服务和 Activity 的 android 软件。我根据 youtube 视频编写了一些代码。但是当我单击开始按钮时,运行按钮它们工作正常。但是在我重新启动服务后(通过按停止然后再次按启动)程序崩溃了。所以任何人都可以帮我解决这个问题。

在 android 中还有什么方法可以在服务和 Activity 之间进行双向通信吗? (例如:- 服务获取 GPS 位置并按 0.001 更改位置,然后 ui 自动显示编辑后的位置)

请有人帮我解决这个问题。

我的代码:-

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();
    }
};
}

我的服务.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>

最佳答案

当您在 stopMethod(View v) 中设置 mConnection=null 时,以及当您尝试从 startMethod(View v)< 绑定(bind)服务时/strong> 它正在尝试将服务与 mConnection(为空) 绑定(bind)。因此它正在崩溃。 修复:注释掉 stoptMethod(View v) 中的 mConnection=null。 也没有必要

Intent i = new Intent(this, MyService.class);停止服务(我);在 stopMethod(View v)

当应用程序组件通过调用 bindService() 绑定(bind)到服务时,服务被“绑定(bind)”。绑定(bind)服务提供了一个客户端-服务器接口(interface),允许组件与服务交互、发送请求、获取结果,甚至通过进程间通信 (IPC) 跨进程进行。绑定(bind)服务仅在另一个应用程序组件绑定(bind)到它时运行。多个组件可以一次绑定(bind)到服务,但是当所有组件都解除绑定(bind)时,服务就会被销毁。

更多信息请访问bound-servicesServices .

关于Android Activity 服务通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653149/

相关文章:

android - 如何在清除数据后清除计数标记并在 android 中卸载应用程序?

android - 即使我的应用程序设置为默认短信应用程序,也可以删除 4.4 上的短信

Android - 检测 Activity 是否因屏幕方向改变而启动

android - 通过 AIDL 在服务之间传递 Activity 对象

android - 如何使用 Hackbook 示例获取 Facebook 好友即将到来的生日

java - QR码扫描后如何添加重定向

java - 如何使用 Intent 将用户输入数据从一个 Activity 发送到另一个 Activity

java - 无法连接到网址

Android - 判断某个InputMethod(自定义键盘)的调用应用

Android:检查与服务器的连接