Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 谷歌播放服务chrash当使用安卓附近的连接_Android_Google Play Services_Google Nearby - Fatal编程技术网

Android 谷歌播放服务chrash当使用安卓附近的连接

Android 谷歌播放服务chrash当使用安卓附近的连接,android,google-play-services,google-nearby,Android,Google Play Services,Google Nearby,我尝试为GooglesNearyConnectionsAPI实现一个小的测试应用程序。不幸的是,在3台经过测试的设备中,有2台在发现或发布广告时使用谷歌Play服务。(OnePlus 1,安卓6.1;Acer Iconia,安卓4.4) 我看到其他设备,但当我连接到其中一个设备时,会播放服务崩溃(只有我的荣誉8继续工作)。它表示连接已挂起,错误代码为1。根据这一说法,这意味着“通知服务已被终止的暂停原因” 也许你们中的一些人可以帮忙。我根据教程编写了这段代码。 不带导入的代码: MainActi

我尝试为GooglesNearyConnectionsAPI实现一个小的测试应用程序。不幸的是,在3台经过测试的设备中,有2台在发现或发布广告时使用谷歌Play服务。(OnePlus 1,安卓6.1;Acer Iconia,安卓4.4)

我看到其他设备,但当我连接到其中一个设备时,会播放服务崩溃(只有我的荣誉8继续工作)。它表示连接已挂起,错误代码为1。根据这一说法,这意味着“通知服务已被终止的暂停原因”

也许你们中的一些人可以帮忙。我根据教程编写了这段代码。 不带导入的代码:

MainActivity.java

package com.example.steffen.nearbyconnectionsdemo;



public class MainActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener,
        Connections.ConnectionRequestListener,
        Connections.MessageListener,
        Connections.EndpointDiscoveryListener {

    // Identify if the device is the host
    private boolean mIsHost = false;
    GoogleApiClient mGoogleApiClient = null;
    Button bt_ad, bt_search, bt_send;
    TextView tv_status;
    CheckBox checkBox;
    Context c;
    String globalRemoteEndpointId = "";
    EditText editText;
    final int MY_PERMISSIONS_REQUEST = 666;

    private static int[] NETWORK_TYPES = {ConnectivityManager.TYPE_WIFI,
            ConnectivityManager.TYPE_ETHERNET};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        c = this;

        checkPermisson();

        editText = (EditText) findViewById(R.id.editText);

        bt_ad = (Button) findViewById(R.id.bt_ad);
        bt_ad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bt_search.setEnabled(false);
                startAdvertising();
            }
        });

        bt_search = (Button) findViewById(R.id.bt_search);
        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startDiscovery();
            }
        });

        bt_send = (Button) findViewById(R.id.bt_send);
        bt_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = "message: " + editText.getText().toString();
                Toast.makeText(c, "Sending: " + message, Toast.LENGTH_SHORT).show();
                byte[] payload = message.getBytes();
                Nearby.Connections.sendReliableMessage(mGoogleApiClient, globalRemoteEndpointId, payload);
            }
        });

        tv_status = (TextView) findViewById(R.id.tv_status);
        checkBox = (CheckBox) findViewById(R.id.checkBox);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Nearby.CONNECTIONS_API)
                .build();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private boolean isConnectedToNetwork() {
        ConnectivityManager connManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        for (int networkType : NETWORK_TYPES) {
            NetworkInfo info = connManager.getNetworkInfo(networkType);
            if (info != null && info.isConnectedOrConnecting()) {
                return true;
            }
        }
        return false;
    }

    private void startAdvertising() {
        if (!isConnectedToNetwork()) {
            // Implement logic when device is not connected to a network
            tv_status.setText("No Network");
            return;
        }

        // Identify that this device is the host
        mIsHost = true;
        checkBox.setChecked(mIsHost);

        // Advertising with an AppIdentifer lets other devices on the
        // network discover this application and prompt the user to
        // install the application.
        List<AppIdentifier> appIdentifierList = new ArrayList<>();
        appIdentifierList.add(new AppIdentifier(getPackageName()));
        AppMetadata appMetadata = new AppMetadata(appIdentifierList);

        // The advertising timeout is set to run indefinitely
        // Positive values represent timeout in milliseconds
        long NO_TIMEOUT = 0L;

        String name = null;
        Nearby.Connections.startAdvertising(mGoogleApiClient, name, appMetadata, NO_TIMEOUT,
                this).setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
            @Override
            public void onResult(Connections.StartAdvertisingResult result) {
                if (result.getStatus().isSuccess()) {
                    // Device is advertising
                    tv_status.setText("Advertising");
                } else {
                    int statusCode = result.getStatus().getStatusCode();
                    // Advertising failed - see statusCode for more details
                    tv_status.setText("Error: " + statusCode);
                }
            }
        });
    }

    private void startDiscovery() {
        if (!isConnectedToNetwork()) {
            // Implement logic when device is not connected to a network
            tv_status.setText("No Network");
            return;
        }
        String serviceId = getString(R.string.service_id);

        // Set an appropriate timeout length in milliseconds
        long DISCOVER_TIMEOUT = 1000L;

        // Discover nearby apps that are advertising with the required service ID.
        Nearby.Connections.startDiscovery(mGoogleApiClient, serviceId, DISCOVER_TIMEOUT, this)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            // Device is discovering
                            tv_status.setText("Discovering");
                        } else {
                            int statusCode = status.getStatusCode();
                            // Advertising failed - see statusCode for more details
                            tv_status.setText("Error: " + statusCode);
                        }
                    }
                });
    }

    @Override
    public void onEndpointFound(final String endpointId, String deviceId,
                                String serviceId, final String endpointName) {
        // This device is discovering endpoints and has located an advertiser.
        // Write your logic to initiate a connection with the device at
        // the endpoint ID

        Toast.makeText(this, "Found Device: " + serviceId + ", " + endpointName + ". Start Connection Try", Toast.LENGTH_SHORT).show();
        connectTo(endpointId, endpointName);
    }

    private void connectTo(String remoteEndpointId, final String endpointName) {
        // Send a connection request to a remote endpoint. By passing 'null' for
        // the name, the Nearby Connections API will construct a default name
        // based on device model such as 'LGE Nexus 5'.
        tv_status.setText("Connecting");

        String myName = null;
        byte[] myPayload = null;
        Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
                remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {
                    @Override
                    public void onConnectionResponse(String remoteEndpointId, Status status,
                                                     byte[] bytes) {
                        if (status.isSuccess()) {
                            // Successful connection
                            tv_status.setText("Connected to " + endpointName);
                            globalRemoteEndpointId = remoteEndpointId;

                        } else {
                            // Failed connection
                            tv_status.setText("Connecting failed");
                        }
                    }
                }, this);
    }

    @Override
    public void onConnectionRequest(final String remoteEndpointId, String remoteDeviceId,
                                    final String remoteEndpointName, byte[] payload) {
        if (mIsHost) {
            byte[] myPayload = null;
            // Automatically accept all requests
            Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId,
                    myPayload, this).setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        String statusS = "Connected to " + remoteEndpointName;
                        Toast.makeText(c, statusS,
                                Toast.LENGTH_SHORT).show();
                        tv_status.setText(statusS);
                        globalRemoteEndpointId = remoteEndpointId;
                    } else {
                        String statusS = "Failed to connect to: " + remoteEndpointName;
                        Toast.makeText(c, statusS,
                                Toast.LENGTH_SHORT).show();
                        tv_status.setText(statusS);
                    }
                }
            });
        } else {
            // Clients should not be advertising and will reject all connection requests.
            Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId);
        }
    }

    @Override
    public void onMessageReceived(String endpointId, byte[] payload, boolean b) {
        String message = payload.toString();
        Toast.makeText(this, "Received from " + endpointId + ": " + message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {
        tv_status.setText("Connection suspended because of " + i);

        mGoogleApiClient.reconnect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        tv_status.setText("Connection Failed");
    }


    @Override
    public void onEndpointLost(String s) {
        tv_status.setText("Endpoint lost: " + s);
    }



    @Override
    public void onDisconnected(String s) {
        tv_status.setText("Disconnected: " + s);
    }

    public void checkPermisson(){
        Toast.makeText(c, "Check permission", Toast.LENGTH_SHORT).show();

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, MY_PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Toast.makeText(c, "Permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(c, "Permission not granted, app may fail", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        }
    }
}
package com.example.steffen.nearbyconnectionsdemo;
公共类MainActivity扩展活动实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
View.OnClickListener,
Connections.ConnectionRequestListener,
Connections.MessageListener,
Connections.EndpointDiscoveryListener{
//确定设备是否为主机
私有布尔值mIsHost=false;
GoogleAppClient MgoogleAppClient=null;
按钮bt_广告,bt_搜索,bt_发送;
text查看电视节目状态;
复选框;
上下文c;
字符串globalRemoteEndpointId=“”;
编辑文本编辑文本;
最终int MY_PERMISSIONS_REQUEST=666;
私有静态int[]网络类型={ConnectivityManager.TYPE\u WIFI,
ConnectionManager.TYPE_ETHERNET};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c=这个;
checkPermisson();
editText=(editText)findViewById(R.id.editText);
bt_ad=(按钮)findviewbyd(R.id.bt_ad);
bt_ad.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
bt_search.setEnabled(false);
开始转换();
}
});
bt_搜索=(按钮)findViewById(R.id.bt_搜索);
bt_search.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
startDiscovery();
}
});
bt_send=(按钮)findviewbyd(R.id.bt_send);
bt_send.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
String message=“message:+editText.getText().toString();
Toast.makeText(c,“发送:+消息,Toast.LENGTH_SHORT).show();
字节[]有效负载=message.getBytes();
sendReliableMessage(mgoogleapClient、globalRemoteEndpointId、负载);
}
});
tv_status=(TextView)findViewById(R.id.tv_status);
复选框=(复选框)findViewById(R.id.checkBox);
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(附近的.CONNECTIONS\u API)
.build();
getWindow().addFlags(WindowManager.LayoutParams.FLAG\u保持屏幕打开);
}
私有布尔值已连接到网络(){
连接管理器连接管理器=
(ConnectionManager)getSystemService(Context.CONNECTIVITY_服务);
用于(int网络类型:网络类型){
NetworkInfo=connManager.getNetworkInfo(networkType);
if(info!=null&&info.isConnectedOrConnecting()){
返回true;
}
}
返回false;
}
私有无效开始转换(){
如果(!isconnectedtonework()){
//当设备未连接到网络时实现逻辑
tv_status.setText(“无网络”);
返回;
}
//确定此设备是主机
mIsHost=true;
checkBox.setChecked(mIsHost);
//使用AppIdentifier进行广告可以让其他设备
//网络发现此应用程序并提示用户
//安装应用程序。
List appIdentifierList=新建ArrayList();
add(新的AppIdentifier(getPackageName());
AppMetadata AppMetadata=新的AppMetadata(appIdentifierList);
//广告超时设置为无限期运行
//正值表示以毫秒为单位的超时
长时间无超时=0L;
字符串名称=null;
附近.Connections.startAversising(mGoogleApiClient,name,appMetadata,无超时,
setResultCallback(new ResultCallback()){
@凌驾
public void onResult(Connections.StartAdvertisingResult){
if(result.getStatus().issucess()){
//这个设备正在做广告
tv_status.setText(“广告”);
}否则{
int statusCode=result.getStatus().getStatusCode();
//广告失败-有关更多详细信息,请参阅状态代码
tv_status.setText(“错误:+statusCode”);
}
}
});
}
私有无效开始发现(){
如果(!isconnectedtonework()){
//当设备未连接到网络时实现逻辑
tv_status.setText(“无网络”);
返回;
}
String serviceId=getString(R.String.service\u id);
//以毫秒为单位设置适当的超时长度
长发现超时=1000L;
//发现附近正在使用所需服务ID进行广告的应用程序。
附近.Connections.startDiscovery(mGoogleApiClient,serviceId,DISCOVER\u TIMEOUT,this)
.setResultCallback(新的ResultCallback(){
@凌驾
公开结果无效(状态)