Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.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 6.0权限_Android_Android Service - Fatal编程技术网

如何从服务中检查新的android 6.0权限

如何从服务中检查新的android 6.0权限,android,android-service,Android,Android Service,我有一个Android 6.0应用程序,它有一个未绑定的Android服务连接到googleapi,用于接收融合的API位置提供者更新。为此,我需要访问\u罚款\u位置权限。 在升级到棉花糖之前,一切正常。现在我需要为我的应用程序实现新的权限模型 我已经读到,不可能直接从服务中检查android 6.0权限 我所有的位置更新接收器和谷歌APi客户端连接部分都由服务处理,并且在服务中处理,我将链接以保持它在那里 是否可以在活动中检查一次权限,然后在服务启动时将其移交给服务,并且权限在服务的生命周期

我有一个Android 6.0应用程序,它有一个未绑定的Android服务连接到googleapi,用于接收融合的API位置提供者更新。为此,我需要访问\u罚款\u位置权限。 在升级到棉花糖之前,一切正常。现在我需要为我的应用程序实现新的权限模型

我已经读到,不可能直接从服务中检查android 6.0权限

我所有的位置更新接收器和谷歌APi客户端连接部分都由服务处理,并且在服务中处理,我将链接以保持它在那里

是否可以在活动中检查一次权限,然后在服务启动时将其移交给服务,并且权限在服务的生命周期内保留在服务中?或者我必须检查每个LocationUpdate的权限吗

我该如何执行我的服务的权限检查?有人做过吗?你能给我一个实施的例子吗

“我的活动”中的新权限检查已经开始工作(如StackOverflow中的一些示例所述),但是当我的服务正在执行所有LocationUpdate时,它是如何工作的

ok update:这就像是我的活动中出现的一样,但我仍然收到一个错误,因为我只是在我的活动中检查。如何让我的服务部件了解权限

我的错误消息:

05-30 15:59:24.035 4261-4261/com.pekam E/谷歌APi客户端﹕ 谷歌 APi连接失败。 java.lang.SecurityException:客户端必须具有访问\u粗略\u位置或访问\u精细\u位置的权限才能执行 任何位置操作

我的活动代码:

服务类别代码:

公共类MyService extends服务实现GoogleAppClient.ConnectionCallbacks、GoogleAppClient.OnConnectionFailedListener、LocationListener、AsyncDelegate{
//带有轨迹和所有内容的CurrentUser对象
public static TblUser user=new TblUser();
公共静态布尔数据刷新=false;
private IBinder mBinder=new MyBinder();
私有静态最终整数请求\u精细位置=0;
私人通知经理nm;
专用计时器=新计时器();
private LocationRequest MLLocationRequest=新位置请求();
私有字符串strLOG=“LOG”;
私人互联网连接检测器cd;
私有布尔值存在;
//谷歌客户端
私人GoogleapClient GoogleapClient;
@凌驾
已更改位置上的公共无效(位置){
位置mCurrentLocation=位置;
试一试{
TblGps gps1=新的TblGps();
gps1.setLat(mCurrentLocation.getLatitude());
gps1.setLng(mCurrentLocation.Get经度());
gps1.setDate(新时间戳(new Date().getTime());
setProvider(mCurrentLocation.getProvider());
gps1.setDeviceID(“1”);
user.getTracks().get(0.getTblgps().add(gps1);
Log.i(“onLocationChanged”,“new Lat:+gps1.getLat()+”,Lng:+gps1.getLng());
Toast.makeText(这是“添加了新位置的位置”,Toast.LENGTH_SHORT.show();
}捕获(例外e){
e、 printStackTrace();
}最后{
}
}
@凌驾
公共无效onConnectionFailed(ConnectionResult捆绑包){
}
@凌驾
未连接的公共空间(捆绑包){
Log.i(“未连接”、“GoogleapClient”);
试一试{
Toast.makeText(此“位置服务已连接”,Toast.LENGTH_SHORT).show();
createLocationRequest();
LocationServices.FusedLocationApi.RequestLocationUpdate(
GoogleAppClient、mLocationRequest、this);
LocationServices.FusedLocationApi.getLastLocation(GoogleAppClient);
}catch(Throwable t){//您应该始终最终捕获计时器任务中的所有异常。
Log.e(“谷歌APi客户端”,“谷歌APi连接失败”,t);
}
}
@凌驾
公共空间连接暂停(int i){
}
//服务
@凌驾
public void onCreate(){
super.onCreate();
cd=新的InternetConnectionDetector(getApplicationContext());
isInternetPresent=cd.isConnectingToInternet();
Log.i(“MyService”,“服务已启动”);
showNotification();
getUserObject();
timer.scheduleAtFixedRate(新TimerTask(){
公开募捐{
onTimerTick();
}
},60000,19000升);
试一试{
GoogleapClient=新的GoogleapClient.Builder(此)
.addApi(LocationServices.API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
googleApiClient.connect();
}捕获(例外e){
e、 printStackTrace();
}最后{
}
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Log.i(“MyService”,“接收到的启动id”+startId+:“+intent”);
返回START_STICKY;//运行直到显式停止。
}
@凌驾
公共空间{
共享参考文献;
mPrefs=PreferenceManager.getDefaultSharedReferences(此参数);
SharedReferences.Editor prefsEditor=mPrefs.edit();
Gson Gson=新的Gson();
字符串json=gson.toJson(用户);
putString(“MyObject”,json);
提交();
super.ondestory();
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
//异步任务委托
@凌驾
public void executionFinished(HttpRequestTaskGetUser用户任务){
String name=userTask.result.getName();
Log.i(“executionFinishedGet”,名称);
Toast.makeText(此“位置执行完成
@Override
    protected void onStart() {
        super.onStart();
        loadPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_FINE_LOCATION);
        if (com.pekam.util.MyAppSettings.isMyServiceRunning(MyService.class, this)) {
            Intent intent = new Intent(this, MyService.class);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        } else {
            Intent intent = new Intent(this, MyService.class);
            startService(intent);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }




private void loadPermissions(String perm,int requestCode) {
        if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, perm)) {
                ActivityCompat.requestPermissions(this, new String[]{perm},requestCode);
            }
        }
    }
public class MyService  extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener,AsyncDelegate {

    //CurrentUser Object with tracks & everything
    public static TblUser user = new TblUser();
    public static boolean dataRefresh=false;

    private IBinder mBinder = new MyBinder();


    private static final int REQUEST_FINE_LOCATION=0;

    private NotificationManager nm;
    private Timer timer = new Timer();


    private LocationRequest mLocationRequest = new LocationRequest();

    private String strLOG = "LOG";

    private InternetConnectionDetector cd ;
    private Boolean isInternetPresent;





    //GoogleApiClient
    private GoogleApiClient googleApiClient;
    @Override
    public void onLocationChanged(Location location) {
        Location mCurrentLocation = location;

        try {

            TblGps gps1 = new TblGps();
            gps1.setLat(mCurrentLocation.getLatitude());
            gps1.setLng(mCurrentLocation.getLongitude());
            gps1.setDate(new Timestamp(new Date().getTime()));
            gps1.setProvider(mCurrentLocation.getProvider());
            gps1.setDeviceID("1");

            user.getTracks().get(0).getTblgps().add(gps1);
            Log.i("onLocationChanged","new Lat:" + gps1.getLat() +", Lng:"+ gps1.getLng());
            Toast.makeText(this, "Location  new Location Added", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult bundle) {

    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.i("onConnected", "GoogleApiClient");
        try {
            Toast.makeText(this, "Location  service connected", Toast.LENGTH_SHORT).show();

            createLocationRequest();
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    googleApiClient, mLocationRequest, this);
            LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

        } catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
            Log.e("Google APi Client", "Google APi Connected Failed.", t);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    //Service
    @Override
    public void onCreate() {
        super.onCreate();
        cd = new InternetConnectionDetector(getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        Log.i("MyService", "Service Started.");

        showNotification();

        getUserObject();

        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                onTimerTick();
            }
        }, 60000, 19000L);

        try {
            googleApiClient = new GoogleApiClient.Builder(this)

                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)

                    .build();

            googleApiClient.connect();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    @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.
    }

    @Override
    public void onDestroy() {
        SharedPreferences mPrefs;
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(user);
        prefsEditor.putString("MyObject", json);
        prefsEditor.commit();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    // Async Task delegate
    @Override
    public void executionFinished(HttpRequestTaskGetUser userTask) {
        String name= userTask.result.getName();
        Log.i("executionFinishedGet",name);
        Toast.makeText(this, "Location  executionFinishedGet", Toast.LENGTH_SHORT).show();

    }
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

//            ActivityCompat.requestPermissions(this,
//                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION},
//                    REQUEST_FINE_LOCATION);

        } else {

        }
    }
    @Override
    public void executionFinished(HttpRequestTaskSaveUser userTask) {
        String name= userTask.result.getName();
        Log.i("executionFinishedSave", name );
        Toast.makeText(this, "Location  executionFinishedGet", Toast.LENGTH_SHORT).show();
    }
    private void getUserObject() {
         try {
            if (isInternetPresent){
                HttpRequestTaskGetUser  http = new HttpRequestTaskGetUser();
                http.delegate=this;
                http.execute(user);
                }

        } catch (Throwable t) {
            Log.e("getuserObject", "getuserObject Failed.", t);
        }
    }

    private void saveUserObject() {
        try {

        if (isInternetPresent) {
            HttpRequestTaskSaveUser http = new HttpRequestTaskSaveUser();
            http.delegate=this;
            http.execute(this.user);
        }
    } catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
                    Log.e("saveUserObject", "saveUserObject Failed.", t);
           }
    }





    public boolean isRunning()
        {
            return isMyServiceRunning(this.getClass());
        }
    private void onTimerTick() {

            try {
                saveUserObject();
                Log.i("TimerTick", "Saved User." );
            } catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
                Log.e("TimerTick", "Timer Tick Failed.", t);            
            }
        }
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
          //  GooglePlayServicesUtil.getErrorDialog(status, t, 0).show();
            return false;
        }
    }
    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.ic_launcher, text, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TabBarActivity.class), 0);
        // Set the info for the views that show in the notification panel.
     //  notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);



        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this);
        notification = builder.setContentIntent(contentIntent)
               .setSmallIcon(R.drawable.ic_launcher).setTicker(text)//.setWhen(java.util.)
                .setAutoCancel(true)//.setContentTitle(title)
                .setContentText(text).build();
        nm.notify(1, notification);

         //  notification.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);
    }
    private void createLocationRequest() {

        mLocationRequest.setInterval(20000);
        mLocationRequest.setFastestInterval(10000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
    }
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)   {
                givePerMisson();
            } else {
                requestIntent();
            }
 @TargetApi(Build.VERSION_CODES.M)
private void givePerMisson() {
    if ((AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) &&
            AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.CALL_PHONE) &&
            AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
            AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.GET_ACCOUNTS) &&
            AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) &&
            AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.CAMERA)
    )) {
        requestIntent();
    } else {
        AndyUtils.givePermisson(SplashActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION, AndyUtils.PERMISSOIN);
        AndyUtils.givePermisson(SplashActivity.this, Manifest.permission.CALL_PHONE, AndyUtils.PERMISSOIN);
        AndyUtils.givePermisson(SplashActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, AndyUtils.PERMISSOIN);
        AndyUtils.givePermisson(SplashActivity.this, Manifest.permission.ACCESS_FINE_LOCATION, AndyUtils.PERMISSOIN);
        AndyUtils.givePermisson(SplashActivity.this, Manifest.permission.GET_ACCOUNTS, AndyUtils.PERMISSOIN);
        AndyUtils.givePermisson(SplashActivity.this, Manifest.permission.CAMERA, AndyUtils.PERMISSOIN);
        if (!AndyUtils.permissionsList.isEmpty()) {
            requestPermissions(AndyUtils.permissionsList.toArray(new String[AndyUtils.permissionsList.size()]), AndyUtils.PERMISSOIN_CODE);
        }
    }

}
 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case AndyUtils.PERMISSOIN_CODE: {
            if ((AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) &&
                    AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.CALL_PHONE) &&
                    AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
                    AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.GET_ACCOUNTS) &&
                    AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) &&
                    AndyUtils.checkPermission(SplashActivity.this, Manifest.permission.CAMERA)
            )) {
                requestIntent();
            } else {
                finish();
            }
        }
    }
}
  public static boolean checkPermission(Context context, String permission) {
try {
    PackageManager pm = context.getPackageManager();
    if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
    }

} catch (Exception e) {
    Log.e("PermissionError", e.toString());
}
return false;
}
public static void givePermisson(Context context, String permisson, String permissonType) {
    int per = context.checkSelfPermission(permisson);
    if (per != PackageManager.PERMISSION_GRANTED) {
        permissionsList.add(permisson);

    } else if (per != PackageManager.PERMISSION_DENIED) {
    }
}
private void showPermissionDialog() {
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(mActivity,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_FOR_LOCATION);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
    }
}