fragment可以发送广播给Service吗?

deathmasgu 发布于 02/11 22:21
阅读 60
收藏 0

我这边在fragment里面有一个播放音乐的播放按钮,另外有一个服务专门用来在后台播放音乐,点击fragment发送广播,service这边已经设置好receiver,测试如果用activity发送,service可以收到没问题,但是用这个activity里面的fragment发送,就会发送失败。发送语句如下,测试该语句返回值为false并且service的onReceive打桩没有收到。

LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
加载中
0
九离天
九离天

你的service是怎么配的,Manifest里面。

我试了一下,可以的,我用的模拟器,7.1的

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "ibm.com.test"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    implementation 'com.android.support:design:27.1.1'
}
package tzroutinepatrol.tzaic.ibm.com.test;

import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import tzroutinepatrol.tzaic.ibm.com.test.ui.main.MainFragment;
import tzroutinepatrol.tzaic.ibm.com.test.ui.main.MyService;

public class MainActivity extends AppCompatActivity {
    Intent service;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        service= new Intent(this, MyService.class);
        startService(service);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance())
                    .commitNow();
        }
    }

    @Override
    protected void onDestroy() {
        stopService(service);
        super.onDestroy();
    }

    public void onClick(View view) {
        Intent intent = new Intent("test.local");
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}
package tzroutinepatrol.tzaic.ibm.com.test.ui.main;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import tzroutinepatrol.tzaic.ibm.com.test.R;

public class MainFragment extends Fragment {

    private MainViewModel mViewModel;

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment, container, false);
        view.findViewById(R.id.message).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMesg();
            }
        });
        return view;
    }

    private void sendMesg() {
        Intent intent = new Intent("test.local");
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        // TODO: Use the ViewModel
    }

}
package tzroutinepatrol.tzaic.ibm.com.test.ui.main;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("top.crossrun","onCreate()");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("test.local");
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        Log.e("top.crossrun","local broad");
                    }
                },intentFilter);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
  <service
            android:name=".ui.main.MyService"
            android:enabled="true"
            android:exported="false"/>

        <activity
            android:name=".Main2Activity"
            android:label="@string/title_activity_main2"
            android:theme="@style/AppTheme.NoActionBar"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

 

 

是不是你启动顺序的问题?

0
d
deathmasgu

感谢你的回答,我用的是FragmentPagerAdapter内部类,位于Service类体里,

 private class InnerPagerAdapter extends FragmentPagerAdapter{
        public InnerPagerAdapter(FragmentManager fm) {
            super(fm);
        }
        public Fragment getItem(int position){return fragments.get(position);}
        public int getCount(){return fragments.size();}
    }

而fragments则是某Activity的fragment集合。可能是我安卓版本低吧,我用的4.2的

返回顶部
顶部